47

I'm looking to write a short program (maybe a Hello World) in Java bytecode. I just want to write the bytecode using my text editor and run it. How would I do this? Got an example? Thanks!

1

3 Answers 3

46

You could try Jasmin!

.class public HelloWorld
.super java/lang/Object

.method public static main([Ljava/lang/String;)V
  .limit stack 3
  .limit locals 1

  getstatic      java/lang/System/out Ljava/io/PrintStream;
  ldc            "Hello World."
  invokevirtual  java/io/PrintStream/println(Ljava/lang/String;)V

  return

.end method

You compile it using:

> java -jar jasmin.jar hello.j

And then you run it like any class:

> java HelloWorld
Hello World.

Update

I see that your question mentions "without using Javac or Java". Could you clarify how you meant that statement?

Sign up to request clarification or add additional context in comments.

9 Comments

This post makes me want to fake the work I'm doing today and tinker around with Jasmin. :-)
+1 Jasmin is what came to my mind and I couldn't remember the name. It was featured in a book that explains JVM internals. I Forget the name of the book too, sigh...
@Bakkal: According to the link: "Jasmin was originally created as a companion to the book "Java Virtual Machine", written by Jon Meyer and Troy Downing and published by O'Reilly Associates."
by "without using Javac or Java," I just meant that I want to write the code using bytecode. Thanks for the info!
wow~ This is super cool. is this JVM independent as well? can this run on a blackberry jvm?
|
11

I've created a new Java bytecode assembler that is backwards compatible with Jasmin but also adds lots of new features and simplifies the syntax slightly.

Here's an example of how you might write a Hello World program.

.class public hello
.super java/lang/Object

.method public static main : ([Ljava/lang/String;)V
    .limit stack 10
    .limit locals 10

    getstatic java/lang/System out Ljava/io/PrintStream;
    ldc "Hello World!"
    invokevirtual java/io/PrintStream println (Ljava/lang/Object;)V
    return
.end method

I've also written a tutorial on bytecode assembly. It currently only covers Hello, World, but I can continue it if there is interest.

2 Comments

the link is broken
Sorry about that. It looks like the whole wiki is gone. I'll email them to see if they can bring it back or have any copies.
9

Byte code is written as actual bytes, which are not normally easily editable by a normal text editor.

This means you will need something that converts a textual representation to binary. A reasonable place to start would be an assembler like Jasmin.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.