Programming Language Comparison Tool

More languages coming soon! Contact me if there are any errors.




# Run with "python FILENAME.py"
import math
import random
from abc import ABC, abstractmethod


# Abstract class (used as an interface here since Python supports multiple inheritance instead)
class Shape(ABC):
    @abstractmethod
    def area(self):
        pass

    @abstractmethod
    def perimeter(self):
        pass
    
    def extra_method(self):
        print("Extra method.")  # Non-abstract method


# "Concrete" Circle class implementing the Shape abstract class
class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return math.pi * (self.radius ** 2)

    def perimeter(self):
        return 2 * math.pi * self.radius


# Basic class (demonstrates objects, instantiation, methods, and constructors)
class Calculator:
    # Constructor
    def __init__(self, name):
        self.name = name

    # Void method (demonstrates calling void methods)
    def greet(self):
        print(f"Hello, this is {self.name}.")

    # Method without arguments (demonstrates calling methods without arguments)
    def generate_random_number(self):
        return random.randint(1, 100)


# Advanced Calculator inheriting from Calculator and using the Shape interface
class AdvancedCalculator(Calculator):
    def __init__(self, name):
        super().__init__(name)

    def square_root(self, x):
        return math.sqrt(x)

    # Using a Shape instance
    def compute_shape_area(self, shape: Shape):
        return shape.area()


# File I/O demonstration
def file_io():
    filename = "demo.txt"

    # Writing to a file
    with open(filename, "w") as file:
        file.write("Hello, world!\n")
        file.write("This is a file I/O demonstration.\n")

    # Reading from a file
    with open(filename, "r") as file:
        for line in file:
            print(line, end=' ')
    print()


# Arrays and tuples demonstration
def arrays_and_tuples():
    # Arrays (lists in Python)
    numbers = [1, 2, 3, 4, 5]
    for num in numbers:
        print(num, end=' ')
    print()

    # Tuples (immutable arrays)
    numbersTuple = (1, 2, 3, 4, 5)
    for num in numbersTuple:
        print(num, end=' ')
    print()
    n1, n2, n3, n4, n5 = numbersTuple  # Unpacking a tuple
    # numbersTuple[0] = 0  # This would cause an error



def add_with_documentation_and_type_hints(x: int , y: int) -> int:
    """
    Adds two numbers and returns the result.

    :param x: The first number.
    :param y: The second number.
    :return:  The sum of x and y.
    """
    return x + y


def main():
    # Primitive types and console output
    print("Primitive Types and Basic Console Output:")
    number = 42  # Integer (int)
    pi = 3.14159  # Float (float)
    is_easy = True  # Boolean (bool)
    name = "Calculator"  # String (str)
    letter = 'A'  # Character (str)
    empty = None  # Null (NoneType)
    print(number, pi, is_easy, name, letter)

    # Type casting
    int_pi = int(pi)
    print(int_pi)  # 3

    # Type hinting (Python 3.5+)
    print("Type Hinting:")
    whole_number: int = 42  # Type hints for lists: list[TYPE]

    # User input
    user_input = input("Enter something: ")

    # Elementary mathematics, arithmetic operators, and assignment operators
    sum = number + 23
    product = number * 2
    exponent = pi ** 2
    floor_division = 10 // 3.0
    number += 1  # Using an assignment operator
    print("Math operations:", sum, product, exponent, floor_division, number)
    print(add_with_documentation_and_type_hints(3, 4))

    # Instantiation and method calls
    calc = Calculator("Basic Calc")
    calc.greet()
    random_number = calc.generate_random_number()
    random_float = random.random()
    print(f"Random number: {random_number}\tRandom float: {random_float}")

    # Advanced usage with inheritance
    adv_calc = AdvancedCalculator("Advanced Calc")
    sqrt_result = adv_calc.square_root(16)
    print(f"Square root: {sqrt_result}")

    # Boolean expressions, conditions, and loops
    if sqrt_result > 5:
        print("Greater than 5.")
    elif sqrt_result == 5:
        print("Exactly 5.")
    else:
        print("Less than 5.")

    # Looping and iteration
    for i in range(5):  # for loop
        print(i, end=' ')
    print()

    # While loop
    count = 0
    while count < 5:
        print(count, end=' ')
        count += 1

    # Working with arrays (lists in Python)
    numbers = [1, 2, 3, 4, 5]
    for num in numbers:  # for-each loop
        print(num, end=' ')
    print()

    # 2D arrays and nested iteration
    matrix = [
        [1, 2, 3], 
        [4, 5, 6], 
        [7, 8, 9]
    ]

    for row in matrix:
        for item in row:
            print(item, end=' ')
        print()
    
    # Alternatively, using indices
    for r in range(3):
        for c in range(3):
            print(matrix[r][c], end=' ')
        print()

    # Exception handling
    try:
        risky_number = int("not a number")
    except ValueError as e:
        print("Caught a ValueError:", e)

    # Functions and recursion (demonstrating with a factorial function)
    def factorial(n):
        if n == 0:
            return 1
        else:
            return n * factorial(n-1)
    print(f"Factorial of 5: {factorial(5)}")

    # File I/O
    print("\nFile I/O Demonstration:")
    file_io()

    # Arrays versus tuples (since Python arrays are dynamic)
    arrays_and_tuples()

    # Anonymous functions (lambdas)
    hello = lambda: print("Hello, world!")
    hello()
    add = lambda x, y: x + y
    print(f"Lambda add: {add(3, 4)}")

    # Dictionaries
    dictionary = {
        "name": "John",
        "age": 25,
        "isStudent": False
    }
    print(dictionary["name"], dictionary["age"], dictionary["isStudent"])

    # Sets
    set1 = {1, 2, 3, 4, 5}
    set2 = {4, 5, 6, 7, 8}
    print(set1.union(set2))
    print(set1.intersection(set2))
    pass


