Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public...

90
Java Java Basics 1

Transcript of Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public...

Page 1: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

1

Java

Java Basics

Page 2: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

Variables

• variable: A piece of the computer's memory that is given a name and type, and can store a value.– Like preset stations on a car stereo, or cell phone speed dial:

– Steps for using a variable:• Declare it - state its name and type• Initialize it - store a value into it• Use it - print it or use it as part of an expression

Page 3: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

4

Variables

• A variable store information such as letters, numbers, words, sentences

• A variable has three properties:– A memory location to store the value,– The type of data stored in the memory location, and– The name (identifier) used to refer to the memory location.

• Sample variable declarations:int x;int v, w, y;

Page 4: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

5

Variable declaration and initialization

• Variable declaration int x; int x,y;• Variable initialization int x; x=5;• Variable declaration and initialization int x=5;

Page 5: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

Compiler errors• A variable can't be used until it is assigned a value.

– int x;System.out.println(x); // ERROR: x has no value

• You may not declare the same variable twice.– int x;int x; // ERROR: x already exists

– int x = 3;int x = 5; // ERROR: x already exists• How can this code be fixed?

Page 6: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

7

The 8 Java Primitive data types

Numeric data types

example Number of bytes Data type byte x=5; 1 Byte

short y=12 2 Short

int x=10; 4 Integer

long s=12l; 8 Long

float r=1.2f; 4 Float

double t=4.7; 8 Double

Boolean data type

Character data type

boolean x=true;boolean y=false;

1 Boolean

char x=‘a;’ 2 Character

Page 7: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

8

Character Data Type

char letter = 'A'; (ASCII) char numChar = '4'; (ASCII)char letter = '\u0041'; (Unicode)char numChar = '\u0034'; (Unicode)

Four hexadecimal digits.

NOTE: The increment and decrement operators can also be used on char variables to get the next or preceding Unicode character. For example, the following statements display character b.

char ch = 'a'; System.out.println(++ch);

You can use ASCII characters or Unicode characters in your Java Programs

Page 8: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

9

Unicode Format Java characters use Unicode, a 16-bit encoding scheme

established by the Unicode Consortium to support the interchange, processing, and display of written texts in the world’s diverse languages. Unicode takes two bytes, preceded by \u, expressed in four hexadecimal numbers that run from '\u0000' to '\uFFFF'. So, Unicode can represent 65535 + 1 characters.

Unicode \u03b1 \u03b2 \u03b3 for three Greek letters

Page 9: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

10

Numeric Operators

Name Meaning Example Result

+ Addition 34 + 1 35 - Subtraction 34.0 – 0.1 33.9 * Multiplication 300 * 30 9000 / Division 1.0 / 2.0 0.5 % Remainder 20 % 3 2

Page 10: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

11

Integer Division

+, -, *, /, and %

5 / 2 yields an integer 2.

5.0 / 2 yields a double value 2.5

5 % 2 yields 1 (the remainder of the division)

Page 11: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

Integer division with /

• When we divide integers, the quotient is also an integer.– 14 / 4 is 3, not 3.5

3 4 52 4 ) 14 10 ) 45 27 ) 1425 12 40 135 2 5 75 54 21

• More examples:– 32 / 5 is 6– 84 / 10 is 8– 156 / 100 is 1

– Dividing by 0 causes an error when your program runs.

Page 12: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

Integer remainder with %• The % operator computes the remainder from integer division.

– 14 % 4 is 2– 218 % 5 is 3

3 43 4 ) 14 5 ) 218 12 20 2 18 15 3

• Applications of % operator:– Obtain last digit of a number: 230857 % 10 is 7– Obtain last 4 digits: 658236489 % 10000 is 6489

– See whether a number is odd: 7 % 2 is 1, 42 % 2 is 0

What is the result?45 % 62 % 28 % 2011 % 0

Page 13: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

Expressions

• expression: A value or operation that computes a value.

• Examples: 1 + 4 * 5(7 + 2) * 6 / 342

– The simplest expression is a literal value.– A complex expression can use operators and

parentheses.

Page 14: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

System.out.print

• Prints without moving to a new line– allows you to print partial messages on the same line

