Skip to content

Repository files navigation

☕ Java Code Visualizer

A browser-based, interactive Java code visualizer that lets you write, compile, and step through Java programs line-by-line — all running entirely in the browser with no backend server required.

Built as a single React component with a custom JavaScript-based Java interpreter, inspired by tools like Python Tutor.

Dark ThemeLight ThemeReactVite


Features

Code Editor (Left Panel)

  • Syntax-highlighted code editor with Fira Code monospace font (16px)
  • Line numbers with clickable breakpoints (red dots)
  • Current-line highlighting and execution path visualization (green stripes, count badges)
  • Never-reached lines dimmed with "not reached" tags after execution
  • Coverage indicator showing percentage of code lines executed
  • Tab key support (4-space indent)
  • Native word-level text selection and copy
  • Dynamic file label derived from public class ClassName in the code
  • Status bar with cursor position (Ln, Col), line count, character count, and keyboard shortcut hints

Java Interpreter Engine

The interpreter supports a comprehensive subset of the Java language and standard library:

Language Features:

  • Primitives:int, double, boolean, char, String, float, long, short, byte
  • Wrapper types:Integer, Double, Long, Float, Short, Byte, Boolean, Character, Object, var
  • Arrays: declaration, initialization ({1,2,3} and new int[N]), access, .length
  • Control Flow:for, while, do-while, if/else if/else, return
  • Methods: declarations, calls, recursion, call stack tracking
  • Operators: arithmetic, comparison, logical, compound assignment (+=, -=, etc.), increment/decrement (++, --)
  • Type Casting:(int), (double), (char) with correct operator precedence
  • Numeric literals:L/l suffix (long), f/F (float), d/D (double), underscore separators (100_000)
  • IEEE 754:1.0 / 0.0Infinity, 0.0 / 0.0NaN (integer division by zero still throws)
  • Inline comments:// comments after statements are stripped during parsing (preserves // inside strings)

Standard Library (~150 methods):

ClassMethods
System.outprintln(), print(), printf() with %d, %f, %.2f, %s, %n, %%
ScannernextInt(), nextDouble(), nextFloat(), nextLine(), next(), nextBoolean()
Mathabs, max, min, sqrt, pow, random, floor, ceil, round, log, log10, sin, cos, tan, asin, acos, atan, atan2, toRadians, toDegrees, signum, cbrt, exp, hypot + PI, E
Stringlength, charAt, substring, indexOf, lastIndexOf, equals, equalsIgnoreCase, compareTo, compareToIgnoreCase, toUpperCase, toLowerCase, trim, strip, stripLeading, stripTrailing, contains, replace, replaceAll, replaceFirst, startsWith, endsWith, isEmpty, isBlank, toCharArray, split, concat, matches, codePointAt, hashCode, getBytes, repeat + String.valueOf(), String.join(), String.format()
IntegerparseInt, valueOf, toString, toBinaryString, toHexString, toOctalString, compare, max, min, sum + MAX_VALUE, MIN_VALUE, SIZE, BYTES
LongparseLong, valueOf, toString, compare + MAX_VALUE, MIN_VALUE, SIZE, BYTES
DoubleparseDouble, valueOf, toString, isNaN, isInfinite, compare + MAX_VALUE, MIN_VALUE, POSITIVE_INFINITY, NEGATIVE_INFINITY, NaN, SIZE, BYTES
Float/Byte/ShortMAX_VALUE, MIN_VALUE, SIZE, BYTES constants
CharacterisLetter, isDigit, isLetterOrDigit, isUpperCase, isLowerCase, toUpperCase, toLowerCase, isWhitespace, isAlphabetic, compare, getNumericValue
Number wrappers.intValue(), .doubleValue(), .floatValue(), .longValue(), .shortValue(), .byteValue(), .toString(), .compareTo(), .equals(), .hashCode()
ArraystoString, sort, fill, copyOf, copyOfRange, equals, deepEquals, binarySearch, asList
ArrayListadd, get, set, remove, size, isEmpty, contains, indexOf, lastIndexOf, clear, toArray, subList, addAll, sort, toString, forEach
HashMapput, get, getOrDefault, remove, containsKey, containsValue, size, isEmpty, clear, keySet, values, entrySet, putIfAbsent, replace, toString
StringBuilderappend, insert, delete, deleteCharAt, replace, reverse, toString, length, charAt, substring, indexOf, capacity, setCharAt
Collectionssort, reverse, max, min, frequency, swap, fill, unmodifiableList
SystemcurrentTimeMillis, nanoTime, arraycopy, exit

Error Handling: infinite loop protection (10K step cap), ArrayIndexOutOfBoundsException, ArithmeticException (integer division by zero only)

