Java Statements and Expressions

At the prompt, you can type standard Java statements and expressions. Statements and expressions are all of the normal things that you’d say inside a Java method: e.g., variable declarations and assignments, method calls, loops, and conditionals.

You can type these exactly as they would appear in Java. You also have the option of working with “loosely typed” variables and arguments. That is, you can simply be lazy and not declare the types of variables that you use (both primitives and objects). BeanShell will still give you an error if you attempt to misuse the actual contents of the variable. If you do declare types of variables or primitives, BeanShell will enforce them.

Here are some examples:

foo = "Foo";   
four = (2 + 2)*2/2;
print( foo + " = " + four );   // print( ) is a bsh command

// do a loop
for (i=0; i<5; i++)
    print(i);  

// pop up an AWT frame with a button in it
b = new JButton("My Button");
f = new JFrame("My Frame");
f.getContentPane( ).add(b, "Center");
f.pack( );
f.setVisible(true);

Get Learning Java now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.