BJEX v1.0.0 — Language Reference

BJEX Documentation

Complete reference for BJEX — syntax, built-ins, examples, and internals.

Introduction

BJEX is a modern, beginner-oriented programming language and interpreter developed entirely from scratch in pure Java with zero external dependencies. It was created with one clear educational vision: to make programming easy to learn without sacrificing the fundamental concepts every programmer must understand.

Unlike traditional languages that require learners to study complex syntax before solving real problems, BJEX emphasizes clarity, simplicity, and practical learning. It allows new programmers to focus on computational thinking, algorithms, and problem-solving — not on confusing rules.

BJEX combines the readability of Python, the flexibility of JavaScript, and the robust architecture of a Java-based interpreter to provide a smooth, frustration-free learning experience.

Note: BJEX uses the .bjex file extension for all source files. Example: hello.bjex, calculator.bjex.

Vision & Goals

"Programming should be easy to learn, enjoyable to practice, and powerful enough to build real solutions."

BJEX was designed to bridge the gap between learning programming and understanding how programming languages actually work internally.

BJEX is specifically designed for:

  • 🎓 Students learning their first programming language
  • 📚 Self-taught programmers who want structured learning
  • 🏫 Educational institutions needing a teaching language
  • 🔬 Compiler and interpreter design study projects
  • 🛠️ Developers interested in language implementation internals

The language minimizes unnecessary syntax while preserving the core concepts found in all modern programming languages — so that everything learned in BJEX directly transfers to languages like Java, Python, and JavaScript.

Internal Architecture

BJEX is implemented using a complete, classical interpreter architecture. Every stage is hand-written in pure Java — no parser generators, no lexer frameworks.

📄 Source Code (.bjex file)
🔬 Lexer — Tokenization
🔢 Token Stream
🌳 Parser — Syntax Analysis
🌿 Abstract Syntax Tree (AST)
⚙️ Interpreter — AST Walking
🌍 Runtime Environment
✅ Program Output

Component Overview

ComponentResponsibility
LexerConverts raw source text into a stream of classified tokens. Handles all 4 comment styles, string literals, numbers, and operators.
ParserConsumes the token stream and builds an Abstract Syntax Tree using recursive descent parsing.
ASTTree of Node objects representing the program's structure — statements, expressions, literals, function calls.
InterpreterWalks the AST and executes each node — evaluates expressions, calls functions, handles control flow.
EnvironmentManages variable scoping — global scope, local function scopes, and closure chains.
Std LibraryBuilt-in functions: print, input, len, upper, lower, substr, split, join, contains, typeof, range, now, readfile, writefile, matrix, array, dict.
Module SystemLoads and executes external .bjex files as importable modules with namespace isolation.
Error HandlerStructured exception framework — throws typed errors (ValueError, NameError, etc.), caught by try/exception blocks.

Quick Start

Get BJEX running in three steps.

Step 1 — Download the Interpreter

Login and download BJEX →

Step 2 — Write Your First Program

Create a file called hello.bjex and paste this inside:

bjex
// My first BJEX program
name = input("Enter your name: ");
print("Hello,", name);
print("Welcome to BJEX Programming Language!");

Step 3 — Run It

terminal
Use BjexIde to Open your file or write code, and then click Run button.
Requirement: Java 17 or higher must be installed on your system. Check with: java -version

Variables & Data Types

BJEX uses dynamic typing — you never declare a type. Just assign a value and BJEX figures out the type automatically.

Declaring Variables

bjex
x     = 42;           // Integer
y     = 3.14;         // Float
name  = "Hello BJEX"; // String
flag  = true;         // Boolean
empty = null;         // Null

Supported Types

TypeExampleDescription
Integer42, -10, 0Whole numbers, positive or negative
Float3.14, -0.5Decimal numbers (double precision)
String"Hello", "BJEX"Text values enclosed in double quotes
Booleantrue, falseLogical true/false values
Arrayarray(1,2,3)Ordered, dynamic collection of values
Dictionarydict("k","v")Key-value pairs, like a HashMap
Matrixmatrix([[1,2],[3,4]])2D numeric matrix with math operations
Symbol:ready, :doneUnique immutable identifier values
Timenow()Current timestamp from runtime
NullnullRepresents no value / empty state
Dynamic Typing: A variable can hold any type and can be reassigned to a different type at any time. BJEX does not enforce type constraints at assignment.

