FirstHack Learn
Log in Sign up free

Introduction to Java

9 min read · 49 views

Introduction to Java

Java was released by Sun Microsystems in 1995 with a specific promise: write once, run anywhere. A program compiled on a Windows machine should run unchanged on Linux, on a Mac, or on a server, without being rebuilt for each one.

C and C++ cannot do that. They compile straight to machine code for one particular processor and operating system, so an executable built on your laptop will not run on a different platform. Java's answer was to add a layer in between, and almost everything distinctive about the language follows from that decision.

What the JVM actually does

When you compile Java, the compiler javac does not produce machine code. It produces bytecode: instructions for an imaginary computer that does not physically exist. Bytecode goes into a .class file.

The imaginary computer is the Java Virtual Machine. There is a real JVM implementation for Windows, one for Linux, one for macOS, one for Android. Each reads the same bytecode and carries out the instructions on the actual hardware underneath. The bytecode is portable; the JVM is not, and that is the point.

So there are two steps every time:

TEXT
javac Main.java      →  produces Main.class  (bytecode)
java Main            →  the JVM loads Main.class and runs it

Notice you type java Main, not java Main.class. You are naming the class, not the file.

Modern JVMs do more than interpret. The JIT compiler translates the hottest parts of your program into real machine code while it runs, which is why Java is much closer to C++ in speed than "it is interpreted" suggests.

The JVM also brings automatic memory management. A background process called the garbage collector finds objects your program can no longer reach and frees them. In C++ you decide when memory is released; in Java you do not think about it. You trade some control for a whole category of bugs you will never have.

C++ Java
Compiles to Machine code for one platform Bytecode for the JVM
To run elsewhere Recompile on that platform Same .class file, different JVM
Memory freeing You do it Garbage collector does it
Pointers Yes, with full arithmetic References only, no arithmetic
Startup speed Immediate JVM must start first

Why colleges use it

Three honest reasons, none of which is that Java is the best language.

  1. The object model is not optional. In C++ you can write an entire program without a class. In Java every piece of code lives inside a class, so a paper on object-oriented programming has nowhere to hide. The syllabus and the language line up.
  2. Errors surface early and clearly. Java is strictly typed and checks array bounds at runtime. An out-of-range index throws ArrayIndexOutOfBoundsException with a line number, rather than silently corrupting memory as C would.
  3. It is genuinely used. Android applications, banking systems and large backend services run on Java or on other JVM languages. The placement relevance is real, not theoretical.

Your first program

Java
public class Main {
    public static void main(String[] args) {
        System.out.println("Hello from Java");
    }
}

That is more ceremony than C's printf, and every word of it is doing something.

  • public class Main declares a class named Main. All Java code lives inside a class. If the class is public, the file must be named Main.java, matching exactly, capital letter included.
  • public on main means the JVM, which is outside your class, is allowed to call it.
  • static means the method belongs to the class itself, not to any object. This matters because when your program starts, no objects exist yet. Without static the JVM would need a Main object in order to call main, and it has no way to create one.
  • void means main returns nothing.
  • String[] args is an array of strings holding command-line arguments. You will rarely use it early on, but the signature must match exactly or the JVM will not recognise this as the entry point.
  • System.out.println(...) reads as: in the System class, take the out object (standard output), and call its println method. println prints and then moves to a new line. print does not.

If that feels like a lot of words to print one line, it is. Java optimises for large programs written by teams, and pays for it with verbosity in small ones.

ℹ️The filename rule is not a style guideline

If your public class is Main, the file must be Main.java. Not main.java, not Main.txt. The compiler enforces this, and the error message names the mismatch. On Windows the filesystem ignores case and hides the problem; on the Linux machines in your lab it will not.

A second program

Java
public class Main {
    public static void main(String[] args) {
        String name = "Ananya";
        int marks = 78;
        int total = 100;

        System.out.println("Student: " + name);
        System.out.println("Marks: " + marks + " out of " + total);

        double percentage = (marks * 100.0) / total;
        System.out.println("Percentage: " + percentage);

        System.out.print("This stays ");
        System.out.print("on one line.");
        System.out.println();

        System.out.println("Passed: " + (marks >= 40));
    }
}

The + operator does two different jobs here. Between two numbers it adds. When either side is a String, it concatenates, converting the other side to text automatically. That causes a classic surprise: "Total: " + 2 + 3 prints Total: 23, because the left + runs first and turns 2 into text. Bracket the arithmetic to force the addition.

Note 100.0 rather than 100. Two integers divided give an integer in Java exactly as in C, so 78 / 100 is 0.

Compiling and running

Save as Main.java and run two commands.

TEXT
javac Main.java
java Main

javac produces Main.class in the same folder. java Main starts a JVM and runs it. If you see Error: Could not find or load main class Main, you are almost certainly in the wrong directory, or you typed java Main.class.

Since Java 11 you can also run a single file directly with java Main.java, skipping the .class file. Learn the two-step version anyway, because that is what your lab expects.

Common mistakes

  • Filename does not match the public class name. public class Student must be in Student.java. The compiler says so explicitly.
  • Typing java Main.class. Pass the class name only: java Main.
  • Getting the main signature wrong. public static void main(String args) without the brackets compiles but the JVM will not find an entry point. It must be String[] args.
  • Missing a semicolon. Java, like C, ends statements with ;. The reported error is often on the following line.
  • Expecting System.out.println to be spelled Println or printLn. Java is case sensitive everywhere: class names, method names, variables.
  • Assuming 78 / 100 gives 0.78. Integer division truncates. Make one operand a double.

You now have a compiler, a running program, and a picture of what the JVM is doing underneath. Types come next. When you would rather solve something than read, go to the Practice page.

Create a free account to track what you have finished.