Java Concepts Java Basics

27
Java Basics (continued) Mr. Smith AP Computer Science A

description

basic concepts of java are presented here for a quick recapitulation for the amateurs and a glance for the beginners.

Transcript of Java Concepts Java Basics

Page 1: Java Concepts Java Basics

Java Basics(continued)

Mr. SmithAP Computer Science

A

Page 2: Java Concepts Java Basics

Basic Java Syntax and SemanticsMethods, Messages, and Signatures

Classes implement methods, and objects are instances of classes.

Objects that share common behavior are grouped into classes.

An object responds to a message only if its class implements a corresponding method.

To correspond the method must have the same name as the message. Messages are sometimes accompanied by

parameters and sometimes not:pen.move(); // No parameter expectedpen.moveDown(8); // One parameter expected

Java Concepts 2.3 (Objects, Classes, and Methods), 2.4 (Method Parameters and return values)

Page 3: Java Concepts Java Basics

Basic Java Syntax and Semantics

Some methods return a value and others do not.

To use a method successfully we must know: What type of value it returns It’s name (identifier) The number and type of the parameters

it expects This information is called the

method’s signature.Java Concepts 2.3 (Objects, Classes, and Methods), 2.4 (Method Parameters and return values)

Page 4: Java Concepts Java Basics

Basic Java Syntax and Semantics

Programming Protocols: Use camelCase

When forming a compound variable name, programmers usually capitalize the first letter of each word except the first. (For example: taxableIncome)

All the words in a program’s name typically begin with a capital letter (ComputeEmployeePayroll).

Constant names usually are all uppercase (TAX_RATE).

Java Concepts 2.1 (Types and Variables)

Page 5: Java Concepts Java Basics

Comments Comments are explanatory

sentences inserted in a program in such a matter that the compiler ignores them.

There are two styles for indicating comments: End of line comments:

These include all of the text following a double slash (//) on any given line; in other words, this style is best for just one line of comments

Multiline comments: These include all of the text between an opening /* and a closing */ Java Concepts 1.6 (Compiling a Simple Program)

Page 6: Java Concepts Java Basics

Additional Operators

Extended Assignment Operators The assignment operator can be combined

with the arithmetic and concatenation operators to provide extended assignment operators. For example:

int a = 17;String s = "hi";a += 3; // Equivalent to a = a + 3;a -= 3; // Equivalent to a = a – 3;a *= 3; // Equivalent to a = a * 3;a /= 3; // Equivalent to a = a / 3;a %= 3; // Equivalent to a = a % 3;s += " there"; // Equivalent to s = s + “

there”;Java Concepts 4.3 (Assignment, Increment, and Decrement)

Page 7: Java Concepts Java Basics

Additional Operators

Increment and Decrement Java includes increment (++) and

decrement (--) operators that increase or decrease a variables value by one:

int m = 7;double x = 6.4;m++; // Equivalent to m = m + 1;x--; // Equivalent to x = x – 1.0;

The precedence of the increment and decrement operators is the same as unary plus, unary minus, and cast.

Java Concepts 4.3 (Assignment, Increment, and Decrement)

Page 8: Java Concepts Java Basics

Standard Classes and Methods

Eight methods in the Math Class

static double random() Returns a double in the range [0.0, 1.0)Java Concepts 4.4 (Arithmetic Operations and Mathematical Functions)

Page 9: Java Concepts Java Basics

Standard Classes and Methods

Using the Math class

double absNum, powerNum, randomNum;

absNum = Math.abs(-30);powerNum = Math.pow(-3, 3);randomNum = Math.random();

Results:absNum = 30 //Absolute value of -30powerNum = -27 //-3 to the 2nd powerrandomNum = ????? //Random number between 0 and 1

Java Concepts 4.4 (Arithmetic Operations and Mathematical Functions)

Page 10: Java Concepts Java Basics

Standard Classes and Methods

Random Numbers and Simulation The Random class of the Java library implements

a random number generator. To generate random numbers, you construct an

object of the Random class and then apply one of the following methods: nextInt(n) – returns a random integer between 0

(inclusive) and n (exclusive) nextDouble() – returns a random floating point

number between 0 (inclusive) and 1 (exclusive) For example, if a contestant on “Deal or No Deal”

is randomly selecting their briefcase from the 26 initial briefcases:import java.util.Random; //Include this at top of program Random generator = new Random();int briefcaseNum = 1 + generator.nextInt(26);Java Concepts 6.5 (Random Numbers and Simulation)

Page 11: Java Concepts Java Basics

Classwork/HomeworkDiceRoller program (similar to Yahtzee):

Write a program to: Allow the person to initially roll five dice.

Each die has six faces representing numbers from 1 to 6.

Print the results of each die to the console. After the first roll, the person should input the number

of dice (between 0 and 5) that they want to roll again.

If they enter 0, then stop. Else, roll that many dice and print the results of

each die to the console again. Repeat the prompt one more time to see if the person

wants to roll some of the dice again (for a maximum of 3 rolls).

Note: You may want to use the Scanner class to input data, the Random class to generate a random number, a for loop for rolling the dice, an if statement for checking the input and a break command to exit the loop, and System.out.print for printing to the console.Java Concepts 6.5 (Random Numbers and Simulation)

Page 12: Java Concepts Java Basics

Control Statements

while (some condition){ do stuff;}

Do stuff repeatedly as long as the condition holds true

if (some condition){ do stuff 1;}else{ do stuff 2;}

If some condition is true, do stuff 1, and if it is false, do stuff 2.

While and if-else are called control statements.

Java Concepts 5.1 (The if Statement), 6.1 (while Loops)

Page 13: Java Concepts Java Basics

The if and if-else Statements

Principal Forms In Java, the if and if-else statements allow for

the conditional execution of statements.if (condition){ statement1; statement2;}

if (condition){ statement1; statement2;}else{ statement3; statement4;} Java Concepts 5.1 (The if Statement)

Page 14: Java Concepts Java Basics

The if and if-else Statements

Relational Operators

The complete list of relational operators available for use in Java.

Java Concepts 5.2 (Comparing values)

Page 15: Java Concepts Java Basics

The if and if-else Statements

Relational Operators

Which of the following if statements are incorrect?

int x;

1. if ( x > 10 )2. if ( x = 10 )3. if ( x >< 10 )4. if ( x == 10 )5. if ( x >= 10 ) 6. if ( x != 10 )

Incorrect

Incorrect

Java Concepts 5.2 (Comparing values)

Page 16: Java Concepts Java Basics

The while Statement The while statement provides a looping mechanism

that executes statements repeatedly for as long as some condition remains true.

while (condition) // loop teststatement; //one statement inside the loop body

while (condition) // loop test{ statement; // many statements statement; // inside the ... // loop body}

Java Concepts 6.1 (while Loops)

Page 17: Java Concepts Java Basics

The while Statement

Common Structure Loops typically adhere to the following

structure:initialize variables //initializewhile (condition) //test{

perform calculations or do something and //loop bodychange variables involved in the condition //loop body

}