Operators

Arithmetic Operators

bjex
a = 10 + 3;    // Addition      → 13
b = 10 - 3;    // Subtraction   → 7
c = 10 * 3;    // Multiplication → 30
d = 10 / 3;    // Division       → 3.333...
e = 10 % 3;    // Modulus        → 1
f = 2 ^ 8;     // Exponentiation → 256

Comparison Operators

bjex
x = 10;
print(x == 10);   // Equal          → true
print(x != 5);    // Not equal      → true
print(x > 5);     // Greater than   → true
print(x < 5);     // Less than      → false
print(x >= 10);   // Greater/equal  → true
print(x <= 9);    // Less/equal     → false

Logical Operators

bjex
a = true;
b = false;
print(a and b);   // Logical AND → false
print(a or  b);   // Logical OR  → true
print(not  a);    // Logical NOT → false

String Concatenation

bjex
first = "Hello";
last  = "BJEX";
full  = first + " " + last;
print(full);   // → Hello BJEX

Comments

BJEX supports four different comment styles — more than most languages.

Single Line — Style 1

// This is a comment
x = 10; // inline comment

Single Line — Style 2

# Python-style comment
y = 20; # also valid

Multi-line — Style 1

/*
  This is a multi-line comment.
  Spans multiple lines.
  C-style syntax.
*/

Multi-line — Style 2

<<<
  Another multi-line comment.
  BJEX unique style.
  Also supports nesting context.
>>>

Input & Output

Printing Output

print() accepts any number of arguments separated by commas. All values are converted to strings and printed space-separated.

bjex
print("Hello World");                  // → Hello World
print("Value:", 42);                   // → Value: 42
print("Sum:", 10 + 5);                 // → Sum: 15
print("X =", x, "Y =", y);            // → X = 10 Y = 20
print("Pi is approximately", 3.14);   // → Pi is approximately 3.14

Reading User Input

input() prints a prompt, waits for the user to type, and returns the value as a string.

bjex
name = input("Enter your name: ");
age  = input("Enter your age:  ");
print("Hello,", name, "— you are", age, "years old.");
Type Note: input() always returns a String. Use arithmetic operations carefully — convert with context if needed.

Conditional Statements

BJEX uses standard if / else if / else blocks with curly braces.

Basic If / Else

bjex
score = 75;

if (score >= 90) {
    print("Grade: A");
} else if (score >= 75) {
    print("Grade: B");
} else if (score >= 60) {
    print("Grade: C");
} else {
    print("Grade: F — Better luck next time!");
}

Nested Conditions

bjex
x = 15;

if (x > 10) {
    if (x > 20) {
        print("x is greater than 20");
    } else {
        print("x is between 10 and 20");
    }
} else {
    print("x is 10 or less");
}

Conditions with Logical Operators

bjex
age  = 20;
pass = true;

if (age >= 18 and pass == true) {
    print("Eligible and passed");
} else {
    print("Not eligible");
}

Loops

For Loop

Three-part C-style for loop: initializer; condition; increment.

bjex
// Count from 1 to 5
for (i = 1; i <= 5; i = i + 1) {
    print("i =", i);
}

// Count down
for (n = 10; n >= 1; n = n - 1) {
    print(n);
}
print("Blast off!");

While Loop

Repeats as long as the condition is true.

bjex
count = 0;
while (count < 5) {
    print("Count:", count);
    count = count + 1;
}

Loops with Arrays

bjex
arr = array(10, 20, 30, 40, 50);
i   = 0;

while (i < length(arr)) {
    print("Element", i, "=", arr[i]);
    i = i + 1;
}

Nested Loops

bjex
// Multiplication table
for (i = 1; i <= 5; i = i + 1) {
    for (j = 1; j <= 5; j = j + 1) {
        print(i, "*", j, "=", i * j);
    }
}

Functions

Functions in BJEX are defined with the func keyword. They support parameters, return values, and full local scoping.

Basic Function

bjex
func greet(name) {
    return "Hello, " + name + "!";
}

message = greet("Bhargav");
print(message);   // → Hello, Bhargav!

Multiple Parameters

bjex
func add(a, b) {
    return a + b;
}

func multiply(a, b, c) {
    return a * b * c;
}

print(add(10, 25));          // → 35
print(multiply(2, 3, 4));    // → 24