int highestTemp = 5;for (int i = -3; i <= highestTemp / 2; i++) { System.out.print((i * 1.8 + 32) + " ");}

• Output:26.6 28.4 30.2 32.0 33.8 35.6

Page 15: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

Printing a variable's value

• Use + to print a string and a variable's value on one line.– double grade = (95.1 + 71.9 + 82.6) / 3.0;System.out.println("Your grade was " + grade);

int students = 11 + 17 + 4 + 19 + 14;System.out.println("There are " + students + " students in the course.");

• Output:

Your grade was 83.2There are 65 students in the course.

Page 16: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

Precedence• precedence: Order in which operators are evaluated.

– Generally operators evaluate left-to-right.1 - 2 - 3 is (1 - 2) - 3 which is -4

– But */% have a higher level of precedence than +-1 + 3 * 4 is 13

6 + 8 / 2 * 36 + 4 * 36 + 12 is 18

– Parentheses can force a certain order of evaluation:(1 + 3) * 4 is 16

– Spacing does not affect order of evaluation1+3 * 4-2 is 11

Page 17: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

Precedence examples

• 1 * 2 + 3 * 5 % 4• \_/ | 2 + 3 * 5 % 4

• \_/ | 2 + 15 % 4

• \___/ | 2 + 3

• \________/ | 5

1 + 8 % 3 * 2 - 9 \_/ |1 + 2 * 2 - 9

\___/ |1 + 4 - 9

\______/ | 5 - 9

\_________/ | -4

Page 18: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

Precedence questions

• What values result from the following expressions?

– 9 / 5

– 695 % 20

– 7 + 6 * 5

– 7 * 6 + 5

– 248 % 100 / 5

– 6 * 3 - 9 / 4

– (5 - 7) * 4

– 6 + (18 % (17 - 12))

Page 19: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

Real number example• 2.0 * 2.4 + 2.25 * 4.0 / 2.0• \___/ | 4.8 + 2.25 * 4.0 / 2.0

• \___/ | 4.8 + 9.0 / 2.0

• \_____/ | 4.8 + 4.5

• \____________/ | 9.3

Page 20: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

21

Example

Page 21: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

22

Declaring constants• Java does not directly support constants. However, a final

variable is effectively a constant.• The final modifier causes the variable to be unchangeable• Java constants are normally declared in ALL CAPS

class Math{public final double PI=3.14;

}

Page 22: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

23

Comments in Java• In Java, comments are preceded:-