# Execute the main function; although Python code is typically written top-level
if __name__ == "__main__":
    main()
    


// See https://t.ly/1jfCG for instructions to run
using System;
using System.IO;
using System.Collections.Generic;


// Interface definition
public interface IShape {
    double Area();
    double Perimeter();
}


// Abstract class implementing the IShape interface
public abstract class Shape : IShape {
    public abstract double Area();
    public abstract double Perimeter();
    public void ExtraMethod() { Console.WriteLine("Extra method."); }  // Non-abstract method
}


// Circle class implementing the Shape Abstract class
public class Circle : Shape {
    public double Radius { get; set; }

    public Circle(double radius) {
        Radius = radius;  // or this.Radius = radius;
    }

    public double Area() { Math.PI * Math.Pow(Radius, 2); }

    public double Perimeter() => 2 * Math.PI * Radius;  // Expression syntax for single-line methods
}


// Basic Calculator class
public class Calculator {
    public string Name { get; set; }

    public Calculator(string name) {
        Name = name;
    }

    // Void methods have no return type
    public void Greet() => Console.WriteLine($"Hello, this is {Name}.");

    public int GenerateRandomNumber() => new Random().Next(1, 101);
}


// Advanced Calculator class inheriting from Calculator
public class AdvancedCalculator : Calculator {
    public AdvancedCalculator(string name) : base(name) { }

    public double SquareRoot(double x) => Math.Sqrt(x);

    public double ComputeShapeArea(IShape shape) => shape.Area();
}


class Program {
    static void FileIO() {
        string filename = "demo.txt";

        // Writing to a file
        using (StreamWriter writer = new StreamWriter(filename)) {
            writer.WriteLine("Hello, world!");
            writer.WriteLine("This is a file I/O demonstration.");
        }

        // Reading from a file
        using (StreamReader reader = new StreamReader(filename)) {
            string line;
            while ((line = reader.ReadLine()) != null) {
                Console.WriteLine(line);
            }
        }
    }


    static void ArraysAndLists() {
        // Array example
        int[] numbers = new int[] { 1, 2, 3, 4, 5 };
        foreach (int num in numbers)
            Console.Write($"{num} ");
        Console.WriteLine();

        // List example
        List<int> numbersList = new List<int> { 1, 2, 3, 4, 5 };
        foreach (int num in numbersList)
            Console.Write($"{num} ");
        Console.WriteLine();

        // Bonus: Tuples (similar to Python)
        numbersTuple = (1, 2, 3, 4, 5);
        foreach (int num in numbersTuple)
            Console.Write($"{num} ");
        Console.WriteLine();
        numbersTuple.Item1;  // Accessing tuple elements
        (int n1, int n2, int n3, int n4, int n5) = numbersTuple;
        // numbersTuple[0] = 10;  // This would cause an error
    }