Functions Without Return

bjex
func printBanner(title) {
    print("=========================");
    print("  " + title);
    print("=========================");
}

printBanner("BJEX Language v1.0");

Functions Calling Functions

bjex
func square(n) {
    return n * n;
}

func sumOfSquares(a, b) {
    return square(a) + square(b);
}

print(sumOfSquares(3, 4));   // → 9 + 16 = 25

Recursion

BJEX fully supports recursive functions. The function can call itself with a different argument until a base case is reached.

Factorial

bjex
func factorial(n) {
    if (n <= 1) {
        return 1;
    }
    return n * factorial(n - 1);
}

print("5! =", factorial(5));    // → 120
print("10! =", factorial(10));  // → 3628800

Fibonacci Sequence

bjex
func fibonacci(n) {
    if (n <= 0) { return 0; }
    if (n == 1) { return 1; }
    return fibonacci(n - 1) + fibonacci(n - 2);
}

for (i = 0; i <= 10; i = i + 1) {
    print("fib(" + i + ") =", fibonacci(i));
}

Sum of Digits

bjex
func sumDigits(n) {
    if (n < 10) {
        return n;
    }
    return (n % 10) + sumDigits(n / 10);
}

print(sumDigits(12345));   // → 15

Arrays

Arrays in BJEX are dynamic, ordered collections. They support index access, appending, and all built-in operations.

Creating Arrays

bjex
// Create with array() function
arr = array(10, 20, 30, 40, 50);

// Create with literal syntax
nums = [1, 2, 3, 4, 5];

print("Array:", arr);
print("Literal:", nums);

Accessing Elements

bjex
arr = array(10, 20, 30, 40, 50);

print(arr[0]);    // → 10  (first element)
print(arr[2]);    // → 30  (third element)
print(arr[4]);    // → 50  (last element)

Array Operations

bjex
arr = array(1, 2, 3);

// Append element to end
append(arr, 4);
append(arr, 5);
print(arr);            // → [1, 2, 3, 4, 5]

// Get length
print(length(arr));    // → 5

Iterating Arrays

bjex
arr = array(5, 10, 15, 20);
i   = 0;

while (i < length(arr)) {
    print("arr[" + i + "] =", arr[i]);
    i = i + 1;
}

Arrays in Functions

bjex
func sumArray(arr) {
    total = 0;
    i     = 0;
    while (i < length(arr)) {
        total = total + arr[i];
        i     = i + 1;
    }
    return total;
}

nums = array(10, 20, 30, 40, 50);
print("Sum:", sumArray(nums));   // → 150

Dictionaries

Dictionaries store key-value pairs — similar to a HashMap in Java or a dict in Python. Keys are strings. Values can be any type.

Creating a Dictionary

bjex
person = dict(
    "name",    "Bhargav",
    "age",     21,
    "country", "India",
    "language","BJEX"
);

print(person);

Accessing Dictionary Data

bjex
d = dict("fruit", "Mango", "color", "Yellow");

// Get all keys
print(keys(d));     // → [fruit, color]

// Get all values
print(values(d));   // → [Mango, Yellow]

Dictionary with Mixed Value Types

bjex
config = dict(
    "debug",   true,
    "version", 1,
    "name",    "BJEX App",
    "port",    8080
);

print("Debug mode:", keys(config));
print("Values:", values(config));

Matrix Operations

BJEX has native matrix support — a unique feature rarely found in beginner languages. Matrices are 2D numeric arrays with built-in arithmetic operations.

Creating Matrices

bjex
m1 = matrix([[1, 2],
             [3, 4]]);

m2 = matrix([[5, 6],
             [7, 8]]);

print("Matrix 1:", m1);
print("Matrix 2:", m2);

Matrix Arithmetic

bjex
// Addition — element-wise
print("M1 + M2:", m1 + m2);
// → [[6,8],[10,12]]

// Multiplication — matrix product
print("M1 * M2:", m1 * m2);
// → [[19,22],[43,50]]
Matrix Multiplication: BJEX uses standard matrix multiplication (dot product), not element-wise multiplication. Matrices must have compatible dimensions.

String Utilities

BJEX includes a powerful set of built-in string functions, all available without importing anything.

FunctionDescriptionExample
len(s)Returns length of stringlen("hello") → 5
upper(s)Converts to uppercaseupper("bjex") → "BJEX"
lower(s)Converts to lowercaselower("BJEX") → "bjex"
substr(s,start,end)Extracts a substringsubstr("abcdef",1,4) → "bcd"
split(s,delim)Splits string into arraysplit("a,b,c",",") → ["a","b","c"]
join(arr,glue)Joins array into stringjoin(["1","2","3"],"-") → "1-2-3"
contains(s,sub)Checks if substring existscontains("hello","ll") → true

Full Example

bjex
sentence = "bhargav java expression language";

print("Length:", len(sentence));          // → 33
print("Upper:", upper(sentence));         // → BHARGAV JAVA EXPRESSION LANGUAGE
print("Substr:", substr(sentence, 0, 7)); // → bhargav

words = split(sentence, " ");
print("Words:", words);                   // → [bhargav, java, expression, language]

rejoined = join(words, "-");
print("Rejoined:", rejoined);             // → bhargav-java-expression-language

print("Has 'java':", contains(sentence, "java")); // → true

Type Checking

Use these built-in functions to inspect and validate types at runtime.

FunctionReturnsDescription
typeof(val)StringReturns type name as string: "integer", "float", "string", "boolean", "array", "dictionary", "matrix"
isnumber(val)BooleanReturns true if value is Integer or Float
isbool(val)BooleanReturns true if value is Boolean
islist(val)BooleanReturns true if value is an Array
bjex
print(typeof(42));          // → integer
print(typeof(3.14));        // → float
print(typeof("hello"));     // → string
print(typeof(true));        // → boolean
print(typeof([1,2,3]));     // → array

print(isnumber(42));        // → true
print(isnumber("hello"));   // → false
print(isbool(true));        // → true
print(islist([1,2,3]));     // → true

Range & Time

range(start, end, step)

Generates a numeric array from start to end with a given step size.

bjex
// Range from 1 to 10, step 1
r1 = range(1, 10, 1);
print(r1);      // → [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

// Even numbers: 0 to 20, step 2
evens = range(0, 20, 2);
print(evens);   // → [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

// Count down: 10 to 1, step -1
countdown = range(10, 1, -1);
print(countdown);

now() — Current Time

bjex
// Get current timestamp
t1 = now();
print("Program started at:", t1);

// Use for simple timing
start = now();
// ... some work ...
end = now();
print("Start:", start);
print("End:  ", end);

Symbol Type

Symbols are unique, immutable identifier values prefixed with a colon :. Two symbols with the same name are always equal. They are ideal for representing states, flags, and named constants.

bjex
// Declare symbols
status = :ready;
mode   = :active;
state  = :ready;

// Symbol comparison
print(status == state);    // → true  (same name = equal)
print(status == mode);     // → false (different names)

// Use symbols for readable state management
connectionState = :disconnected;

if (connectionState == :disconnected) {
    print("Not connected to server");
} else if (connectionState == :connected) {
    print("Connection established");
} else if (connectionState == :error) {
    print("Connection error occurred");
}
Best Practice: Use symbols instead of magic strings like "ready", "done", "error". They prevent typos and make intent clear.

Exception Handling

BJEX provides structured, typed exception handling with try, exception, and finally blocks — identical in concept to Java and Python.

Basic Try / Exception / Finally

bjex
try {
    x = 10 / 0;
} exception(ValueError) {
    print("Caught: Division by zero!");
} finally {
    print("This always runs — cleanup here.");
}

Catching Undefined Variables

bjex
try {
    print(undefinedVariable);
} exception(NameError) {
    print("Caught: Variable does not exist.");
} finally {
    print("Cleanup complete.");
}

Multiple Exception Types

bjex
try {
    result = 10 / 0;
    print(unknownVar);
} exception(ValueError) {
    print("Math error caught.");
} exception(NameError) {
    print("Name error caught.");
} finally {
    print("Block complete.");
}

Exception in Functions

bjex
func safeDivide(a, b) {
    try {
        return a / b;
    } exception(ValueError) {
        print("Cannot divide by zero!");
        return 0;
    }
}

print(safeDivide(10, 2));    // → 5
print(safeDivide(10, 0));    // → Cannot divide by zero! 0

Supported Exception Types

Exception TypeTriggered When
ValueErrorDivision by zero, invalid numeric operations
NameErrorAccessing an undefined variable
TypeErrorOperation on incompatible types
IndexErrorArray index out of bounds
FileErrorFile not found or I/O failure

