• No results found

BasicSyntax

N/A
N/A
Protected

Academic year: 2020

Share "BasicSyntax"

Copied!
73
0
0

Loading.... (view fulltext now)

Full text

(1)

Basic Syntax

(2)

Syntax

Comments

Reserved words

Modifiers – will cover in future classesStatements

Blocks

(3)

Comments

Used to document code

VariablesFunctionsClasses

• Ignored by the compiler

(4)

Comments

Single line comment

Used to comment a single line of code

Multiline comment

Used to comment several lines of code

Javadoc comment

Comments that are interpreted by the Javadoc

(5)

Comments

Single line comment

//

Multiline comment

Start = /*End = */

• Javadoc comment

Start = /**End = */

(6)

Comment Examples

//this is a single line comment

public class HelloWorld //also single line comment

{

/**

* This is a javadoc comment * @param args

*/

public static void main(String args[]) {

System.out.println("Hello World“/* Comment*/);

/*

multiline comment */

(7)

Reserve Words

• Words that have special meaning to the compiler

Part of the language syntax • Cannot be used as variables

• Example reserve words

public, private, new, static, final, if, else, etc…

• List of reserve words

https://docs.oracle.com/javase/tutorial/java/nutsan

dbolts/_keywords.html

(8)

Reserve Words Example

public class HelloWorld {

public static void main(String args[]) {

System.out.println("Hello World“); }

(9)

Statements

Represent an action or sequence of actions • End all statements with semicolons

(10)

Statements Example

public class HelloWorld

{

public static void main(String args[]) {

System.out.println("Hello World“);

(11)

Blocks

Separate pieces of the program • Examples:

ClassesFunctions

if/else blocksLoops

(12)

Blocks Example

public class HelloWorld

{//start block for the class

public static void main(String args[])

{//start block for the function

System.out.println("Hello World“);

}//end block for the function

(13)

Main Method

The starting point of the program • Invoked by the Java interpreter

• Takes an array of strings as input parameters

Input arguments

(14)

Main Method Example

public class HelloWorld

{

public static void main(String args[]) {

//code for program here }

(15)

Example - HelloWorld

HelloWorld.java

(16)

Variables

• Consist of letters, digits, dollar signs (‘$’) and underscores (‘_’)

Can be any length

• Cannot start with a digit

• Cannot be a reserve word

(17)

Variable Naming Convention

All words are combined into a single word

Ex: “thisIsAVariableName”

Camel Case

First word starts with a lowercase letter –Other words start with an uppercase letter

Variable names should be interpretable

–Ex: “userName”, “password”

Bad example: “xxxxxxxxx”, “di3298nyqwvt”

Do not use ‘i’, ‘j’, ‘k’, etc…

–typically used as loop variables when iterating over

(18)

Constants

• Variables that will/should never change

• Should be declared with the final key word

• Usually declared with the static key word

By convention, should be all capital letters

• By convention, words separate by underscores

• Example: PI variable in Math class

(19)

Declaring Variables

int x;

Declares ‘x’ to be an integer variable

double radius;

Declares ‘radius’ to be a double variable

char a;

Declares ‘a’ to be a character variable

(20)

Assignment Statements

Statements that assign a value to a variable

• x = 1;

• radius = 1.0;

(21)

Declaring and Initializing

Can declare and initialize a variable in one

step

• Examples

int x = 1;

double d = 1.4;

(22)

Numerical Primitive Data Types

Type Bits

(bytes) Minimum Value Maximum Value

byte 8 (1) -27 (-128) 27-1 (127)

short 16 (2) -215 (-32768) 215-1 (32767)

int 32 (4) -231 (-2147483648) 231-1 (2147483647)

long 64 (8) -263 263-1

float 32 (4) ~-1.4e-45 ~3.4e38

(23)

Numerical Operators

Operator Symbol Example Result

Addition + 5 + 2 7

Subtraction - 5 - 2 3

Multiplication * 5 * 2 10

Division / 5 / 2

5.0 / 2 2.52

Modulus % 5 % 2 1

(24)

Shortcut Assignment Operators

Operator Long

Example ExampleShort

+= x = x + 10 x += 10

-= x = x - 10 x -= 10

*= x = x * 10 x *= 10

/= x = x / 10 x /= 10

(25)

Increment Operators

• Preincrement

Increments the variable by 1 then evaluates the

new value

++x;

Postincrement

Evaluates the new value then increments the

variable by 1 then

x++;

(26)

Decrement Operators

• Predecrement

Decrements the variable by 1 then evaluates the

new value

--x

Postdecrement

Evaluates the new value then decrements the

variable by 1 then

(27)

x--Example - IncrementDecrement

IncrementDecrement.java

(28)

Floating Point Literals

• Written with a decimal point

• Default to double type

(29)

Floating Point Literals

Examples

double x = 5;

5 is considered an integer

double x = 5.0

5.0 is considered a double

double x = 5.2f

• 5.2f is considered a float

double x = 1.5e+3

x = 1500

(30)

Floating Point Numbers

Not stored as exact numbers • Stored as approximations

• Example

System.out.println(1.0 - 0.9);

Displays 0.09999999999999998 instead of 0.1.

• Keep this in minds when using them!

– Money

(31)

Example - DoubleTest

DoubleTest.java

(32)

Numeric Conversion Rules

1. If one of the operands is double, the other is converted into double.

2. Otherwise, if one of the operands is float, the other is converted into float.

3. Otherwise, if one of the operands is long, the other is converted into long.

(33)

Example - DividingIntegers

DividingIntegers.java

(34)

Example - Division 1

int x = 5;

int y = 2;

double z = x / y;

System.out.println(z);

(35)

Example - Division 1

int x = 5;

int y = 2;

double z = x / y;

System.out.println(z); // int / int = int

// 5 / 2 = 2.5

// 2.5 gets truncated to 2

(36)

int x = 5; int y = 2;

double z = (x * 1.0) / 2; System.out.println(z);

What gets printed out? Why?

(37)

int x = 5; int y = 2;

double z = (x * 1.0) / 2; System.out.println(z);

What gets printed out? Why?

int * double  double 5 * 1.0  5.0

37

(38)

int x = 5; int y = 2;

double z = (x * 1.0) / 2; System.out.println(z);

What gets printed out? Why?

double / int  double 5.0/2  2.5

(39)

Character Data Type

• Can be written as ASCII or Unicode

• ASCII

– char letter = 'A';

• Unicode

– char letter = '\u0041';

• Unicode characters start with \u

• Unicode character range

– Hexadecimal ‘\u0000’ to ‘\uffff’

– 65,536 characters

• Can use increment/decrement on char variables

(40)

Escape Characters

Character Escape Sequence

Backspace \b

Tab \t

Linefeed \n

Carriage Return \r

Backslash \\

Single Quote \‘

(41)

Example - Escape Sequences

EscapeCharacters.java

(42)

Programming Errors

Syntax Errors

Detected by the compiler

Runtime Errors

Causes the program to throw an exception

If the exception is not caught the program will end

• Logic Errors

(43)

Syntax Error Example

public class SyntaxError

{

public static void main(String[] args) {

i = 30;

System.out.println(i + 4); }

}

(44)

Runtime Error Example

public class RuntimeError

{

public static void main(String[] args) {

int i = 1 / 0; }

(45)

Logic Error Example

public class LogicError {

public static void main(String args[]) {

int number = Integer.parseInt(args[0]); if(number < 5 && number > 0)

{

System.out.println(“Number is [0, 5]”); }

}

(46)

Comparison Operators

Operator Description

< Less than

<= Less than or equal to > Greater than

>= Greater than or equal to

== Equal to

(47)

One-way if Statement

if(boolean expression)

{

//Execute statements }

• Boolean expression is enclosed in paranthesis

• No semi-colon after boolean expression

• Optional brackets around the “if” block

(48)

One-way if Statement

boolean expression

Statements

True

(49)

Two-way if Statement

if(boolean expression) {

//Execute statements if true }

else {

//Execute statements if false }

(50)

Two-way if Statement

boolean expression

Statements

True False

(51)

Multiple if Statements

if(boolean expression){/*code*/}

else if(boolean expression){/*code*/} else if(boolean expression){/*code*/} else{/*code*/}

(52)

Multiple if Statements

if(score >= 90)

{grade = ‘A’;}

else if(score >= 80) {grade = ‘B’;}

else if(score >= 70) {grade = ‘C’;}

else

(53)
(54)

Logical Operators

NOT

True when input is false

AND

True when all inputs are true

OR

True when any inputs are true

XOR

(55)

Truth Table

55 A Value B Value NOT (!A) AND (A && B) OR (A || B) XOR (A ^

B)

FALSE FALSE TRUE FALSE FALSE FALSE FALSE TRUE TRUE FALSE TRUE TRUE

(56)

Operator Precedence

• Increment and Decrement (var++, var--)

Unary Plus and Minus (+, -) • Type casting

• Not (!)

Multiplication, division, and remainder (*, /, %) • Binary addition and subtraction (+, -)

Comparisons (<, <=, >, >= )Equality (==, !=)

• Exclusive OR (^)

(57)

Operator Precedence

Parenthesis evaluated first

Inner to outer

Precedence rules are applied next

• Rules of the same precedence are evaluated left-to-right

except for assignment operators which are

evaluated right-to-left

(58)

Loops

for loops

• while loops

• do-while loops

(59)

While Loop

• Executes while a condition is true

while(condition) {

//execute code }

(60)

While Loop Example

int i= 0;

While(i < 100) {

(61)

More While Loop Conditions

while(true) • while(x < 5)

• while(!stack.empty())

• while(x<list.size())

• While(x < 5 && y > 0)

(62)

For loop

• for(initial actions, conditional, action after each iteration)

Three parameters

– Initial action = takes place before the loop starts

Conditional statement = determines if then loop continuesAction after each iteration = executes after every loop

iteration

• Any / All parameters can be empty (rarely are)

(63)

For Loop Examples

• for(int i=0; i < 7; i++)

• for(int i=0, int j=0; i<5 && j <5; i++, j=j+2)

• for(; i<7; i++)

for(; ; x+=0.5)

(64)

Break

Unlabeled

Terminates the inner most loop

Labeled

Can terminate outer loops

(65)

Break

Breaks the code flow • Breaks the loop logic

• Bad programming practice

• Anything coded with breaks can be done without breaks

• Only use in switch statements

(66)

Break Example

int x=0;

while(true) {

System.out.println(x); if(x > 10)

break; }

int x=0;

while(x <= 10) {

System.out.println(x); }

(67)

Continue

Unlabeled

Skips current iteration of the inner-most loop

Labeled

Skips the current iteration of outer loopsUses a label to find where to skip

(68)

Continue

Breaks the code flow • Breaks the loop logic

• Bad programming practice

(69)

Switch Statement

Similar to if/else if structure • Code is often nicer looking

• Used for searching for cases to execute code

(70)

Switch Example

Switch(grade) case ‘A’:

System.out.println(“Good Job”) break;

case ‘B’:

System.out.println(“Try harder”) break;

case ‘F’:

System.out.println(“Bad Job”) break;

(71)

Switch Rules

• Switch value must be a char, byte, short, or int

• Case type must match the switch type

• Code executes when case value matches the switch value

• break statements are optional

Next case will execute without breakLike “falling through” the code

• Default case is optional

Good for error checking on switch value

(72)

Nested loops

int[] someArray = {5, 3, 8, 1, 7, 0,3};

for(int i=0; i<someArray.length; i++) {

for(int j=i; j<someArray.length; j++) {

if(someArray[i] > someArray[j]) {

int temp = someArray[i];

someArray[i] = someArray[j]; someArray[j] = temp;

} }

(73)

Naming Convention

http://

www.oracle.com/technetwork/java/codeconve ntions-135099.html

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html http://www.oracle.com/technetwork/java/codeconve

References

Related documents

(2 pts) Consider a portfolio consisting of the following four European options with the same expiration date T on the underlying asset S:.. • long one call with strike 40, • long

CASE statement evaluates a explain of Boolean expressions and, scramble it finds an advance that evaluates to TRUE, executes a clap of statements associated with certain

This review focuses on an update of the / hydrolase fold family of mammalian epoxide hydrolases and their role in xenobiotic metabolism, but will also summarise the functions

By comparing the two situations with or without the returns policy in the decentralized supply chain, we conclude that the returns policy is channel coordinating and Pareto

The boolean expression is evaluated and if it evaluates to true the statement inside the if is executed and the program continues to the next executable statement.. If the

Recall rank is the maximum number of linearly independent column/row vectors for a matrix, or equivalently, the number of nonzero rows when putting a matrix in row echelon form..

The ________ function returns Boolean True value if all the keys in the dictionary are True else returns False.. Predict the output of the

Keywords: uncertainty quantification; stochastic partial differential equations; elastic wave equation; regularity; collocation method; error analysis.. AMS Subject