In the last lesson we discussed about: Objects and Instances Declaring Variables

1 / 9

# In the last lesson we discussed about: Objects and Instances Declaring Variables - PowerPoint PPT Presentation

Review. In the last lesson we discussed about: Objects and Instances Declaring Variables The “=“ used as an assignment operator We also looked at the ACM hierarchy. Casting and Precedence.

I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.

## PowerPoint Slideshow about ' In the last lesson we discussed about: Objects and Instances Declaring Variables' - page

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

Review

• In the last lesson we discussed about:
• Objects and Instances
• Declaring Variables
• The “=“ used as an assignment operator
• We also looked at the ACM hierarchy

Casting and Precedence

• When performing arithmetic operations in Java we have to understand how precedence (priority) works.
• First priority is given to parenthesis ()
• Second *, /, %
• Least +,-
• Starting from left to right

For example:

• X = 1 + 3 * 5 / 2;
• Lets see how this will evaluate.
• 3 * 5 = 15
• 15 / 2 = 7 (Integer division)
• X=8

Divide integers but get real

• int x = 5; (Integer division)
• double y = x / 2;
• Evaluates the right side first and then returns the answer to the left side
• In order to get a double value we will use a process called CAST!

CAST is just like in a film!

• Just like a film has a cast of characters who act temporarily to fulfill a role similarly in Java a cast is a conversion of one data type to another.

For e.g.:

int x=5;

double y = (double) x/2 (x remains as an integer)

y now contains 2.5 due to the casting on the right side of the equal sign

Calculate Average

• import acm.program.*;
• public class CalculateAverage extends ConsoleProgram {

public void run() {

println(“This program requires two numbers:”);

double avg = n1 + n2 / 2; //BUGGY!

println(“The average is:” + avg + “.”);

}

• } // Whats the problem here?

Short hands

• Seems like x = x +1 is very commonly used in programming languages
• There are short hands for doing this:
• x+=1;
• x++;
• x-=1;
• x--;
• x*=2;
• x/=2;

Constants

• Lets have a look at an example of area of a circle.
• double PI =3.14;
• double A = PI * r * r;
• PI is a variable and it can be changed which means the whole equation will change.
• Defining:
• private static final double PI=3.14;
• You could come up with a constant called SEVENTY_TWO=72