– by two slashes (//) in a line, – or enclosed between /* and */ in one or multiple lines.

• When the compiler sees //, it ignores all text after // in the same line. • When it sees /*, it scans for the next */ and ignores any text between /* and

*/

// This application program prints Welcome to Java!

/* This application programprints Welcome to Java! */

class A{// Author :Ahmed Alyint x;public static void m(){………..}

}

class A{int x;public static void m(){………..}

}

Compiler view

Page 23: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

Comments example/* Suzy Student, CS 101, Fall 2019 This program prints lyrics about ... something. */

public class BaWitDaBa { public static void main(String[] args) { // first verse System.out.println("Bawitdaba"); System.out.println("da bang a dang diggy diggy"); System.out.println();

// second verse System.out.println("diggy said the boogy"); System.out.println("said up jump the boogy"); }}

Page 24: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

25

Identifier• JAVA use identifiers to name variables, constants, methods, classes, and packages• An identifier is a sequence of characters that consists of letters, digits, underscores

(_), and dollar signs ($).• A n identifier cannot start with a digit.• An identifier cannot be a reserved word.• An identifier cannot be true, false, or null.• An identifier can be of any length.

$2 ComputeArea area radiusshowMessageDialog

2AA-b d+4

// author: Ahmed Alipackage racing;public class Car{String color;private int speed;private int numOfDoors=4;public void incrementSpeed(int value){…………………..}}

racing, Car, color, speed, numOfDoors, incrementSpeed are all identifiers

Page 25: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

26

Reserved WordsReserved words or keywords are words that have a specific meaning to the compiler and cannot be used for other purposes in the program. For example: class, public, static, and void.

Java uses certain reserved words called modifiers that specify the properties of the data, methods, and classes and how they can be used. For example: public ,private, finalprivate int speed;public static void getNumberOfCars(){ }

Modifiers

int speed; int class;

// author: Ahmed Alipublic class Car{String color;private int speed;private int numOfDoors=4;public void incrementSpeed(int value){…………………..}public void decrementSpeed(int value){speed=speed-value;}public int getSpeed(){…………………..}public boolean isMoving(){…………………..}public static void getNumberOfCars(){}}

Page 26: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

27

List of Java Keywords

Page 27: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

28

Literal Values for primitives

By default, a numeric literal is either a double or an int,

7 5.6int double

float x=4.7f; float x=4.7;

byte b = 1;short s = 2; Java relaxes its assignment conversion

boolean b = true;

boolean v = false;

boolean b = True;

boolean x = False;

char x=‘A’;

char x=65;

int x=1_342; int x=1342; double x=1_767.2;

Page 28: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

Strings

String name1=“Ahmed ”;String name2=“Mohamed”;String name=name1+name2;String x=7+” ”;

int y=10;//prints y=10String s=“y=“+y;

Combining variables and string

String concatenation is applied using the + operator

The data type String hold an array of charactersString values are surrounded by double quotation

String name1=“Ahmed ”;

String name1=new String(“Ahmed ”);

Page 29: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

String concatenation• string concatenation: Using + between a string and another value

to make a longer string."hello" + 42 is "hello42"1 + "abc" + 2 is "1abc2""abc" + 1 + 2 is "abc12"1 + 2 + "abc" is "3abc""abc" + 9 * 3 is "abc27""1" + 1 is "11"4 - 1 + "abc" is "3abc"

• Use + to print a string and an expression's value together.– System.out.println("Grade: " + (95.1 + 71.9) / 2);

• Output: Grade: 83.5

Page 30: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

31

Primitive data type conversion

A primitive data type can be converted to another type, provided the conversion is a widening conversion

int i=12;double d=i;

1-Conversion by Assignment

2-Conversion by Method call

class test{void m1(){int i=9;m2(i); }void m2(double d){///}}

•All operands are set to the wider type of them •The promotion should be to at least int

3-Conversion by Arithmatic Promotion

short s1=7;short s2=13;// short s3=s1+s2; compile error as s1,s2 are converted to intint i=s1+s2;

Page 31: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

32

Primitive CastingCasting is explicitly telling Java to make a conversion. A casting operation may widen or narrow its argument. To cast, just precede a value with the parenthesized name of the desired type.

int i=12;

short s=(short)i;

short s=i;int i = d;

double d = 4.5;

int i = (int)d;

int i=4 +7.0;

int i=(int) (4 +7.0);

int i=7;short i=i +3;

int i;short s=(short) (i +3);

Page 32: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

33

Casting between char and Numeric Types

int i = 'a'; // Same as int i = (int)'a';The Unicode of character a is assigned to i

char c = 97; // Same as char c = (char)97;

The lower 16 are used as the unicode

Page 33: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

Mixing types

• When int and double are mixed, the result is a double.– 4.2 * 3 is 12.6

• The conversion is per-operator, affecting only its operands.– 7 / 3 * 1.2 + 3 / 2– \_/

| 2 * 1.2 + 3 / 2

– \___/ | 2.4 + 3 / 2

– \_/ | 2.4 + 1

– \________/ | 3.4

– 3 / 2 is 1 above, not 1.5.

2.0 + 10 / 3 * 2.5 - 6 / 4 \___/ |2.0 + 3 * 2.5 - 6 / 4

\_____/ |2.0 + 7.5 - 6 / 4

\_/ |2.0 + 7.5 - 1

\_________/ | 9.5 - 1

\______________/ | 8.5

Page 34: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

Java Operators

• Arithmetic+,-,*,/,%,++,--

• Logic&,|,~,&&,||

• Assignment=, +=, -=, etc..

• Comparison<,<=,>,>=,==,!=

• Work just like in C/C++,

Page 35: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

Increment and decrement

shortcuts to increase or decrease a variable's value by 1

Shorthand Equivalent longer versionvariable++; variable = variable + 1;variable--; variable = variable - 1;

int x = 2;x++; // x = x + 1;

// x now stores 3

double gpa = 2.5;gpa--; // gpa = gpa - 1;

// gpa now stores 1.5

Page 36: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

Modify-and-assign operatorsshortcuts to modify a variable's value

Shorthand Equivalent longer versionvariable += value; variable = variable + value;variable -= value; variable = variable - value;variable *= value; variable = variable * value;variable /= value; variable = variable / value;variable %= value; variable = variable % value;

x += 3; // x = x + 3;

gpa -= 0.5; // gpa = gpa - 0.5;

number *= 2; // number = number * 2;

Page 37: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

Java's Math classMethod name Description

Math.abs(value) absolute value

Math.round(value) nearest whole number

Math.ceil(value) rounds up

Math.floor(value) rounds down

Math.log10(value) logarithm, base 10

Math.max(value1, value2) larger of two values

Math.min(value1, value2) smaller of two values

Math.pow(base, exp) base to the exp power

Math.sqrt(value) square root

Math.sin(value)Math.cos(value)Math.tan(value)

sine/cosine/tangent ofan angle in radians

Math.toDegrees(value)Math.toRadians(value)

convert degrees toradians and back

Math.random() random double between 0 and 1

Constant Description

E 2.7182818...

PI 3.1415926...

Page 38: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

Calling Math methodsMath.methodName(parameters)

• Examples:double squareRoot = Math.sqrt(121.0);System.out.println(squareRoot); // 11.0

int absoluteValue = Math.abs(-50);System.out.println(absoluteValue); // 50

System.out.println(Math.min(3, 7) + 2); // 5

• The Math methods do not print to the console.– Each method produces ("returns") a numeric result.– The results are used as expressions (printed, stored, etc.).

Page 39: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

Return

• return: To send out a value as the result of a method.– The opposite of a parameter:• Parameters send information in from the caller to the

method.• Return values send information out from a method to

its caller.main

Math.abs(-42)

-42

Math.round(2.71)

2.71

42

3

Page 40: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

Math questions• Evaluate the following expressions:

– Math.abs(-1.23)– Math.pow(3, 2)– Math.pow(10, -2)– Math.sqrt(121.0) - Math.sqrt(256.0)– Math.round(Math.PI) + Math.round(Math.E)– Math.ceil(6.022) + Math.floor(15.9994)– Math.abs(Math.min(-3, -5))

• Math.max and Math.min can be used to bound numbers.

Consider an int variable named age.– What statement would replace negative ages with 0?– What statement would cap the maximum age to 40?

Page 41: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

Input and System.in

• System.out– An object with methods named println and print

• System.in– not intended to be used directly– We use a second object, from a class Scanner, to help us.

• Constructing a Scanner object to read console input:Scanner name = new Scanner(System.in);

– Example:Scanner console = new Scanner(System.in);

Page 42: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

Hint: Reading integers from Console

43

class ScannerDemo{public static void main (String [] arg){java.util.Scanner scan=new java.util.Scanner (System.in);System.out.println("Please Enter first number");int num1=scan.nextInt();System.out.println("Please Enter Second number");int num2=scan.nextInt();int sum=num1+num2;System.out.println("The sum of " + num1 +" and "+num2+"="+sum);

}}

Page 43: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

Java class libraries, import• Java class libraries: Classes included with Java's JDK.

– organized into groups named packages– To use a package, put an import declaration in your program.

• Syntax:// put this at the very top of your programimport packageName.*;

• Scanner is in a package named java.util

import java.util.*;

– To use Scanner, you must place the above line at the top of your program (before the public class header).

Page 44: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

Scanner methods

– Each method waits until the user presses Enter.• The value typed is returned.

System.out.print("How old are you? "); // promptint age = console.nextInt();System.out.println("You'll be 40 in " + (40 - age) + " years.");

• prompt: A message telling the user what input to type.

Method DescriptionnextInt() reads a token of user input as an int

nextDouble() reads a token of user input as a double

next() reads a token of user input as a String

nextLine() reads a line of user input as a String

Page 45: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

Example Scanner usageimport java.util.*; // so that I can use Scanner

public class ReadSomeInput { public static void main(String[] args) { Scanner console = new Scanner(System.in);

System.out.print("How old are you? "); int age = console.nextInt();

System.out.println(age + "... That's quite old!");

}}

• Output (user input underlined):

How old are you? 1414... That's quite old!

Page 46: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

Another Scanner exampleimport java.util.*; // so that I can use Scanner

public class ScannerSum { public static void main(String[] args) { Scanner console = new Scanner(System.in);

System.out.print("Please type three numbers: "); int num1 = console.nextInt(); int num2 = console.nextInt(); int num3 = console.nextInt();

int sum = num1 + num2 + num3; System.out.println("The sum is " + sum); }}

• Output (user input underlined):Please type three numbers: 8 6 13The sum is 27

– The Scanner can read multiple values from one line.

Page 47: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

• The for loop is similar to C/C++• Java also has support for continue and break

keywords• Again, work very similar to C/C++

Control Structures

for(int i = 0; i < 10; i++) { a += i; if(a > 100) break;}

for(int i = 0; i < 10; i++) { if(i == 5) continue; a += i;}

Page 48: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

The if statement

Executes a block of statements only if a test is true

if (test) { statement; ... statement;}

• Example:double gpa = console.nextDouble();if (gpa >= 2.0) { System.out.println("Application accepted.");}

Page 49: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

The if/else statementExecutes one block if a test is true, another if false

if (test) { statement(s);} else { statement(s);}

• Example:double gpa = console.nextDouble();if (gpa >= 2.0) { System.out.println("Welcome to Mars University!");} else { System.out.println("Application denied.");}

Page 50: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

Nested if/else/if– If it ends with else, one code path must be taken.– If it ends with if, the program might not execute any path.

if (test) { statement(s);} else if (test) { statement(s);} else if (test) { statement(s);}

• Example:if (place == 1) { System.out.println("You win the gold medal!");} else if (place == 2) { System.out.println("You win a silver medal!");} else if (place == 3) { System.out.println("You earned a bronze medal.");}

Page 51: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

Factoring if/else code

• factoring: extracting common/redundant code– Factoring if/else code can reduce the size of if/else

statements or eliminate the need for if/else altogether.

• Example:if (a == 1) { x = 3;} else if (a == 2) { x = 6; y++;} else { // a == 3 x = 9;}

x = 3 * a;if (a == 2) { y++;}

Page 52: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

Code in need of factoringif (money < 500) { System.out.println("You have, $" + money + "

left."); System.out.print("Caution! Bet carefully."); System.out.print("How much do you want to bet? "); bet = console.nextInt();} else if (money < 1000) { System.out.println("You have, $" + money + "

left."); System.out.print("Consider betting moderately."); System.out.print("How much do you want to bet? "); bet = console.nextInt();} else { System.out.println("You have, $" + money + "

left."); System.out.print("You may bet liberally."); System.out.print("How much do you want to bet? "); bet = console.nextInt();}

Page 53: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

if/else question

A person's body mass index(BMI) is defined to be:

• Write a program that produces the following output:This program reads data for two people and computestheir body mass index (BMI) and weight status.Enter next person's information:height (in inches)? 70.0weight (in pounds)? 194.25Enter next person's information:height (in inches)? 62.5weight (in pounds)? 130.5Person #1 body mass index = 27.87overweightPerson #2 body mass index = 23.49normalDifference = 4.38

7032

height

weightBMI

BMI Weight class

below 18.5 underweight

18.5 - 24.9 normal

25.0 - 29.9 overweight

30.0 and up obese

Page 54: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

if/else, return question

• Write a class countFactors that returnsthe number of factors of an integer.– countFactors(24) returns 8 because

1, 2, 3, 4, 6, 8, 12, and 24 are factors of 24.

• Write a program that prompts the user for a maximum integer and prints all prime numbers up to that max.Maximum number? 522 3 5 7 11 13 17 19 23 29 31 37 41 43 4715 primes (28.84%)

Page 55: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

Relational expressions

• A test in an if is the same as in a for loop.

for (int i = 1; i <= 10; i++) { ...if (i <= 10) { ...

– These are boolean expressions, seen in Ch. 5.

• Tests use relational operators:Operato

rMeaning Example Value

== equals 1 + 1 == 2

true

!= does not equal 3.2 != 2.5

true

< less than 10 < 5 false

> greater than 10 > 5 true

<= less than or equal to 126 <= 100

false

>= greater than or equal to 5.0 >= 5.0

true

Page 56: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

Logical operators: &&, ||, !

• Conditions can be combined using logical operators:

• "Truth tables" for each, used with logical values p and q:

Operator

Description

Example Result

&& and (2 == 3) && (-1 < 5)

false

|| or (2 == 3) || (-1 < 5)

true

! not !(2 == 3) true

p q p && q p || q

true true true true

true false

false true

false

true false true

false

false

false false

p !p

true false

false

true

Page 57: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

Evaluating logic expressions• Relational operators have lower precedence than math.

5 * 7 >= 3 + 5 * (7 - 1)5 * 7 >= 3 + 5 * 635 >= 3 + 3035 >= 33true

• Relational operators cannot be "chained" as in algebra.

2 <= x <= 10 (assume that x is 15)true <= 10 error!

– Instead, combine multiple tests with && or ||

2 <= x && x <= 10 (assume that x is 15)true && false false

Page 58: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

Logical questions

• What is the result of each of the following expressions?int x = 42;int y = 17;int z = 25;

– y < x && y <= z– x % 2 == y % 2 || x % 2 == z % 2– x <= y + z && x >= y + z– !(x < y && x < z)– (x + y) % 2 == 0 || !((z - y) % 2 == 0)

• Answers: true, false, true, true, false

Page 59: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

Control Structures

• if/else, for, while, do/while, switch• Basically work the same as in C/C++

if(a > 3) { a = 3;}else { a = 0;}

for(i = 0; i < 10; i++) { a += i;}

i = 0;while(i < 10) { a += i; i++;}

i = 0;do { a += i; i++;} while(i < 10);

switch(i) { case 1: string = “foo”; case 2: string = “bar”; default: string = “”;}

Page 60: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

The while loop• while loop: Repeatedly executes its

body as long as a logical test is true.while (test) { statement(s);}

• Example:int num = 1; // initializationwhile (num <= 200) { // test System.out.print(num + " "); num = num * 2; // update}

– OUTPUT:1 2 4 8 16 32 64 128

Page 61: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

A deceptive problem...

• Write a method printNumbers that prints each number from 1 to a given maximum, separated by commas.

For example, the call:printNumbers(5)

should print:1, 2, 3, 4, 5

Page 62: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

for loop syntaxfor (initialization; test; update) { statement; statement; ... statement;}

– Perform initialization once.– Repeat the following:

• Check if the test is true. If not, stop.• Execute the statements.• Perform the update.

body

header

Page 63: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

Initializationfor (int i = 1; i <= 6; i++) { System.out.println(i + " squared = " + (i * i));}

• Tells Java what variable to use in the loop

– Called a loop counter

• Can use any variable name, not just i• Can start at any value, not just 1

Page 64: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

Testfor (int i = 1; i <= 6; i++) { System.out.println(i + " squared = " + (i * i));}

• Tests the loop counter variable against a bound

– Uses comparison operators:< less than<= less than or equal to> greater than>= greater than or equal to

Page 65: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

Updatefor (int i = 1; i <= 6; i++) { System.out.println(i + " squared = " + (i * i));}

• Changes loop counter's value after each repetition– Without an update, you would have an infinite loop

– Can be any expression:for (int i = 1; i <= 9; i += 2) { System.out.println(i);}

Page 66: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

Loop walkthrough

for (int i = 1; i <= 4; i++) { System.out.println(i + " squared = " + (i * i));}System.out.println("Whoo!");

Output:1 squared = 12 squared = 43 squared = 94 squared = 16Whoo!

1

1

2

2

3

3

4

4

5

5

Page 67: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

Fixed cumulative sum loop

• A corrected version of the sum loop code:int sum = 0;for (int i = 1; i <= 1000; i++) { sum = sum + i;}System.out.println("The sum is " + sum);

Key idea:

– Cumulative sum variables must be declared outside the loops that update them, so that they will exist after the loop.

Page 68: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

Cumulative product

• This cumulative idea can be used with other operators:int product = 1;for (int i = 1; i <= 20; i++) { product = product * 2;}System.out.println("2 ^ 20 = " + product);

– How would we make the base and exponent adjustable?

Page 69: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

Multi-line loop bodySystem.out.println("+----+");for (int i = 1; i <= 3; i++) { System.out.println("\\ /"); System.out.println("/ \\");}System.out.println("+----+");

– Output:+----+\ // \\ // \\ // \+----+

Page 70: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

Loops with if/else

• if/else statements can be used with loops or methods: int evenSum = 0;int oddSum = 0;

for (int i = 1; i <= 10; i++) { if (i % 2 == 0) { evenSum = evenSum + i; } else { oddSum = oddSum + i; }}

System.out.println("Even sum: " + evenSum);System.out.println("Odd sum: " + oddSum);

Page 71: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

int highTemp = 5;for (int i = -3; i <= highTemp / 2; i++) { System.out.println(i * 1.8 + 32);}

– Output:26.628.430.232.033.835.6

Expressions for counter

Page 72: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

Counting down

• The update can use -- to make the loop count down.– The test must say > instead of <

System.out.print("T-minus ");for (int i = 10; i >= 1; i--) { System.out.print(i + ", ");}System.out.println("blastoff!");

– Output:T-minus 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, blastoff!

Page 73: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

Loop tables• What statement in the body would cause the loop to print:

2 7 12 17 22

• To see patterns, make a table of count and the numbers.– Each time count goes up by 1, the number should go up by 5.– But count * 5 is too great by 3, so we subtract 3.

count

number to print 5 * count

1 2 5

2 7 10

3 12 15

4 17 20

5 22 25

5 * count - 3

2

7

12

17

22

Page 74: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

Loop tables question• What statement in the body would cause the loop to print:

17 13 9 5 1

• Let's create the loop table together.– Each time count goes up 1, the number printed should ...– But this multiple is off by a margin of ...

count

number to print

1 17

2 13

3 9

4 5

5 1

-4 * count -4 * count + 21

-4 17

-8 13

-12 9

-16 5

-20 1

-4 * count

-4

-8

-12

-16

-20

Page 75: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

Redundancy between loopsfor (int j = 1; j <= 5; j++) { System.out.print(j + "\t");}System.out.println();

for (int j = 1; j <= 5; j++) { System.out.print(2 * j + "\t");}System.out.println();

for (int j = 1; j <= 5; j++) { System.out.print(3 * j + "\t");}System.out.println();

for (int j = 1; j <= 5; j++) { System.out.print(4 * j + "\t"){}System.out.println();

Output:1 2 3 4 5 2 4 6 8 10 3 6 9 12 15 4 8 12 16 20

Page 76: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

Nested loops• nested loop: A loop placed inside another loop.

for (int i = 1; i <= 4; i++) { for (int j = 1; j <= 5; j++) { System.out.print((i * j) + "\t"); } System.out.println(); // to end the line}

• Output:1 2 3 4 5 2 4 6 8 10 3 6 9 12 15 4 8 12 16 20

• Statements in the outer loop's body are executed 4 times.– The inner loop prints 5 numbers each time it is run.

Page 77: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

Nested for loop exercise• What is the output of the following nested for loops?

for (int i = 1; i <= 6; i++) { for (int j = 1; j <= 10; j++) { System.out.print("*"); } System.out.println();}

• Output:************************************************************

Page 78: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

Complex lines

• What nested for loops produce the following output?

....1

...2

..3

.45

• We must build multiple complex lines of output using:– an outer "vertical" loop for each of the lines– inner "horizontal" loop(s) for the patterns within each line

outer loop (loops 5 times because there are 5 lines)

inner loop (repeated characters on each line)

Page 79: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

Outer and inner loop• First write the outer loop, from 1 to the number of lines.

for (int line = 1; line <= 5; line++) { ...}

• Now look at the line contents. Each line has a pattern:– some dots (0 dots on the last line)– a number

....1

...2

..3

.45

Page 80: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

Nested for loop exercise• What is the output of the following nested for loops?

for (int line = 1; line <= 5; line++) { for (int j = 1; j <= (-1 * line + 5); j++) { System.out.print("."); } for (int k = 1; k <= line; k++) { System.out.print(line); } System.out.println();}

• Answer:....1...22..333.444455555

Page 81: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

Drawing complex figures

• Use nested for loops to produce the following output.

• Why draw ASCII art?– Real graphics require a lot of finesse– ASCII art has complex patterns– Can focus on the algorithms

#================#| <><> || <>....<> || <>........<> ||<>............<>||<>............<>|| <>........<> || <>....<> || <><> |#================#

Page 82: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

83

3 Type of Errors might be in your program

i-Compile ErrorsCompile errors occurs on attempting to compile your fileCompile errors prevent the creation of the .class fileCompile error occurs when a syntax rule is not obeyed

ii-Runtime ErrorsRuntime errors occurs after the program has compiled successfully and is running Runtime error in java are called ExceptionsExceptions can occur for many reasons including a wrong input from user or a certain resource (eg. A file) that was not found.

iii-Logic ErrorThe class compiled and run without reporting any errorsThe task is not executed correctly due to algorithmic error

Page 83: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

84

Exercises

• Using just the ahead and turnRight/turnLeft methods create a robot that travels in a complete square once, beginning from its starting position. Make the robot travel 150 units for each side of the square.

• Using a for loop create a robot that travels in a complete square 10 times.

• Adapt the code so that it uses a loop that repeats four times to control the forward movement and turns.

Page 84: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

85

• The main voltage supplied by a substation is measured at hourly intervals over a 72-hour period, and a report made. Write a program to read in the 72 reading array and determine:

• the mean voltage measured• the hours at which the recorded voltage varies from

the mean by more than 10%• any adjacent hours when the change from one

reading to the next is greater than 15% of the mean value

Page 85: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

86

• We wish to solve the following problem using Java. given an array A, print all permutations of A (print all values of A in every possible order). For example, A contained the strings “apple”, “banana”, and “coconut”, the desired output is:

• apple banana coconut• apple coconut banana• banana apple coconut• banana coconut apple• coconut apple banana• coconut banana apple

Page 86: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

87

• Write a Java application which prints a triangle of x's and y's like the one below. Each new line will have one more x or y than the preceding line. The program should stop after it prints a line with 80 characters in it. You may make use of both the

• Write() and WriteLine() methods. For example;• x• yy• xxx• yyyy• xxxxx

Page 87: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

88

• A year with 366 days is called a leap year. A year is a leap year if it is divisible by 4 (for example, 1980). However, since the introduction of the Gregorian calendar on October 15, 1582, a year is not a leap year if it is divisible by 100 (for example, 1900); however, it is a leap year if it is divisible by 400 (for example, 2000). Write program (not a whole class) that accepts an int argument called “year” and returns true if the year is a leap year and false otherwise.

Page 88: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

89

• A number of students are answering a questionnaire form that has 25 questions. Answer to each question is given as an integer number ranging from 1 to 5. Write a program that first reads the number of students that have left the fulfilled questionnaire. After that the programs reads answers so that first answers of the first student are entered starting from question 1 and ending to question 25.

• Answers of second student are then read in similar way. When all answers are entered the program finds out what are questions (if any) to which all students have given the same answer. Finally the program displays those questions (the question numbers).

Page 89: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

90

• Write a console application that inputs the grads of 100 students and counts the number of students with grad ‘A’ or ‘a’ and ‘B’ or ‘b’ and ‘C’ or ‘c’ and ‘D’ or ‘d’ and ‘F’ or ‘f’

Page 90: Java Java Basics 1. A Simple Java Program // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args)

91

• Using a while loop create a robot that travels in a square forever (or until the round ends anyway).

• Alter your robot so that it counts the number of squares it has travelled and writes this to the console.