In order for the loop to terminate, each iteration through the loop must move variables involved in the condition significantly closer to satisfying the condition.

Java Concepts 6.1 (while Loops)

Page 18: Java Concepts Java Basics

The while Statement

1. Write a while loop that will sum the numbers from 1 to 100 (i.e. 1+2+3+… +100).

2. Print the answer to the console.

Java Concepts 6.1 (while Loops)

Page 19: Java Concepts Java Basics

The while Statement

int sum = 0;int count = 1;while (count <= 100){ sum += count;

count++;}System.out.println (sum);

Java Concepts 6.1 (while Loops)

Page 20: Java Concepts Java Basics

The for Statement The for statement combines counter

initialization, condition test, and update into a single expression.

The form for the statement:for (initialize counter; test counter; update counter)

statement; // one statement inside the loop body

for (initialize counter; test counter; update counter){ statement; // many statements statement; // inside the

. . .; // loop body } Java Concepts 6.2 (for Loops)

Page 21: Java Concepts Java Basics

The for Statement

Declaring the Loop Control Variable in a for Loop.

The for loop allows the programmer to declare the loop control variable inside of the loop header.

The following are equivalent loops that show these two alternatives:

int i; //Declare control variable above loop

for (i = 1; i <= 10; i++)System.out.println(i);

for (int i = 1; i<= 10; i++) //Declare variable in loop header

System.out.println(i);

Use this technique if you need to

reference the value of i later

Use this technique if you only use variable

i within the loopJava Concepts 6.2 (for Loops)

Page 22: Java Concepts Java Basics

Nested Control Statements and the break Statement

Control statements can be nested inside each other in any combination that proves useful.

The break statement can be used for breaking out of a loop early, that is before the loop condition is false.

If you are nesting loops, the break statement only breaks out of the loop the program is currently in (the inside loop).

break statements can be used similarly with both for loops and while loops (break terminates the loop immediately).

Java Concepts 6.4 Advanced Topic (break and continue Statements)

Page 23: Java Concepts Java Basics

Sentinel

A data value that is used to denote the end of a data list or data input.

The value cannot be a valid data value Usually 99999 or an unreachable high

value or it could be a character such as “Q” for Quit.

Example: Enter your age or type “Q” to quit. Note: if you do it this way then the value you enter needs to be a string.

Java Concepts 6.4 (Processing Sentinel Values)

Page 24: Java Concepts Java Basics

Sentinel

Write a segment of code that will have the user input data values and then do something until the user indicates there are no more data values.

Java Concepts 6.4 (Processing Sentinel Values)

Page 25: Java Concepts Java Basics

SentinelWrite a segment of code that will read in data values and do something until there are no more.

OPTION 1: int num;

boolean done = false; while ( ! done) {

System.out.print(“enter a value, 99 to end “); num = in.nextInt(); if (num == 99)

{ done = true;}else{ // rest of code to do something goes here}

}

Java Concepts 6.4 (Processing Sentinel Values)

Page 26: Java Concepts Java Basics

Sentinel

Write a segment of code that will read in data values and do something until there are no more.

OPTION 2: int num;while (true)

{ System.out.print(“enter a value, 99 to end “);

num = in.nextInt(); if (num == 99)

{ break;}// rest of code to do something goes here

}

Java Concepts 6.4 (Processing Sentinel Values)

Page 27: Java Concepts Java Basics

Classwork/Homework

CircleCalc program:Write a program to: Have the user input the diameter of a circle and the program

outputs the: Radius (which is the diameter divided by 2) Circumference (which is PI times the diameter) Area (which is PI times the radius squared) Note: you can use Math.PI to get the value of PI

Use a for loop to prompt the user 4 times (4 circle diameters) and print the radius, circumference, and area each time.

Then use a sentinel controlled loop (sentinel value should be 99999) to do the same thing.

Test input for validity.

What is the advantage of using a sentinel controlled loop?It allows the user to stop the looping whenever they want