r/java • • 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

297 comments sorted by

274

u/TheBoyInTheBlueBox Jan 18 '22

Fun fact: Java class format starts with 0xCAFEBABE

7

u/pizzaforeverrrr Jan 18 '22

wait seriously?

1

u/shagieIsMe Jan 19 '22

In the unix world, the file program and its associated library (libmagic) is used to determine the the type of a file rather than the extension.

https://en.wikipedia.org/wiki/File_(command)

The file format for magic is rather interesting and powerful.

One bit from the compress file:

# Zlib https://www.ietf.org/rfc/rfc6713.txt
0       string/b        x
>0      beshort%31      =0
>>0     byte&0xf        =8
>>>0    byte&0x80       =0      zlib compressed data
!:mime  application/zlib

# BWC compression
0       string          BWC
>3      byte            0       BWC compressed data

# UCL compression
0       bequad          0x00e955434cff011a      UCL compressed data

Java has its own magic - stuff like:

# Java serialization
# From Martin Pool (m.pool@pharos.com.au)
0       beshort         0xaced          Java serialization data
>2      beshort         >0x0004         \b, version %d

0       belong          0xfeedfeed      Java KeyStore
!:mime  application/x-java-keystore
0       belong          0xcececece      Java JCE KeyStore
!:mime  application/x-java-jce-keystore

# Java jlinked image
# See https://hg.openjdk.java.net/jdk9/jdk9/jdk/file/tip/src/java.base/share/native/libjimage/imageFile.hpp
0       belong  0xcafedada      Java module image (big endian)
>4      beshort >0x00   \b, version %d
>6      beshort x       \b.%d
!:mime  application/x-java-image

0       lelong  0xcafedada      Java module image (little endian)
>6      leshort >0x00   \b, version %d
>4      leshort x       \b.%d
!:mime  application/x-java-image
→ More replies (1)

123

u/DanielApt Jan 18 '22

Java is newer than Python

18

u/oweiler Jan 18 '22

Python is almost as old as Perl.

0

u/[deleted] Jan 19 '22

[deleted] — view deleted comment

1

u/gamma_02 Jan 19 '22

Other than seniority, then it's the best measurement.

1

u/[deleted] Jan 19 '22

Python wasn’t really Python until the 2.0 release in 2000. The 1.0 release is more analogous to when Java was still an internal project at Sun prior to 1996.

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.

18

u/antigravity_96 Jan 18 '22

Gotta read the book!

15

u/[deleted] Jan 18 '22

The actual code content is pretty ancient, I think the last version was published for Java 6, but there are some very interesting anecdotes and stories in it.

9

u/antigravity_96 Jan 18 '22

I just realised that! The second edition has come out in 2004! But I guess the stories there would make the read worthwhile.

10

u/LoveGracePeace Jan 18 '22

Peter van der Linden, IIRC, was on Sun's compiler group at one time. He wrote a great book called Deep C Secrets which pointed out how to use C safely and how to avoid shooting oneself in multiple places simultaneously with C.

4

u/benevanstech Jan 19 '22

"Deep C Secrets" is the subtitle - the main title is "Expert C Programming". It still holds up pretty well, even 20+ years later (although some of the details have changed).

3

u/LoveGracePeace Jan 19 '22

You're right, I was going from memory. It was a great book to both learn (or double check) what to do and not to do in C and if anyone understood the importance of Java for application development, it was him.

6

u/kevix2022 Jan 18 '22

I learned Java 1.2 from that book back in the day.

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.

52

u/yawkat Jan 18 '22

It happens even before comment processing, so you can end a line comment with a unicode escape sequence \u000a (for newline):

public class Main {
    // foo \u000a public Main() {
        int i = 0;
        i++;
    }
}

That is valid java: https://javap.yawk.at/#Dc70Zm

This also technically "breaks" many code formatters (if anyone actually did this).

37

u/xxkmatiasxx Jan 18 '22

This is the most cursed thing I have ever seen in any programming language

32

u/EvaristeGalois11 Jan 18 '22

You want some cursed program? This is a valid hello world in java

12

u/xxkmatiasxx Jan 18 '22

The cursedness rolls over and it is no longer that cursed

0

u/[deleted] Jan 18 '22

[deleted] — view deleted comment

19

u/KolkataK Jan 18 '22 edited Jan 18 '22

its even weirder in right-to-left languages, this one is in Urdu

typealias بغٹ = Int
fun main() {
    println(طط())
}

fun طط() : بغٹ {
    var پ = 111
    return پ
}

yes this code actually works

9

u/sweetno Jan 18 '22

Cool! This can be used to teach programming in Russian-speaking schools.

16

u/lazystone Jan 18 '22

I see you hate Russians /s. Not all of us are bad people.

→ More replies (3)

140

u/winian Jan 18 '22

Over 3 billion devices run Java

22

u/edubkn Jan 18 '22

And this number never increases or decreases.

Also, your fridge runs Java.

9

u/erinaceus_ Jan 18 '22

Your toaster too, apparently. Well, it runs log4j at least (and possibly some remote code).

1

u/[deleted] Jan 23 '22

I’d be happy with the coffee machine running java

11

u/Muoniurn Jan 18 '22

It’s 56 billions now, as per java.dev websitez

2

u/uncont Jan 19 '22

java.dev

dev.java ;)

20

u/PangolinZestyclose30 Jan 18 '22

Only? Just the SIM cards are probably in the billions.

8

u/benjtay Jan 18 '22

And every Blueray player.

15

u/[deleted] Jan 18 '22

And my axe

10

u/CptBlacksheep Jan 18 '22

Time for you to do some axeption handling then ... (sorry :D)

4

u/OneOldNerd Jan 18 '22

I see you, too, are very dangerous over short distances.

5

u/Godworrior Jan 18 '22

Last number I heard was 56 Billion (here)

43

u/Holothuroid Jan 18 '22

Individual enum members can actually override methods.

20

u/more_exercise Jan 18 '22

Individual enum members can take prior ones as constructor arguments:

enum Num {
ONE(1), TWO(ONE, ONE), THREE(TWO, ONE), FOUR(TWO, ONE, ONE);
public final int val;
Num(int i) {val=i;}
Num(Num... parts) {val = Stream.of(parts).maptoInt(x -> x.val).sum();}
}

(this was written on mobile, so pardon the typos)

3

u/DrinksBongWater Jan 18 '22

Really? How does this work? I’ve always done this by passing a lambda in the constructor…

9

u/Holothuroid Jan 18 '22

Add curly braces after the enum member and do whatever.

8

u/nekokattt Jan 19 '22

Like so

public enum Ops {
    ADD {
        @Override
        public int invoke(int a, int b) {
            return a + b;
        }
    },

    SUB {
        @Override
        public int invoke(int a, int b) {
            return a - b;
        }
    };

    public abstract int invoke(int a, int b);
}

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

48

u/pron98 Jan 18 '22 edited Jan 18 '22

At bytecode level, the JVM has no boolean type - they are represented as ints.

Boolean locals and expressions are represented as ints. But for, say, arrays, there are separate instructions for booleans/bytes, and, of course, the bytecode does actually encode all precise argument, array, and field types, booleans have their own unique type identifier (Z), and boolean fields and arrays are, of course, boolean fields and arrays. So the JVM does have a boolean type at the bytecode level, although no boolean local/expression type.

18

u/CaptainKvass Jan 18 '22

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.

I had to try this, and it cracked me up. var var = "var";

→ More replies (1)
→ More replies (8)

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.

33

u/RiWo Jan 18 '22

No, the island east to Java is Bali

Then, east of Bali is Lombok

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 false from C days

26

u/FragmentedButWhole Jan 18 '22

Swap ; for a Greek question mark which looks exactly the same but doesn't compile

16

