Java vs JavaScript – Key Differences Explained with Examples
Despite the similar names, Java and JavaScript are completely different languages, designed by different people for different purposes. The name "JavaScript" was chosen in 1995 mainly for marketing, when Java was the hottest language around. As the saying goes, Java is to JavaScript what car is to carpet.
Today both are hugely popular: JavaScript runs every interactive website and many servers via Node.js, while Java powers enterprise back-ends and Android. This tutorial explains how they differ, with the same examples written in both.
1. Java and JavaScript at a Glance
| Aspect | Java | JavaScript |
|---|---|---|
| Created | 1995, James Gosling (Sun Microsystems) | 1995, Brendan Eich (Netscape), in about 10 days |
| Typing | Static, strong | Dynamic, weak (implicit type conversion) |
| Execution | Compiled to bytecode, run by the JVM | Run by a JavaScript engine (V8, SpiderMonkey) with JIT compilation |
| Runs in | JVM on servers, desktops, Android | Browsers, Node.js, Deno, Bun |
| Object model | Class-based | Prototype-based (with class syntax since ES6) |
| Concurrency | Multithreaded, virtual threads | Single-threaded event loop, async/await, Web Workers |
| Standard | Java Language Specification (OpenJDK) | ECMAScript (ECMA-262) |
| File extension | .java → .class | .js, .mjs |
| Main uses | Back-ends, Android, big data, enterprise | Web front-ends, Node.js servers, full-stack apps |
2. Typing: Static vs Dynamic
A JavaScript variable can hold a number now and a string later, and the language quietly converts types in many expressions. Java fixes each variable's type and refuses mismatches at compile time.
let value = 5; // a number...
value = "five"; // ...now a string: allowed
console.log(typeof value);
console.log("5" + 1); // "51" (string concatenation)
console.log("5" - 1); // 4 (string converted to number)
console.log(0 == ""); // true (loose equality converts types)
console.log(0 === ""); // false (strict equality)
string 51 4 true false
public class Types {
public static void main(String[] args) {
int value = 5;
// value = "five"; // compile error: String cannot be converted to int
System.out.println("5" + 1); // "51": + with a String concatenates
// System.out.println("5" - 1); // compile error: bad operand types for -
System.out.println(Integer.parseInt("5") - 1); // explicit conversion: 4
System.out.println(value == 5);
}
}
51 4 true
Both treat "5" + 1 as string concatenation, but JavaScript also silently turns "5" - 1 into 4, while Java refuses to compile it. TypeScript, a typed superset of JavaScript, adds compile-time types similar to Java's.
3. Objects and Asynchronous Code
Modern JavaScript has class syntax and private fields, so simple classes look similar in both languages. Asynchronous code differs more: JavaScript uses promises and async/await on a single thread; Java uses CompletableFuture or threads.
class Cart {
#items = []; // private field
add(name, price) { this.#items.push({ name, price }); return this; }
total() { return this.#items.reduce((sum, i) => sum + i.price, 0); }
}
const cart = new Cart().add("pen", 10).add("book", 250);
console.log("Total:", cart.total());
// Asynchronous code with promises and async/await
const fetchStock = (item) => new Promise(resolve => setTimeout(() => resolve(`${item}: in stock`), 50));
(async () => {
const results = await Promise.all([fetchStock("pen"), fetchStock("book")]);
console.log(results.join(", "));
})();
Total: 260 pen: in stock, book: in stock
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
public class Cart {
record Item(String name, double price) { }
private final List<Item> items = new ArrayList<>();
Cart add(String name, double price) { items.add(new Item(name, price)); return this; }
double total() { return items.stream().mapToDouble(Item::price).sum(); }
static CompletableFuture<String> fetchStock(String item) {
return CompletableFuture.supplyAsync(() -> item + ": in stock");
}
public static void main(String[] args) {
Cart cart = new Cart().add("pen", 10).add("book", 250);
System.out.println("Total: " + cart.total());
String results = fetchStock("pen").thenCombine(fetchStock("book"), (a, b) -> a + ", " + b).join();
System.out.println(results);
}
}
Total: 260.0 pen: in stock, book: in stock
Notice that JavaScript prints 260 while Java prints 260.0: JavaScript has a single number type, while Java distinguishes int, long, double and others.
4. Where the Code Runs
- JavaScript was born in the browser, where it manipulates web pages (the DOM) and responds to user actions. With Node.js (2009) it also runs on servers and in command-line tools.
- Java runs wherever there is a JVM: servers, desktops, Android devices and embedded systems. Java applets once ran in browsers, but they were removed years ago; Java no longer runs inside web pages.
5. Concurrency Model
JavaScript runs your code on a single thread with an event loop. Long tasks block everything, so I/O is non-blocking and handled with callbacks, promises or async/await; CPU-heavy work goes to Web Workers or worker threads. Java is multithreaded: many threads run in parallel on all CPU cores, and Java 21's virtual threads let blocking code scale to huge numbers of concurrent requests.
6. Other Language Differences
| Feature | Java | JavaScript |
|---|---|---|
| Number types | byte, short, int, long, float, double | number (64-bit float) and bigint |
| Equality | == compares primitives/references; equals() compares content | == converts types; === is strict |
| Functions | Methods inside classes; lambdas for functional interfaces | First-class functions anywhere |
| Inheritance | Classes and interfaces | Prototype chain |
| Modules | Packages and the module system | ES modules (import/export) |
| Null values | null | null and undefined |
| Package registry | Maven Central | npm |
| Build | Compile step required (Maven, Gradle) | No compile step needed (bundlers optional) |
7. How They Work Together
Java and JavaScript often appear in the same application: a React, Angular or Vue front-end written in JavaScript or TypeScript runs in the browser and calls a REST or GraphQL API built with Java and Spring Boot. Knowing both makes you a full-stack developer.
8. Which Should You Learn?
- Learn JavaScript if you want to build websites and web apps; it is unavoidable for front-end work.
- Learn Java if you want to build robust back-end services, enterprise systems or Android apps.
- For full-stack development, learn both: JavaScript/TypeScript for the browser and Java for the server.
9. Summary
- Java and JavaScript are unrelated languages that share only part of their name and some C-style syntax.
- Java is statically typed, class-based and multithreaded, running on the JVM.
- JavaScript is dynamically typed, prototype-based and event-loop driven, running in browsers and Node.js.
- They often work together: JavaScript front-ends talking to Java back-ends.