Inspection Panels (Right Panel)

  • Variables Tab — Live variable visualization with:
    • Step-through diff:13 → 21 before→after pills with delta badges (+8 / -3)
    • NEW badge for freshly declared variables
    • Changes summary header: "⚡ 2 changes on this step: sum, i"
    • Array cells with index pointers, change highlighting, and previous value strikethrough
  • Call Stack Tab — Current method call hierarchy with line numbers
  • Output Tab — Console-style output with inline Scanner input display and Clear button
  • Compile Log Tab — Success/error messages with line numbers

Toolbar

  • Compile & Run — Executes the full program and jumps to the last step
  • Step Forward / Back — Navigate through execution states one step at a time
  • Auto Play / Pause — Automatic stepping with adjustable speed slider
  • Reset — Clear all execution state
  • Download — Save current code as .java file
  • Fullscreen — Toggle browser fullscreen mode
  • Load Example dropdown — 9 built-in example programs
  • Open Java File(s) — Load .java files from your local machine

Keyboard Shortcuts

ShortcutAction
Cmd/Ctrl + EnterCompile & Run
Cmd/Ctrl + SDownload as .java file
Cmd/Ctrl + /Toggle line comment (//)
Cmd/Ctrl + ZUndo
Cmd/Ctrl + Shift + ZRedo
TabInsert 4 spaces
F11Toggle fullscreen
Click line numberToggle breakpoint

Theming

  • Dark Mode (default) — GitHub dark-inspired palette with moon icon
  • Light Mode — Clean light palette with sun icon
  • Single animated toggle button with smooth 0.4s transitions across all elements

Quick Start

Prerequisites

  • Node.js (v18+ recommended)
  • npm (comes with Node.js)

Setup

# 1. Create a new Vite + React project
npm create vite@latest java-visualizer -- --template react
cd java-visualizer
# 2. Install dependencies
npm install
npm install lucide-react
# 3. Copy the component into the project
cp ~/Downloads/JavaCodeVisualizer.jsx src/JavaCodeVisualizer.jsx

Configure

Replace src/App.jsx with:

importJavaCodeVisualizerfrom'./JavaCodeVisualizer'functionApp(){return<JavaCodeVisualizer/>}exportdefaultApp

Replace src/index.css with:

* {
margin:0;
padding:0;
}
html,body,#root {
width:100%;
height:100vh;
margin:0;
overflow: hidden;
}

Empty src/App.css — delete all contents (or delete the file and remove its import from App.jsx).

Ensure src/main.jsx looks like:

importReactfrom'react'importReactDOMfrom'react-dom/client'importAppfrom'./App'import'./index.css'ReactDOM.createRoot(document.getElementById('root')).render(<React.StrictMode><App/></React.StrictMode>,)

Run

npm run dev

Open http://localhost:5173 in your browser.

Build for Production

npm run build # Creates optimized static files in dist/
npm run preview # Preview the production build locally

Project Structure

java-visualizer/
├── public/
├── src/
│ ├── JavaCodeVisualizer.jsx # Single-file component (~4,010 lines)
│ ├── App.jsx # Wrapper component
│ ├── main.jsx # React entry point
│ ├── index.css # Global reset styles
│ └── App.css # (empty)
├── index.html
├── package.json
├── vite.config.js
├── .gitignore
├── README.md
├── TODO.md
└── JavaCodeVisualizer_VersionHistory.md

Component Architecture

JavaCodeVisualizer.jsx is a self-contained single-file component containing:

SectionDescription
JAVA_LOGOBase64-embedded Java icon
JavaInterpreter classTokenizer, parser, expression evaluator, statement executor, state snapshot engine, ~150 standard library methods
EXAMPLES object9 built-in Java programs
THEMES objectDark and light theme color definitions (~40 tokens each)
highlightJava()Regex-based syntax highlighter
JavaCodeVisualizer()Main React component with state, handlers, diff engine, execution path tracker, and JSX

Built-in Examples

ProgramConcepts Demonstrated
Array Sum & AverageArrays, loops, arithmetic, type casting, conditionals
Bubble SortNested loops, array swapping, comparison logic
Fibonacci (Recursive)Recursion, method calls, return values
Factorial (Recursive)Recursion, multiplication, base cases
Binary SearchWhile loop, divide and conquer, array access
String ReversalString methods, charAt, string concatenation
FizzBuzzModulo operator, if/else if/else chains
Selection SortNested loops, minimum finding, array swapping
Grade Calculator (Scanner)Scanner input (nextLine, nextInt), for loop, if/else if/else, type casting

Scanner / User Input

Programs using java.util.Scanner are fully supported with interactive input:

importjava.util.Scanner;
publicclassEvenOddChecker {
publicstaticvoidmain(String[] args) {
Scannerscanner = newScanner(System.in);
System.out.print("Enter a number: ");
intnum = scanner.nextInt();
if (num % 2 == 0) {
System.out.println(num + " is an even number.");
} else {
System.out.println(num + " is an odd number.");
}
scanner.close();
}
}

