placeholder

Java and JavaScript

07 Oct 2024

Ernesto Ballon

Ernesto Ballon

5 min read

Comprehensive comparison between Java and JavaScript in terms of declaration, data structures, loops, and other key features.

1. Language Type and Execution Environment

FeatureJavaJavaScript
Language TypeStatically typed, compiled languageDynamically typed, interpreted language
ExecutionRuns on the Java Virtual Machine (JVM)Runs in the browser or Node.js environment
TypingStrongly typed (variables must have a specific type)Loosely typed (variable types are inferred dynamically)

2. Declaration (Variables and Functions)

Variable Declaration

FeatureJavaJavaScript
Variable DeclarationMust specify the type (e.g., int, String)var, let, and const are used, no type declaration required
Exampleint age = 25;let age = 25; (or var / const)
  • In Java, variables are explicitly typed (e.g., int, boolean, String).
  • In JavaScript, variables are implicitly typed, and types are inferred based on the value.

Function Declaration

FeatureJavaJavaScript
Function DeclarationYou must declare the return type (e.g., void, int)Functions are declared with function keyword or arrow functions
Examplejava public void greet() { System.out.println("Hi"); }js function greet() { console.log("Hi"); }
  • Java: Function declarations must specify the return type and parameters.
  • JavaScript: Functions are dynamically typed and can be defined using function or arrow syntax (()=>).

3. Data Structures

Primitive Types

FeatureJavaJavaScript
Primitive Typesint, float, double, boolean, char, byte, etc.number, string, boolean, undefined, null, symbol, bigint
String TypeString classstring (primitive type)
Exampleint num = 10;let num = 10;
  • Java: Strongly typed and uses distinct data types for integers, floats, etc.
  • JavaScript: Weakly typed with only number to represent all numeric types.

Reference Types

FeatureJavaJavaScript
ObjectsDefined using classes (Object is base class)Objects are key-value pairs (dynamic, no class needed)
ExamplePerson person = new Person();let person = { name: "John", age: 30 };

Collections

FeatureJavaJavaScript
ArraysFixed-size arrays (int[], String[])Dynamic arrays (Array object)
ListArrayList, LinkedList, List interfaceJavaScript has Array, which acts like List
MapHashMap, TreeMap, HashtableJavaScript’s Object and Map for key-value pairs
SetHashSet, TreeSet, LinkedHashSetJavaScript’s Set for unique values

Example of List/Array:

  • Java:java

    List<String> fruits = new ArrayList<>(); fruits.add("Apple");
  • JavaScript:js

    let fruits = ["Apple", "Banana"];

4. Loops and Iteration

Both Java and JavaScript provide similar looping constructs, but there are slight differences in syntax and features.

For Loop

FeatureJavaJavaScript
Basic For Loopfor (int i = 0; i < 10; i++)for (let i = 0; i < 10; i++)
For-Each Loopfor (String item : list)for (let item of array)

While Loop

FeatureJavaJavaScript
While Loopwhile (condition)while (condition)
Do-While Loopdo { ... } while (condition)do { ... } while (condition)

Example of For-Each Loop:

  • Java:java

    for (String fruit : fruits) { System.out.println(fruit); }
  • JavaScript:js

    for (let fruit of fruits) { console.log(fruit); }

5. Object-Oriented Features

Classes and Objects

FeatureJavaJavaScript
Class Declarationclass MyClass {}class MyClass {} (ES6 introduced class syntax)
Object InstantiationMyClass obj = new MyClass();let obj = new MyClass();
Inheritanceclass SubClass extends SuperClass {}class SubClass extends SuperClass {}

Both languages support object-oriented programming with classes, inheritance, and encapsulation. However:

  • Java: Classes are strictly typed and need to be compiled. Java has interfaces, abstract classes, polymorphism, and multiple inheritance (via interfaces).
  • JavaScript: Classes were introduced with ES6. JavaScript is prototype-based, meaning objects can inherit from other objects via prototypes.

Example of Class:

  • Java:java

    public class Car { private String model; public Car(String model) { this.model = model; } public void drive() { System.out.println("Driving " + model); } }
  • JavaScript:js

    class Car { constructor(model) { this.model = model; } drive() { console.log(`Driving ${this.model}`); } }

6. Exception Handling

FeatureJavaJavaScript
Try-Catchtry { ... } catch (Exception e) { ... }try { ... } catch (err) { ... }
Finallyfinally block for cleanupfinally block for cleanup
Checked ExceptionsYes (e.g., IOException)No (only runtime errors, all are unchecked)

Example:

  • Java:java

    try { int result = 10 / 0; } catch (ArithmeticException e) { System.out.println("Error: Division by zero"); } finally { System.out.println("Cleanup"); }
  • JavaScript:js

    try { let result = 10 / 0; } catch (err) { console.log("Error: Division by zero"); } finally { console.log("Cleanup"); }

7. Multithreading and Asynchronous Code

FeatureJavaJavaScript
MultithreadingYes (supports multithreading with Thread class or ExecutorService)No real multithreading (single-threaded, event-driven)
AsynchronousHandled via Runnable, Callable, FutureHandled with callbacks, Promises, and async/await
  • Java: Java supports real multithreading, where multiple threads run in parallel.
  • JavaScript: JavaScript is single-threaded and handles asynchronous behavior through event loops and callbacks, but with async/await and Promises, asynchronous code can look cleaner.

Example of Asynchronous Code:

  • JavaScript:js

    async function fetchData() { let data = await fetch('https://api.example.com/data'); console.log(data); }
  • Java:java

    Runnable task = () -> { System.out.println("Running task"); }; new Thread(task).start();

8. Other Relevant Features

Modules

  • Java: Since Java 9, it supports modules (module-info.java), allowing modularized development.
  • JavaScript: Supports ES6 modules (import and export statements), as well as CommonJS (require) for Node.js.

Memory Management

  • Java: Automatic garbage collection, but memory can be managed using finalize() and manual techniques.
  • JavaScript: Also uses garbage collection, and memory management is implicit.

Summary

FeatureJavaJavaScript
TypingStrong (static)Weak (dynamic)
CompilationCompiledInterpreted
ClassesStrict OOP (class-based inheritance)Prototype-based, class support since ES6
ThreadsReal multithreadingSingle-threaded (event-driven with async)
Data StructuresRich and strict (List, Map, Set, Array)Dynamic (Array, Object, Map, Set)
Exception HandlingChecked and unchecked exceptionsOnly unchecked runtime errors

Both languages are powerful but serve different purposes: Java for large-scale, strongly-typed enterprise systems, and JavaScript for web development and event-driven environments.