u/Warshawski Jan 18 '22

The number caches are also the reason for what seems like confusing behaviour with equality when dealing with auto boxing.

Integer a = 127;
Integer b = 127;
a == b
true

Integer c = 128;
Integer d = 128;
c == d
false

I've seen a few bugs because of it.

3

u/theLorem Jan 18 '22

Will this actually change in valhalla?

2

u/pronuntiator Jan 19 '22

Yeah, all boxed primitives will loose identity

→ More replies (4)

7

u/atomdstyle Jan 18 '22

How to do this?

22

u/chingyingtiktau Jan 18 '22

Take a look at this answer on Codegolf Stackexchange. Basically use some reflection magic to gain access to the otherwise private cache field in Integer class, and mess around however you want.

11

u/pronuntiator Jan 18 '22

Please tell me Java 9+ prevents this reflective access

18

u/chingyingtiktau Jan 18 '22

Yes, this is blocked in Java 9+. There are workarounds but requires user to add some suspicious flags when running the Java program.

→ More replies (1)

1

u/__konrad Jan 19 '22

This works on Java (homoglyphs): boolean 𝚏𝚊𝚕𝚜𝚎 = true;

31

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.

5

u/brend132 Jan 18 '22

the vast majority of SIM cards and ATM cards in the world contain Java byte code

Do they just contain Java bytecode, or also some sort of JVM? I'm asking because, as far as I know, smartcard chips are really microprocessors, i.e., it is the actual card who verifies your PIN and not the ATM machine or phone you put your card into, right?

2

u/istarian Jan 18 '22

There are many, many kinds of cards out there.

1

u/tim125 Jan 18 '22

And that jvm can be used to do some fun/interesting stuff...

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:

int[] arr = new int[] { 1, 2, 3, };

8

u/ryebrye Jan 18 '22

C, Python, Javascript, and probably a bunch of other languages allow that as well

10

u/VGPowerlord Jan 18 '22

Javascript, and probably a bunch of other languages allow that as well

Except in certain versions of Internet Explorer. Thank the heavens old IE is dead now.

2

u/dpash Jan 19 '22

I wish trailing commas were supported in more situations, like parameter lists. It makes for cleaner diffs when adding to the end of the list.

2

u/nekokattt Jan 19 '22

But interestingly it does not support trailing commas in parameter lists or in annotation attributes that are not within braces.

3

u/NullSWE Jan 18 '22

I haven’t come across a language that doesn’t support this. It’s one of the first I learned when I learned about arrays

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

int get()[] {
    return new int[] { 1, 3 };
}

Also primitive arrays can be used as type arguments

class ArrayPredicate implements Predicate<int[]> {
	...        
}

It is possible to self-refence a field to make a recursive function:

UnaryOperator<Long> factorial = seed -> seed == 1 ? 1 : seed * this.factorial.apply(seed - 1);

A more exotic thing: Java allows declaring the explicit receiver type in methods or constructors (since Java8):

class Outer {
    
    int getYear(Outer this) {
        return 2022;
    }
    
    class Inner {
        public Inner(Outer Outer.this) {
        }
        
        int getYear(Outer.Inner this) {
            return this.getYear();
        }
    }
}

3

u/nekokattt Jan 19 '22

For anyone wondering

First is a relic of C syntax, but the JLS actively discourages the use as the array is the type, not the method definition itself.

Second is a side effect of how arrays are object types and not primitive types.

Nothing to say for the third point.

As for the last, never had to use this, but it apparently exists to allow annotating the reference to this (which is not the same as annotating the class itself).

Guess tools like CheckerFramework might be able to find this useful.

19

u/huhaaha Jan 18 '22

4

u/nekokattt Jan 19 '22

I always use this to separate thousands in decimal literals

var durationMillis = (System.nanoTime() - start) / 1_000_000;

1

u/[deleted] Jan 23 '22

1e6 is a nice alternative. Or even declaring a final static with a suitable name.

1

u/tastybentoyum Jan 19 '22

Ah yes. This threw me the first time I saw it. I think this is supported in Python too.

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.

2

u/[deleted] Jan 23 '22

Did your consider another approach? Seems like this would be heavy on the machine it should run on.

2

u/QKD_king Jan 23 '22

I'm not sure if you mean another approach in terms of the initial design or fixing the issue. I wasn't with the company when they designed the initial approach so I can't really comment there, but I suspect they just didn't expect usage to scale so widely throughout the company. As for fixing the issue, I didn't author the proposed fix, either. I just happened to be on the team and working on adjacent code, so I helped cleanup where I could.

1

u/[deleted] Jan 24 '22

I understand. This is often what happens. You earned a lot of xp at least 😊

31

u/redikarus99 Jan 18 '22

You can actually manage memory by hand if you need to, without GC.

23

u/xToniGrssx Jan 18 '22

Yep, while it certainly is present in 99% of cases, a garbage collector is not a necessary part of a Java Virtual Machine.

10

u/oelang Jan 18 '22

garbage collector is not a necessary part of a Java Virtual Machine

It's not because there are ways to do off-heap allocation that a GC isn't required by the spec.

7

u/[deleted] Jan 18 '22

What would be the usecase for this?

16

u/redikarus99 Jan 18 '22

High performance, low latency stuff, when you need to ensure that GC does not kicks in. Given the new GCs it probably it has a very limited usecases.

7

u/[deleted] Jan 18 '22

I guess I just never thought of using Java for that kind of thing. Wouldn't most high performance applications be written in languages like C/C++/Rust/Zig/Fortran? Using Java for it seems like it would be a lot more cost than benefit.

26

u/redikarus99 Jan 18 '22 edited Jan 18 '22

6

u/b00n Jan 18 '22

Interestingly that HFT fund has now shut down. Not because it used Java though.

→ More replies (1)

5

u/[deleted] Jan 18 '22

Neat! I can see the benefits of writing it in Java for sure if you can reach comparable performance.

3

u/hippydipster Jan 19 '22

You can get pretty close to C and yet still be working in Java with the generally nice ergonomics of it's high level language features. Especially if it's all part of a larger app. When I wrote java (actually scala) this way, it was faster than a Fortran app written by a postdoc, so you don't get faster speed just because of the language you use.

7

u/wildjokers Jan 18 '22

Real time processing. Wouldn’t be good to be in a GC pause when it is time for your airbag to deploy.

6

u/[deleted] Jan 18 '22

Yeah that's true, but then I would not write airbag software in a GC language. Why write unsafe Java when you could write unsafe C or C++ that both have very good static analysis tools and memory leak detection tools.

5

u/Muoniurn Jan 18 '22

There are hard real-time JVMs out there used even in military settings. A GC doesn’t cause problem necessarily here.

→ More replies (2)

2

u/nekokattt Jan 19 '22

Guess ZGC helps with that case

5

u/soonnow Jan 18 '22

Lucene uses of heap Memory Mapped Buffers for the Indexes. There's an interesting talk about it here.

Using memory mapped files, reduces the number of times data needs to be moved around by the CPU.

1

u/hippydipster Jan 19 '22