    /// <summary>
    /// Adds two numbers and returns the result.
    /// </summary>
    /// <param name="x">The first number.</param>
    /// <param name="y">The second number.</param>
    /// <returns>The sum of x and y.</returns>
    static int AddWithDocumentation(int x, int y) {
        return x + y;
    }


    static void Main(string[] args) {
        // Primitive types and console output
        Console.WriteLine("Primitive Types and Basic Console Output:");
        int number = 42;  // Integer
        double pi = 3.14159;  // Float
        bool is_easy = true;  // Boolean
        string name = "Calculator";  // String
        char letter = 'A';  // Character
        object nothing = null;  // Null
        Console.WriteLine(number + " " + pi + " " + is_easy + " " + name + " " + letter);

        // Type casting
        int int_pi = (int)pi;
        Console.WriteLine(int_pi);  // 3

        // User input
        Console.Write("Enter something: ");
        string user_input = Console.ReadLine();

        // Elementary mathematics, arithmetic operators, and assignment operators
        int sum = number + 23;
        int product = number * 2;
        double exponent = Math.Pow(pi, 2);
        int floor_division = Math.Floor(10 / 3.0);
        number += 1;  // Using an assignment operator
        Console.WriteLine($"Math operations: {0} {1} {2} {3} {4}", 
                          sum, product, exponent, floor_division, number);
        Console.WriteLine(AddWithDocumentation(3, 4));


        // Instantiation and method calls
        Calculator calc = new Calculator("Basic Calc");
        calc.Greet();
        int random_number = calc.GenerateRandomNumber();
        double random_float = new Random().NextDouble();
        Console.WriteLine($"Random number: {random_number}\tRandom float: {random_float}");

        // Advanced usage with inheritance
        AdvancedCalculator adv_calc = new AdvancedCalculator("Advanced Calc");
        double sqrt_result = adv_calc.SquareRoot(16);
        Console.WriteLine($"Square root: {sqrt_result}");

        // Boolean expressions, conditions, and loops
        // You can also omit {}s for single-line code blocks
        if (sqrt_result > 5) {
            Console.WriteLine("Greater than 5.");
        } else if (sqrt_result == 5) {
            Console.WriteLine("Exactly 5.");
        } else {
            Console.WriteLine("Less than 5.");
        }

        // Looping and iteration
        for (int i = 0; i < 5; i++) { // for loop
            Console.Write(i + " ");
        }
        Console.WriteLine();

        // While loop
        int count = 0;
        while (count < 5) {
            Console.Write(count + " ");
            count += 1;
        }

        // Working with arrays
        int[] numbers = new int[] { 1, 2, 3, 4, 5 };
        foreach (int num in numbers) {  // for-each loop
            Console.Write(num + " ");
        }
        Console.WriteLine();

        // 2D (jagged) arrays and nested iteration
        int[][] matrix = new int[][] { 
            new int[] { 1, 2, 3 }, 
            new int[] { 4, 5, 6 }, 
            new int[] { 7, 8, 9 } 
        };

        foreach (int[] row in matrix) {
            foreach (int item in row) {
                Console.Write(item + " ");
            }
            Console.WriteLine();
        }

        // Alternatively, using indices
        for (int r = 0; r < matrix.Length; r++) {
            for (int c = 0; c < matrix[r].Length; c++) {
                Console.Write(matrix[r][c] + " ");
            }
            Console.WriteLine();
        }

        // 2D (multidimensional) arrays (different from jagged arrays in C#)
        int[,] matrix2D = new int[,] { 
            { 1, 2, 3 }, 
            { 4, 5, 6 }, 
            { 7, 8, 9 } 
        };

        for (int r = 0; r < matrix2D.GetLength(0); r++) {
            for (int c = 0; c < matrix2D.GetLength(1); c++) {
                Console.Write(matrix2D[r, c] + " ");
            }
            Console.WriteLine();
        }

        // Exception handling
        try {
            int risky_number = int.Parse("not a number");
        } catch (FormatException e) {
            Console.WriteLine("Caught a FormatException: " + e.Message);
        }

        // Functions and recursion (demonstrating with a factorial function)
        int Factorial(int n){
            if (n == 0) 
                return 1;
            else
                return n * Factorial(n - 1);
        }
        Console.WriteLine($"Factorial of 5: {Factorial(5)}");

        // File I/O
        Console.WriteLine("\nFile I/O Demonstration:")
        FileIO();

        // Arrays versus Lists (Dynamic Arrays)
        ArraysAndLists();

        // Anonymous functions (lambdas)
        Func<void> hello = () => Console.WriteLine("Hello, world!");
        hello();
        Func<int, int, int> add = (x, y) => x + y;
        Console.WriteLine($"Lambda add: {add(3, 4)}");

        // Dictionaries
        var dictionary = new Dictionary<string, object> {  // Use var for type inference
            { "name", "John" },
            { "age", 25 },
            { "isStudent", false }
        };

        // Sets
        var set1 = new HashSet<int> {1, 2, 3, 4, 5};
        var set2 = new HashSet<int> {4, 5, 6, 7, 8};

        var unionSet = new HashSet<int>(set1);
        unionSet.UnionWith(set2);
        Console.WriteLine($"Union: {string.Join(", ", unionSet)}");

        var intersectionSet = new HashSet<int>(set1);
        intersectionSet.IntersectWith(set2);
        Console.WriteLine($"Intersection: {string.Join(", ", intersectionSet)}");
    }
}
        