When you click Compile & Run, the program executes until it hits scanner.nextInt(), then pauses and shows an input prompt in the Output tab. Type your value, press Enter, and execution continues. User inputs appear inline after their prompts, matching real terminal behavior.

Supported Scanner Methods

MethodInput Type
nextInt()Integer
nextDouble()Decimal number
nextFloat()Decimal number
nextLine()Full line of text
next()Single word
nextBoolean()true/false

Collections Support

The interpreter supports the most commonly used Java collections:

// ArrayListArrayList<String> list = newArrayList<>();
list.add("Hello");
list.add("World");
System.out.println(list.toString()); // [Hello, World]// ArrayList with initial valuesArrayList<Integer> nums = newArrayList<>(Arrays.asList(40, 10, 30));
Collections.sort(nums);
System.out.println(nums.toString()); // [10, 30, 40]// HashMapHashMap<String, Integer> map = newHashMap<>();
map.put("a", 1);
map.put("b", 2);
System.out.println(map.get("a")); // 1// StringBuilderStringBuildersb = newStringBuilder("Hello");
sb.append(" World");
sb.reverse();
System.out.println(sb.toString()); // dlroW olleH

Step-Through Variable Diff

When stepping through code, the Variables tab shows exactly what changed:

  • Before→After pills:sum: 13 → 21 with green-highlighted diff
  • Delta badges:+8 (green) or -3 (red) for numeric changes
  • NEW badge: freshly declared variables marked with blue NEW pill
  • Changes summary: "⚡ 2 changes on this step: sum, i" at the top
  • Array cell diff: changed cells flash and show previous value as strikethrough above

Execution Path Visualization

After running a program, the editor shows the execution path:

  • Green stripes on the left gutter for every executed line
  • Count badges for lines hit multiple times in loops (e.g., 5, 12)
  • Dimmed lines (30% opacity) for code that was never reached
  • "not reached" tags on skipped conditional branches
  • Coverage % in the step bar showing how much of the code was executed

Loading Local Files

Click the dropdown button in the toolbar and select "Open Java File(s)…" to load .java files from your local machine. You can multi-select files with Cmd+Click (Mac) or Ctrl+Click (Windows). Loaded files appear under a "Your Files" section in the dropdown.


Theme Toggle

Click the animated pill-shaped toggle in the toolbar header to switch between dark and light themes. The toggle shows a moon icon in dark mode and a sun icon in light mode. All colors — syntax highlighting, backgrounds, borders, overlays, variable cards, array cells — transition smoothly.


Dependencies

PackageVersionPurpose
react18+UI framework
react-dom18+React DOM renderer
lucide-react0.383+Icon library (Play, Pause, Download, Maximize, etc.)
vite5+Build tool and dev server

External Resources (loaded via CDN)

ResourcePurpose
Google Fonts — Fira CodeCode editor font
Google Fonts — DM SansUI/label font

Browser Compatibility

BrowserStatusNotes
Chrome / Edge✅ Full supportFile System Access API for file picker
Firefox✅ SupportedUses fallback <input type="file"> for file picker
Safari✅ SupportedUses fallback <input type="file"> for file picker

Known Limitations

  • Single-class programs only — the interpreter executes the main method of one class; multi-class programs are not supported
  • No multi-line comments/* */ comments spanning multiple lines are not yet handled (single-line // comments work, including inline)
  • No exception handlingtry/catch/finally blocks are not interpreted
  • No switch statementsswitch/case is not yet implemented
  • No for-each loops — only traditional for(init; cond; update) syntax
  • No generics validation — generic type parameters are accepted syntactically but not type-checked
  • No static fields or method overloading
  • Floating-point displaydouble values may show JavaScript floating-point artifacts

Troubleshooting

IssueSolution
Blank screen / import errorsEnsure npm install lucide-react completed successfully
App not full-width / cropped edgesClear src/App.css completely; set #root { width: 100%; height: 100vh; margin: 0; overflow: hidden; } in index.css
Code appears centeredEnsure text-align: center is not set on #root in your CSS
Port already in useVite auto-picks next port, or run npm run dev -- --port 3000
File picker doesn't openCheck browser compatibility; Chrome/Edge support showOpenFilePicker, others use fallback
undefined in outputCheck for inline // comments on the affected line (should be fixed in v22+)

Version History

See JavaCodeVisualizer_VersionHistory.md for the complete development changelog across 23 iterative versions.


Roadmap

See TODO.md for the full planned features roadmap including upcoming items like breakpoint-aware auto-play, array swap animations, memory model visualization, guided tutorials, and more.


License

This project is provided as-is for educational and personal use.


Credits

Built with React, Vite, Lucide Icons, Fira Code, and DM Sans.

About

A browser-based Java Code Visualizer, write, compile & step through Java line-by-line with variable diff, execution path tracking, ~150 stdlib methods, Scanner input, ArrayList/HashMap/StringBuilder, dark/light themes, keyboard shortcuts, and 9 example programs. No backend required.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages