From the course: Java 25 for Professionals with Jetbrains AI Assistant
No boilerplate classes with compact source files - Java Tutorial
From the course: Java 25 for Professionals with Jetbrains AI Assistant
No boilerplate classes with compact source files
- [Instructor] Alright, look at this code, and let me ask you, what language are you looking at? No, no, don't run away. This is Java. This new feature makes Java feel light. Maybe not as light as Python, but it is definitely a step in that direction. We can now write a tiny Java program without a class declaration. I know, what a crowd pleaser. This code is enough. I can run it like this. And as you can see, it outputs, "Hello world." Void main is now the entry point of our application. Yes, that means no public static void main string array args anymore. There's more new though. Do you see the IO? IO is new as well. And it's a simple console console helper in Java lang io. Yep, we no longer need system out print line either. IO is introduced to give us access to several system in and system out methods conveniently. So what you just saw is a compact file and in compact files, all packages exported by Java base are auto important, so you can use things such as list math, et cetera, with no imports. And yes, the package statement is not necessary either. So Java is all hip and trendy now. If you missed a class, you can put a class around it, and the old way of creating a main method still works. You might think, 'Well what if I have both main methods, the modern one and the old way?" Well, that's method overloading because they accept different parameters and that's allowed. So which one do you think that the compiler prefers as an entry point? It's the explicit version. And it might be that I've been using it like this for almost 20 years, but at this point, I still like the explicit version a lot myself. You can see it in action here. You can also see the public is even redundant. I don't need to put that in front of this. And if I run it, it's printing another Hello world, indicating that the old way of declaring a main method is used as an entry point. So this is pretty awesome, but there's a few things to mention. The compact file is an unnamed class, and that means you can't instantiate it with a new keyword. Auto-imports, they are only for the compact file without the class around it. And if you put the class around it, it can still run, but you'd have to import what you need. So here's the same thing, but now we see class around it, and you can see that I'm needing an import here. And yes, we can import modules, but we'll talk more about that later. And please mind all the versions of Java, have no clue what it is you're doing here. So make sure to run this with Java 25 or once it's available, an even newer version of Java.