// Run with "java FILENAME.java"
import java.io.*;   // FileReader, FileWriter, IOException, BufferedReader, BufferedWriter
import java.util.*; // Map, Set, List, Random, HashMap, HashSet, Scanner, ArrayList
import java.util.function.BiFunction;


// Interface for shapes
interface IShape {
    double area();
    double perimeter();
}


// Abstract class implementing the IShape interface
abstract class Shape implements IShape {
    public abstract double area();
    public abstract double perimeter();
    public void extraMethod() { System.out.println("Extra method."); }  // Non-abstract method
}


// Circle class implementing the Shape abstract class
class Circle extends Shape {
    private double radius;

    public Circle(double radius) {
        this.radius = radius;
    }

    public double area() {
        return Math.PI * radius * radius;
    }

    public double perimeter() {
        return 2 * Math.PI * radius;
    }
}


// Basic Calculator class
class Calculator {
    private String name;

    public Calculator(String name) {
        this.name = name;
    }

    // Void methods have no return type
    public void greet() {
        System.out.println("Hello, this is " + name + ".");
    }

    public int generateRandomNumber() {
        return new Random().nextInt(100) + 1;
    }
}


// Advanced Calculator extending Calculator
class AdvancedCalculator extends Calculator {
    public AdvancedCalculator(String name) {
        super(name);
    }

    public double squareRoot(double x) {
        return Math.sqrt(x);
    }

    public double computeShapeArea(IShape shape) {
        return shape.area();
    }
}


