Java Tutorial (Easy & Modern Features)
Java is a robust, object-oriented language widely used for enterprise applications, Android development, and large-scale systems.
1. "Hello, World!"
Explanation:
-
public class HelloWorld: Defines a class namedHelloWorld. In Java, all code resides within classes. -
public static void main(String[] args): This is the entry point of the Java program.public: The method is accessible from anywhere.static: The method belongs to the class itself, not to any specific object of the class.void: The method doesn't return any value.main: The special name for the entry point method.String[] args: An array of strings to receive command-line arguments.
-
System.out.println(...): Prints output to the console, followed by a newline.
2. var for Local Variable Type Inference (Java 10+):
Allows the compiler to infer the type of a local variable based on its initialization, similar to C++ auto or Python's typing.
auto or Python's typing.
Explanation:
var message = ...: Declaresmessageusingvar, letting the compiler determine its type (String).
3. Records (Java 14+):
A concise way to create classes that primarily hold data. They automatically generate constructors, getters, equals(), hashCode(), and toString().
Explanation:
public record Point(int x, int y): Defines a record namedPointwith two integer components,xandy.p1.x(): Automatically generates a getter method for thexcomponent.
4. Text Blocks (Java 15+):
A convenient way to define multi-line strings without needing escape sequences like \n.
strings without needing escape sequences like \n.
Explanation:
""" ... """: Uses triple double quotes to define a text block. Newlines and indentation are generally preserved.
5. Switch Expressions (Java 14+, enhanced in Java 17+):
A more concise way to write switch statements, allowing them to return a value.
Explanation:
switch (dayOfWeek) { ... }: Defines the switch expression.case 1 -> "Monday";: Uses the->operator to specify the value to return for each case.default -> "Invalid day";: The default case.
Running Java Code:
Save the code in a .java file (e.g., MyProgram.java). Open your terminal or command prompt, navigate to the directory where you saved it.
- Compile:
- Run: