[WannaJava]

Java Beginners Tutorial

intro basics applets comments variables expressions loops review
Chpt. 6 Expressions

So now you know about variables, and we've already talked about statements. (If you need to review statements, go back and look at Dissecting the Statement in the Basics section.) Let's put the two together to express ourselves better.

An expression is a type of statement that produces some result that can be used in another statement. And like all statements, expressions are found inside classes. Most are found inside methods, but we'll see later on that some end up outside of any method. Just remember that everything happens inside classes.

Before we jump into a method, though, let's look closer at the definition of an expression. What we're really talking about here is the meat of programming. We're talking about calculations. You can say:
  int a = 5;
  int b = 10;

which are statements. But in order to do anything with them you need to write some expressions. Just like in algebra, we use variables to represent numbers in calculations or expressions. Thus:
  int c, d, e; //declare new integer variables
  c = a + b; //add a and b
  d = b/a; //divide b by a
  e = c * d; //multiply c and d

Quick -- what's e equal?

Some points to note:

  • The symbols Java uses to express calculations are called operators (=, +, -, ...).
  • The single forward slash '/' is used for division, and the star '*' is used for multiplication.
  • The numbers or variables that go along with the operators are called the operands.
  • The spaces between operands and operators is totally arbitrary. You can say c=a+b; or c = a + b; or even
       c =
        a + b;
    .
  • Assigning a value to a variable in a declaration (known as 'initialization') is considered a statement, but assigning a value to a variable that is already declared (called a variable assignment) is an expression.

With that vast wealth of knowledge in hand, let's go write some expressions!



<< BACK | NEXT >>

WannaJava.com WannaJava.net WannaJava.org

WannaJava™
Copyright © 1999-2010 - All Rights Reserved
Contact Us