// Only the main class should be public
public class Main {
    static void fileIO() {
        String filename = "demo.txt";

        // Writing to a file
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filename))) {
            writer.write("Hello, world!\n");
            writer.write("This is a file I/O demonstration.\n");
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Reading from a file
        try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Alternatively, using Scanner
        try (Scanner scanner = new Scanner(new FileReader(filename))) {
            while (scanner.hasNextLine()) {
                System.out.println(scanner.nextLine());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    static void arraysAndLists() {
        // Array example
        int[] numbers = { 1, 2, 3, 4, 5 };
        for (int num : numbers)
            System.out.print(num + " ");
        System.out.println();

        // List example
        List<Integer> numbersList = new ArrayList<>();
        for (int i = 1; i <= 5; i++)
            numbersList.add(i);
        for (int num : numbersList)
            System.out.print(num + " ");
        System.out.println();

        // Java doesn't have tuples in the standard library
    }


    /**
     * Adds two numbers and returns the result.
     * @param x The first number.
     * @param y The second number.
     * @return  The sum of x and y.
     */
    static int addWithDocumentation(int x, int y) {
        return x + y;
    }


    public static void main(String[] args) {
        // Primitive types and console output
        System.out.println("Primitive Types and Basic Console Output:");
        int number = 42;  // Integer
        double pi = 3.14159;  // Float
        boolean is_easy = true;  // Boolean
        String name = "Calculator";  // String
        char letter = 'A';  // Character
        Object nothing = null;  // Null
        System.out.println(number + " " + pi + " " + is_easy + " " + name + " " + letter);

        // Type casting
        int int_pi = (int)pi;
        System.out.println(int_pi);  // 3

        // User input
        System.out.print("Enter something: ");
        Scanner input = new Scanner(System.in);
        String user_input = input.nextLine();

        // Elementary mathematics, arithmetic operators, and assignment operators
        int sum = number + 23;
        int product = number * 2;
        double exponent = Math.pow(pi, 2);
        int floor_division = (int)Math.floor(10 / 3.0);
        number += 1;  // Using an assignment operator
        System.out.printf("Math operations: %d %d %f %d %d\n", 
                          sum, product, exponent, floor_division, number);
        System.out.println(addWithDocumentation(3, 4));

        // Instantiation and method calls
        Calculator calc = new Calculator("Basic Calc");
        calc.greet();
        int random_number = calc.generateRandomNumber();
        double random_float = Math.random();
        System.out.println("Random number: " + random_number + "\tRandom float: " + random_float);

        // Advanced usage with inheritance
        AdvancedCalculator adv_calc = new AdvancedCalculator("Advanced Calc");
        double sqrt_result = adv_calc.squareRoot(16);
        System.out.println("Square root: " + sqrt_result);

        // Boolean expressions, conditions, and loops
        // You can also omit {}s for single-line code blocks
        if (sqrt_result > 5) {
            System.out.println("Greater than 5.");
        } else if (sqrt_result == 5) {
            System.out.println("Exactly 5.");
        } else {
            System.out.println("Less than 5.");
        }

        // Looping and iteration
        for (int i = 0; i < 5; i++) { // for loop
            System.out.print(i + " ");
        }
        System.out.println();

        // While loop
        int count = 0;
        while (count < 5) {
            System.out.print(count + " ");
            count += 1;
        }

        // Working with arrays
        int[] numbers = new int[] { 1, 2, 3, 4, 5 };
        for (int num : numbers) {  // for-each loop (enhanced for loop)
            System.out.print(num + " ");
        }
        System.out.println();

        // 2D arrays and nested iteration
        int[][] matrix = new int[][] {
            { 1, 2, 3 },
            { 4, 5, 6 },
            { 7, 8, 9 }
        };

        for (int[] row : matrix) {
            for (int item : row) {
                System.out.print(item + " ");
            }
            System.out.println();
        }

        // Alternatively, using indices
        for (int r = 0; r < matrix.length; r++) {
            for (int c = 0; c < matrix[r].length; c++) {
                System.out.print(matrix[r][c] + " ");
            }
            System.out.println();
        }

        // Exception handling
        try {
            int risky_number = Integer.parseInt("not a number");
        } catch (NumberFormatException e) {
            System.out.println("Caught a NumberFormatException: " + e.getMessage());
        }

        // Functions and recursion (demonstrating with a factorial function)
        // Java does not support methods inside methods, but you can use inner classes
        class Factorial {
            static int factorial(int n) {
                if (n == 0) {
                    return 1;
                }
                return n * factorial(n - 1);
            }
        }
        System.out.println("Factorial of 5: " + Factorial.factorial(5));

        // File I/O
        System.out.println("\nFile I/O Demonstration:");
        fileIO();

        // Arrays versus Lists (Dynamic Arrays)
        arraysAndLists();

        // Anonymous functions (lambdas)
        Runnable hello = () -> System.out.println("Hello, world!");
        hello.run();
        BiFunction<Integer, Integer, Integer> add = (x, y) -> x + y;
        System.out.printf("Lambda add: %d\n", add.apply(5, 3));
        
        // Dictionaries (Maps)
        Map<String, Object> dictionary = new HashMap<>();  // var dict = new HashMap<String, Object>();
        dictionary.put("name", "John");
        dictionary.put("age", 25);
        dictionary.put("isStudent", false);
        System.out.println(dictionary.get("name") + " " + 
                           dictionary.get("age")  + " " + 
                           dictionary.get("isStudent"));

        // Sets
        Set<Integer> set1 = new HashSet<Integer>() {{ add(1); add(2); add(3); add(4); add(5); }};
        Set<Integer> set2 = new HashSet<Integer>() {{ add(4); add(5); add(6); add(7); add(8); }};
        
        var unionSet = new HashSet<Integer>(set1);
        unionSet.addAll(set2);
        System.out.println("Union: " + unionSet);
        
        var intersectionSet = new HashSet<Integer>(set1);
        intersectionSet.retainAll(set2);
        System.out.println("Intersection: " + intersectionSet);
    }
}