[Java] Intro to Variables

Awesome! We can now do simple calculations in Java! However, by plugging in equations in the display method, codes can get messier and messier. So, let’s try something new by editing the following to your codes.

public class Calc {

    public static void main(String[] args) {

        //We are declaring a variable here, remember Algebra?
        int result = (5+6)*8-1;

        System.out.print("(5+6)*8-1 = ");
        System.out.println(result);

    }

}

And you should get the exact same thing like before.

(5+6)*8-1 = 87

Wow, this is big. So Computer Science is just like elementary school Algebra? Yup, at least that’s the way I tends to think of it.

You declare a variable by starting with the keyword int, then the variable name, which must not be a reserved word like “int”. After that, you put tag on the equal sign and your mathematical expression. As always, end your line with with a semicolon (;).

Okay, let’s try something else to get a better understanding. Replace your codes inside the main method with the following:

       int a = 50;
       int b = 5;
       int c = 1
       int result = a*b+c;

        System.out.print("a*b+c = ");
        System.out.println(result);

Run it, and the result should be:

a*b+c = 251

Now, go mess around some more! Don’t do division yet though, I will go over that next lesson. It is special.

Continue to Next Lesson

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s