Docsity

OSU CSE: Operators, Expressions, Statements, and Control Flow, Study notes of Java Programming

Partial preview of the text

Download OSU CSE: Operators, Expressions, Statements, and Control Flow and more Study notes Java Programming in PDF only on Docsity!

Operators, Expressions,

Statements, Control Flow

Operators

• An operator is a symbol (or combination

of a couple symbols) that is used with

variables and values to simplify how you

write certain program expressions

  • Usually, operators are designed to mimic

mathematical notation—but do not be fooled

into confusing programming and

mathematics!

Most Common Operators

String boolean char int double

Best Practice : do not use == or != with Strings, but rather the equals method; details later.

Most Common Operators

String boolean char int double

Operators for or (||) and and (&&) use short- circuit evaluation.

Most Common Operators

String boolean char int double

Best Practice : do not check double s for equality; details later.

Expressions

• An expression is a “syntactically well-

formed and meaningful fragment” (roughly

analogous to a word in natural language)

• Meaningful?

  • It has a value (of some type, of course)

Some Expressions

• Examples of code fragments that are

expressions:

i

j + 7

"Hello" + " World!"

keyboardIn.nextLine()

n == 0 new SimpleWriter1L()

What is the type of each of these expressions?

Some Expressions

• Examples of code fragments that are

expressions:

i

j + 7

"Hello" + " World!"

keyboardIn.nextLine()

n == 0 new SimpleWriter1L()

This fragment creates a new object of type SimpleWriter1L, and its value is a reference to that object; details later.

Simple Statements

• Some examples of simple statements:

i = 12;

j += 7;

k++;

SimpleWriter fileOut =

new SimpleWriter1L("foo.txt");

fileOut.print("Hi, Mr. Foo.");

Simple Statements

• Some examples of simple statements:

i = 12;

j += 7;

k++;

SimpleWriter fileOut =

new SimpleWriter1L("foo.txt");

fileOut.print("Hi, Mr. Foo.");

This is the same as j = j + 7;

Compound Statements/Blocks

• Any sequence of zero or more statements

enclosed in {…} is a block

• Example:

String s = in.nextLine();

out.println ("s = " + s);

Compound Statements/Blocks

• Any sequence of zero or more statements

enclosed in {…} is a block

• Example:

String s = in.nextLine();

out.println ("s = " + s);

The scope of variable s is just the block in which it is declared.

Control Flow

• Conditional or selection statements

  • if
  • if-else
  • if-else-if
  • switch

• Loop or iteration statements

  • while
  • for
  • do-while

Control Flow

• Conditional or selection statements

  • if
  • if-else
  • if-else-if
  • switch

• Loop or iteration statements

  • while
  • for
  • do-while

We will normally use these, but you may use a switch statement if you like; details later.