File I/O

BJEX supports reading and writing text files with simple, clean built-in functions.

Writing a File

bjex
// Write text to a file (creates it if it doesn't exist)
writefile("output.txt", "Hello from BJEX!");
print("File written successfully.");

Reading a File

bjex
// Read the full content of a file
content = readfile("output.txt");
print("File content:", content);

File I/O with Exception Handling

bjex
try {
    data = readfile("data.txt");
    print("Read successful:", data);
} exception(FileError) {
    print("File not found. Creating a new one...");
    writefile("data.txt", "Default content");
} finally {
    print("File operation complete.");
}

Practical: Save User Data

bjex
name  = input("Enter your name: ");
score = input("Enter your score: ");

entry = name + "," + score;
writefile("scores.txt", entry);

print("Saved:", readfile("scores.txt"));
Path Note: File paths are relative to the directory from which BJEX was launched. Use absolute paths when working across different directories.

Module System

BJEX supports modular programming through the import statement. You can split your code across multiple .bjex files and import them.

Creating a Module

Create a file called mathutils.bjex:

mathutils.bjex
// mathutils.bjex — reusable math functions

func square(n) {
    return n * n;
}

func cube(n) {
    return n * n * n;
}

func isPrime(n) {
    if (n < 2) { return false; }
    i = 2;
    while (i * i <= n) {
        if (n % i == 0) { return false; }
        i = i + 1;
    }
    return true;
}

Importing and Using a Module

main.bjex
import mathutils.bjex;

print(mathutils.square(5));     // → 25
print(mathutils.cube(3));       // → 27
print(mathutils.isPrime(17));   // → true
print(mathutils.isPrime(10));   // → false

Standard Library Module

bjex
// Import built-in std module
import std.bjex;

print(std.helloModule());   // → Standard library loaded!
Module Naming: Import with the filename (without path) and access functions using moduleName.functionName() syntax.

Complete Built-in Reference

Every built-in function available in BJEX, no imports required.

FunctionParametersReturnsDescription
print(...)Any valuesvoidPrints space-separated values to output
input(prompt)StringStringPrints prompt and reads user input
len(s)String or ArrayIntegerReturns length
upper(s)StringStringUppercase conversion
lower(s)StringStringLowercase conversion
substr(s,i,j)String, Int, IntStringSubstring from index i to j (exclusive)
split(s,d)String, StringArraySplits string on delimiter
join(arr,g)Array, StringStringJoins array with glue string
contains(s,t)String, StringBooleanTrue if s contains substring t
typeof(v)AnyStringReturns type name as string
isnumber(v)AnyBooleanTrue if Integer or Float
isbool(v)AnyBooleanTrue if Boolean
islist(v)AnyBooleanTrue if Array
array(...)Any valuesArrayCreates a new dynamic array
append(arr,v)Array, AnyvoidAppends value to array end
length(arr)ArrayIntegerReturns array element count
dict(...)key,val pairsDictionaryCreates key-value dictionary
keys(d)DictionaryArrayReturns array of all keys
values(d)DictionaryArrayReturns array of all values
matrix(arr)2D ArrayMatrixCreates a 2D numeric matrix
range(s,e,step)Int,Int,IntArrayGenerates numeric sequence
now()noneTimeReturns current timestamp
readfile(path)StringStringReads entire file content
writefile(path,txt)String,StringvoidWrites text to file (overwrites)

Future Roadmap

BJEX is actively evolving. Here's what's planned for upcoming versions:

FeatureVersionStatus
GraalVM Native Image builds (.exe / .dmg / .deb)v1.1.0🔄 In Progress
Object-Oriented Programming — Classes & Objectsv1.2.0📋 Planned
Lambda Expressions / Anonymous Functionsv1.2.0📋 Planned
Interactive REPL (Read-Eval-Print Loop)v1.3.0📋 Planned
Package Manager for BJEX modulesv1.3.0📋 Planned
Web-based BJEX Playground (run in browser)v1.4.0💡 Concept
Bytecode Compilation for faster executionv2.0.0💡 Concept
Dedicated BJEX IDE with syntax highlightingv2.0.0💡 Concept
Contribute: BJEX is on GitHub. github.com/MRBG18/BJEX-Custom-Programming-Language — open an issue or submit a PR.