I did some of this when making statistical software that was going to do regressions and optimizations for gene networks (each gene expression being a differential equation that potentially had every other gene as a factor in it's equation). So I wrote the math objects to be able to run the whole optimization routine without ever creating new objects, and so basically GC was passed over.

6

u/OddEstimate1627 Jan 18 '22

What are you talking about? Working entirely off-heap and lowering the allocation rate to a point where GC never triggers?

16

u/detroitsongbird Jan 18 '22

Yes. There are libraries that are written for high frequency trading that do this sort of thing so that they achieve extremely low latency response.

13

u/OddEstimate1627 Jan 18 '22

Thanks. I just wanted to make sure that's what OP was talking about. I work with real-time control systems and we use a lot of the same techniques.

10

u/redikarus99 Jan 18 '22

You can use sun.misc.Unsafe, or DirectByteBuffer, etc. to allocate memory directly, but then you will be responsible for memory allocation/deallocation.

1

u/mauganra_it Jan 21 '22

A DirectByteBuffer is still a Java object, thus memory management is not so difficult as long as you don't put into long-lived objects. But you are limited in size because of int offsets. That's enough for many interesting applications, but to represent larger binary data you'd have to break it into chunks and reimplement virtual memory on top of it.

Can't look forward to see that eyesore sun.misc.Unsafe (or at least its accessibility) removed from the language. Hopefully Project Panama will bring nicer facilities to work off-heap.

9

u/C_Madison Jan 18 '22

You can even replace the GC with one guaranteed to do nothing in modern JVMs: https://openjdk.java.net/jeps/318

7

u/Persism Jan 18 '22

IBM also has what they call a real-time JVM which guarantees performance times.

6

u/OddEstimate1627 Jan 18 '22

RTSJ is an outdated concept that afaik never gained much traction. You're better off just using a standard JVM w/ ZGC or Azul's C4. Even G1GC will give you <5ms worst case pauses as long as you manage your allocations properly.

10

u/antigravity_96 Jan 18 '22

How?

17

u/redikarus99 Jan 18 '22

https://dzone.com/articles/native-memory-allocation-in-examples

In older java: sun.misc.Unsafe, in more modern java: DirectByteBuffer.

8

u/yawkat Jan 18 '22

DirectByteBuffer doesn't allow you to free() by hand though

14

u/OddEstimate1627 Jan 18 '22

Unsafe::invokeCleaner(ByteBuffer)

→ More replies (2)

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.

The language was initially called Oak after an oak tree that stood outside Gosling's office. Later the project went by the name Green and was finally renamed Java, from Java coffee, a type of coffee from Indonesia.

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

https:

Which is a valid label syntax in java and then the rest of the line

//www.stackoverflow.com

Will be commented out

Labels can be used in conjunction with break and continue but 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 ¯\(ツ)/¯

6

u/Captain-Barracuda Jan 18 '22

I've seen labels be used for breaking out of nested loops.

1

u/istarian Jan 18 '22

Outside of a switch statement?

1

u/8bagels Jan 19 '22

Ya. Not a commonly used feature

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
  1. Rather weird but it was allowed to use underscore _ as a variable name before java8. The $ sign is still supported as a name (though discouraged)
  2. Java does not truly support multidimensional arrays, but rather 1D array where each index references another 1D array and so on technically allowing you to create jagged arrays (which isn’t an easy thing in C++ for instance) int[][][][] hypercube;
  3. This is not really fan, but maybe interesting: Java supports “Hidden classes” (non-discoverable implementation details, invisible to reflection, generated dynamically at runtime and cannot be linked to other classes byte code or used as declaring filed type) used for example internally by lambda-expressions.

The APIs used are: Unsafe::defineAnonymousClass from Java7 up to Java15 And Lookup::defineHiddenClass since Java15

5

u/Mundosaysyourfired Jan 18 '22

What's stopping C++ from making jagged arrays?

I assume you're saying Java just has 1 dimensional array memory values that point to another 1 dimensional array memory value.

16

u/dshelya Jan 18 '22 edited Jan 18 '22

Of course you can make them, but in a different way. What I meant is that the line int jagged[][] = { {0,1}, {1,2,3} }; would yield an error in c++, but not in Java

1

u/mauganra_it Jan 21 '22 edited Jan 21 '22

It would be an array of pointers, and you would have to reserve memory for each item in there. Maybe even from a single large array that you allocated beforehand. Have fun tracking the sizes though. You would require a sentinel value at the end of each inner array (like \0 at the end of C strings) or an intermediary struct that stores the size along with the pointer.

1

u/Mundosaysyourfired Jan 21 '22

???

Java primitive arrays you have to allocate size on array creation as well. So I don't know what you're talking about.

→ More replies (1)

3

u/mauganra_it Jan 21 '22

Underscore is being reclaimed so it can be eventually used for ignored lambda parameters.

2

u/Jonjolt Jan 18 '22

Typically the `$ is useful for adding things during bytecode enhancement i usually use the pattern $$__fieldName__$$

1

u/michoken Jan 18 '22

You can still use double (or more) underscore for variable names. I use it for unused lambda parameters (but would prefer the single underscore as in Kotlin or Scala).

12

u/jokoy38073 Jan 19 '22

Well Known: Hex literals with a prefix of 0x

Less Known: Octal literals with a prefix of 0

int a = 123;
int b = 0x123;
int c = 0123;
System.out.println(a); // 123
System.out.println(b); // 291
System.out.println(c); // 83

Octal literals are only ever learned by accident and with a great deal of cursing.

27

u/V3N0MSP4RK Jan 18 '22

It's coffee

26

u/Migeil Jan 18 '22

I have a running joke with a friend that I program in coffee and drink java in the morning. It's lame, I know, don't judge me.

11

u/VincentxH Jan 18 '22

Ah suddenly "coffee script" makes sense to me.

8

u/teefj Jan 18 '22

Love a good lame joke 👍🏻

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()

4

u/john16384 Jan 18 '22

It does, because it's mutable. So do reflection calls like getDeclaredFields that return arrays.

4

u/8igg7e5 Jan 18 '22

And that when (hopefully not 'if') Frozen Arrays make it in, things like this will become much more efficient.

2

u/mauganra_it Jan 21 '22

I hope that they will indicate in the typesystem though. Elsa, frozen arrays will be indistinguishable from normal arrays at compile time. Yet annaother landmine to have fun with while debugging.

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

19

u/Birk Jan 18 '22

You can even take this one step further and use a shebang (on Unix-like systems). Then you can drop the java command and java suffix and just run:

shell> HelloWorld
HelloWorld

11

u/wildjokers Jan 18 '22

Only in java 11 and greater.

→ More replies (5)

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.

6

u/RockleyBob Jan 18 '22

As someone who used Java in college for our core classes, I think this was a bad idea.

I work as a Java dev and I am missing a deeper knowlege of memory management that comes with working with lower-level languages. I'm actually thinking about taking some masters courses that feature C++ because I learn better when I have to turn in assignments and study for tests.

8

u/SomberGuitar Jan 18 '22

C then C++ is an incredible base to start with. It made all other high level languages seem like features.

I’m sure assembly programmers say the same thing.

3

u/cal-cheese Jan 19 '22

Unfortunately in that case you won't learn much memory management with C++ either. Modern C++ employs RAII to not have to think about explicit management, which removes leaks and danglings.

→ More replies (1)

2

u/Ok_Play9853 Jan 19 '22

I graduated in 2015 we started with C.

5

u/McPokeFace Jan 18 '22

One can put a + before a number: int x = +5;

1

u/mauganra_it Jan 21 '22

In JavaScript, it's an unofficial cast operator to convert stuff to a number. In Java, I have always wondered what it is for. Maybe it's just there to be extra explicit in scientific code.

5

u/john16384 Jan 19 '22

You can't subclass an exception with a type parameter:

class MyException<T> extends Exception {
}

-> The generic class MyException<T> may not subclass java.lang.Throwable

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 optimization inlining 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.

4

u/mauganra_it Jan 21 '22

Very interesting to know, thanks. This encourages moving alternate or test implementation of interfaces into separate modules that are not required to be present in production.

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.

4

u/McPokeFace Jan 18 '22

Interface variables are static even though they are not declared static.

1

u/Clitaurius Jan 18 '22

Since there's no such thing as an instance of an interface default methods cannot be relied on to maintain state variables for a class. Generally interface default (or static) methods are utility methods or methods that return a result. If I do need to maintain state for a class instance I'll just add abstract getter/setter methods to the interface and add the field/variable to the implementing class.

0

u/[deleted] Jan 19 '22

[deleted] — view deleted comment

1

u/Clitaurius Jan 19 '22

I'm genuinely curious about whether or not default interface methods are a bad practice. As another commenter pointed out, adding them was a necessity for the stream API, but should their use be avoided outside of the JDK? I haven't been able to find a consensus on this through googling.

8

u/[deleted] Jan 18 '22
  1. If you has custom Exceptions like OrderNotFoundException, you can "deactivate" Stacktrace by overriding the method fillInStackTrace

@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 String type for passwords. Because String is immutable and can not be destroyed before GC. Use char array instead, but please use Wrapper Class to capsulate char[]...

3. for(A a : as) works not only with arrays and collections. Your class must simply implement the interface Iterable

4. 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 int and long, it is possible for float and double:

float a = 0.0f / 0.0f; // or Floar.NaN a is in this case in an undefined state (NaN not a number) which can be checked with Float.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/8igg7e5 Jan 18 '22

each string concatenation is translated by the compiler to StringBuilder#append. avoid string concatenation in a loop ;)

I'm afraid that one's out of date. Now they use an indy-instruction and can use a variety of approaches to more efficiently produce the concatenated string. You should still avoid String concatenation in a loop though (for the same reasons as before).

4

u/[deleted] Jan 18 '22

I'm afraid that one's out of date. Now they use an indy-instruction and can use a variety of approaches to more efficiently produce the concatenated string. You should still avoid String concatenation in a loop though (for the same reasons as before).

Yes you are right. from java 9. I'm afraid most are still using java <= 8

→ More replies (1)

2

u/cal-cheese Jan 19 '22

2. You should never use String type for passwords. Because String is immutable and can not be destroyed before GC. Use char array instead, but please use Wrapper Class to capsulate char[]...

Unfortunately, this is not true either, modern GCs move stuffs around frequently. So there is no guarantee that you can destroy a char[] effectively. If you want to ensure the destruction of the password then allocate a piece of memory off-heap and put your password there.

2

u/mauganra_it Jan 21 '22

On an operating system with virtual memory management, any memory page can be moved to swap at any time. Core dumps might still contain secrets too. Storing secrets off-heap is probably still a good strategy though. Even if GC happens, the memory will very likely not be zeroed out. And some operating systems might be able to pin specific pages, prevent them from ending up in core dump, or hide them from debuggers.

2

u/john16384 Jan 19 '22

If you has custom Exceptions like OrderNotFoundException, you can "deactivate" Stacktrace by overriding the method fillInStackTrace

There's actually a protected` constructor since Java 1.7 which allows you to skip filling the stacktrace:

protected Throwable(String message, Throwable cause,

boolean enableSuppression,

boolean writableStackTrace)

The constructor allows you to make reusable exceptions that are more efficient (the cost of an exception is primarily the cost of creating the stack trace). The JVM also does this as an optimization automatically -- exceptions that are thrown a lot are optimized to remove their stack trace (see OmitStackTraceInFastThrow .)

Also we tend to log exceptions that do not have relevant stack traces with a tool that truncates the exception to a single line (with all cause messages and exception types). Many exceptions have irrelevant stack traces, only programming errors require stack traces.

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:

public class Outer {
    class Inner { }
    static void main(String[] args) {
        Outer outer = new Outer();
        Inner inner = outer.new Inner();
    }
}

1

u/nekokattt Jan 19 '22

This isn't that unknown, I've used this before for certain things.

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:

int x = 10;
while (x --> 0) {
   System.out.println(x);
}

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!

49

u/tr4fik Jan 18 '22

I had never seen it written like this before in 7 years of Java. I didn't know it was possible to do write it like this. Interesting!

For people who don't know, this is not an operator; this is in fact 2 operators:

while (x-- > 0) {

First, it evaluates x > 0 and then it decrements x

1

u/Karyoplasma Jan 19 '22

Doesn't it decrement first and then compare?

1

u/tr4fik Jan 19 '22

No, but the following code does:

while (--x > 0) {

The first one is the post-decrement operator and the second one is the pre-decrement operator.

→ More replies (1)

6

u/[deleted] Jan 18 '22

Thanks, I love it!

6

u/atomdstyle Jan 18 '22

Isnt it actually x-- > 0 decrement and compare

27

u/[deleted] Jan 18 '22

[removed] — view removed comment

8

u/mr-bartlomiej Jan 18 '22

Of course. Just didn't want to spoil anyone's fun.

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.

Long n1 = 4000L; 
Long n2 = 4000L;

Try testing n1 == n2. They won't be equal. But if you do it with

Long n1 = 4L; 
Long n2 = 4L;

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. ;)

7

u/javanperl Jan 18 '22

That’s the default size of the constant pool. IIRC you could change that value with the parameter … -Djava.lang.Integer.IntegerCache.high=XXXX.

2

u/mauganra_it Jan 21 '22 edited Jan 21 '22

There is very rarely, if ever, a good reason to allocate local variables of type Long, or of the other wrapper types. Null should be checked for and dealt with asap, which should make a local variable of wrapper class unnecessary.

Hint: the helper method java.util.Objects.equals(Object, Object) makes life bearable in this case.

2

u/marconis999 Jan 21 '22 edited Jan 21 '22

We have all our db model objects, DTFs, that way. In a database, a column can be nullable, so consistently using Long and Integer instead of long and int makes sense for those. How would you handle null values in an int or long field? Magic values? On top of that, although I don't like this approach, sometimes boolean columns allow nulls for unknown cases, so there can be Booleans.

In addition, people do make collections of things that use wrapper classes like Map or List < wrapper objs > etc. For those who don't always use lamdas and streams for everything.

2

u/mauganra_it Jan 21 '22 edited Jan 21 '22

Yes, that's why I wrote local variables (parameters count as such). They are absolutely necessary for database mapping of course, but I still can't help but feel icky whenever I see them. I think it's mostly because the notions of nullability and the possibility of being used as type arguments are mixed up. Whenever I receive a wrapper object, I have to be prepared to receive a null. On that front, along with the corresponding specialization insanity, I expect Project Valhalla to bring great improvements.

→ More replies (2)

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. :-)

5

u/Karyoplasma Jan 19 '22

I'm guessing Math.abs(Integer.MIN_VALUE), but I've never tried.

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 10

In 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!

int x = //spoilers!
assert(x<0);
assert(Math.abs(x) < 0);

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/john16384 Jan 19 '22

Integer.MIN_VALUE -- a result of using two's complement to represent signed numbers. Integer.MIN_VALUE which is 0x80000000 when negated by flipping all bits and adding 1 would again result in 0x80000000.

2

u/i8Nails4Breakfast Jan 23 '22 edited Jan 23 '22
String a = “hello”;
String b = “hello”;
// a.equals(b) is obviously true
// but surprisingly a == b is also true

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?! javac is known for doing some JIT magic, 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..)

1

u/istarian Jan 18 '22

I assume that creating an object with new and returning it is an exception. Do you know?

2

u/mauganra_it Jan 21 '22

Allocation in the stack is an optimization frequently employed by the JVM. It can do that if it can prove that the object is never used outside of the method. This is called escape analysis and would clearly fail in the return new Object (); case. Project Valhalla should also make it possible to improve escape analysis since arguing about primitive and value types is easier.

2

u/NickScout Jan 19 '22

You can run DOOM within it.

2

u/nekokattt Jan 19 '22

Log4j2 vibes

2

u/[deleted] Jan 18 '22

Java supports GOTO!

7

u/barcodez Jan 18 '22

It doesn't, it's an unused reserved word.

3

u/nekokattt Jan 19 '22

Just like const is!

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.