Basic Java Syntax, cont d. COMP 401, Fall 2015 Lecture 3 1/15/2015

Similar documents
Basic Java Syntax. COMP 401, Fall 2015 Lecture 2 1/13/2014

Java Programming Basics. COMP 401, Spring 2017 Lecture 2

Java Programming Basics. COMP 401, Fall 2017 Lecture 2

Strings and Arrays. COMP 401, Fall 2017 Lecture 4

Operators. Java operators are classified into three categories:

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

CT 229 Java Syntax Continued

WEEK 4 OPERATORS, EXPRESSIONS AND STATEMENTS

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Flow Control. CSC215 Lecture

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Full file at

(Not Quite) Minijava

CGS 3066: Spring 2015 JavaScript Reference

CprE 288 Introduction to Embedded Systems Exam 1 Review. 1

Programming with Java

YOLOP Language Reference Manual

CS313D: ADVANCED PROGRAMMING LANGUAGE

Lexical Considerations

Pull Lecture Materials and Open PollEv. Poll Everywhere: pollev.com/comp110. Lecture 12. else-if and while loops. Once in a while

Lexical Considerations

1 Lexical Considerations

Strings, Arrays, A1. COMP 401, Spring 2015 Lecture 4 1/20/2015

COMP 208 Computers in Engineering

Principles of Computer Science

Operators in java Operator operands.

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017

Introduction to Java & Fundamental Data Types

CS313D: ADVANCED PROGRAMMING LANGUAGE

Accelerating Information Technology Innovation

Object-Oriented Programming in Java

PROGRAMMING FUNDAMENTALS

Introduction. C provides two styles of flow control:

Sri Vidya College of Engineering & Technology

QUIZ: What value is stored in a after this

Java Notes. 10th ICSE. Saravanan Ganesh

Introduction to Programming Using Java (98-388)

Binghamton University. CS-211 Fall Syntax. What the Compiler needs to understand your program

APCS Semester #1 Final Exam Practice Problems

Java Loop Control. Programming languages provide various control structures that allow for more complicated execution paths.

Week 4 Lecture 1. Expressions and Functions

Introduction to the Java Basics: Control Flow Statements

ECE 122. Engineering Problem Solving with Java

Decision Making in C

CS 106 Introduction to Computer Science I

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

Index COPYRIGHTED MATERIAL

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

7/8/10 KEY CONCEPTS. Problem COMP 10 EXPLORING COMPUTER SCIENCE. Algorithm. Lecture 2 Variables, Types, and Programs. Program PROBLEM SOLVING

Loops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

Sprite an animation manipulation language Language Reference Manual

Add Subtract Multiply Divide

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Q1 Q2 Q3 Q4 Q5 Total 1 * 7 1 * 5 20 * * Final marks Marks First Question

The Arithmetic Operators. Unary Operators. Relational Operators. Examples of use of ++ and

The Arithmetic Operators

1007 Imperative Programming Part II

Sir Muhammad Naveed. Arslan Ahmed Shaad ( ) Muhammad Bilal ( )

Introduction to Computer Science Midterm 3 Fall, Points

Programming Constructs Overview. Method Call System.out.print( hello ); Method Parameters

Week 6: Review. Java is Case Sensitive

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

CS 231 Data Structures and Algorithms, Fall 2016

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty!

Crayon (.cry) Language Reference Manual. Naman Agrawal (na2603) Vaidehi Dalmia (vd2302) Ganesh Ravichandran (gr2483) David Smart (ds3361)

C/Java Syntax. January 13, Slides by Mark Hancock (adapted from notes by Craig Schock)

C/Java Syntax. Lecture 02 Summary. Keywords Variable Declarations Data Types Operators Statements. Functions. if, switch, while, do-while, for

13 th Windsor Regional Secondary School Computer Programming Competition

Software Design and Analysis for Engineers

CS 106 Introduction to Computer Science I

Values and Variables 1 / 30

Le L c e t c ur u e e 2 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Variables Operators

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

Programming Lecture 4

AN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

Java Review. Java Program Structure // comments about the class public class MyProgram { Variables

Functions. Lecture 6 COP 3014 Spring February 11, 2018

C++ Programming Lecture 1 Software Engineering Group

C/C++ Programming Lecture 7 Name:

Operators And Expressions

COMP-202: Foundations of Programming. Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015

Quiz 1: Functions and Procedures

public class Foo { private int var; public int Method1() { // var accessible anywhere here } public int MethodN() {

Java Bytecode (binary file)

PLT Fall Shoo. Language Reference Manual

Basics of Java Programming

Lecture Set 4: More About Methods and More About Operators

class objects instances Fields Constructors Methods static

Chapter 3: Operators, Expressions and Type Conversion

Syntax and Variables

Recap: Assignment as an Operator CS 112 Introduction to Programming

Programming Lecture 4

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Arrays. Comp Sci 1570 Introduction to C++ Array basics. arrays. Arrays as parameters to functions. Sorting arrays. Random stuff

Loops and Expression Types

Mr. Monroe s Guide to Mastering Java Syntax

Variables and literals

GridLang: Grid Based Game Development Language Language Reference Manual. Programming Language and Translators - Spring 2017 Prof.

Transcription:

Basic Java Syntax, cont d. COMP 401, Fall 2015 Lecture 3 1/15/2015

Inside a method The body of a method is a sequence of statements. A statement ends in a semi- colon Types of statements: DeclaraPon of local variables Assignment CondiPonal Loop Method call Return statement Statement Blocks One or more statements enclosed in curly braces { } Allowed anywhere a single statement is allowed. And vice versa

Local variable declarapon Syntax: type name;! type name1, name2, name3;! type name = value;! A local variable is valid within the block of statements where the declarapon occurs. This is known as the scope of the variable. The declarapon must occur before the variable is used. Parameter names are local variables that are in scope for the enpre method body.

Variable Names Variable names should start with a leyer and can contain leyers, digits, $, or _ Can not start with digit Can not contain whitespace or punctuapon other than $ or _ In general, use of punctuapon in variable names is discouraged. Case sensipve Can not be a keyword Legal: foo, bar, a_variable, var123 Legal but not considered good: var_with_$, _badness Illegal: 1var, while, break, this has whitespace

Inside a method The body of a method is a sequence of statements. A statement ends in a semi- colon Types of statements: DeclaraPons of local variables Assignment CondiPonal Loop Method call Return statement Blocks Zero or more statements enclosed in curly braces { } Allowed anywhere a single statement is allowed. And vice versa

Assignment Syntax: variable = expression;! Note: single equals for assignment. Le] hand side must be some sort of variable that can be assigned. Expression must produce a value that matches the type of the variable.

Expressions A sequence of symbols that can be evaluated to produce a value. Can be used wherever a value is expected. Types of expressions: Literal values: 123, c, a string, true Variable name: a_variable Value retrieved from an array: my_array[3] Class/object fields: Math.PI Value as a result of a method call: foo() Compound expressions formed by applying an operator: 4+3*2

Operators Unary: +, -,!, ++, - - ArithmePc: +, -, /, *, % RelaPonal: ==,!=, >, >=, <, <= Boolean: &&, Ternary:?: expression? if_true : if_false Bitwise: ~, <<, >>, >>>, &,, ^ Be aware of precedence Can be controlled by explicitly grouping with () Be aware of context Some operators do different things depending on the types of the values they are applied to.

Assignment and Unary Operators Most numeric operators have an assignment form. Easy syntax for applying the operator to a variable and assigning the result back to the same variable. Examples: a += 3 // Equivalent to a = a + 3 b *= 4 // Equivalent to b = b * 4 Unary operators ++ and Used with integer typed variables to increment and decrement. Usually used as a statement unto itself: a++; // Equivalent to a = a + 1; b- - ; // Equivalent to b = b 1;

ImporPng JAR files into a project Save JAR file somewhere. Create a new project in Eclipse. Right click the src folder in the project and choose, Import Choose the type General- >Archive and click Next Browse for and select the JAR file. Click Finish

lec02.ex2.example2 Variable declarapons for value types Integer math vs. Real math Ternary operator Operator precedence Boolean operator shortcut

Inside a method The body of a method is a sequence of statements. A statement ends in a semi- colon Types of statements: Variable declarapon Assignment CondiPonal Loop Method call Return statement Blocks Zero or more statements enclosed in curly braces { } Allowed anywhere a single statement is allowed. And vice versa

CondiPonal ExecuPon: if- else if- else if (expression) {!!block! } else if (expression) {!!block! } else {!!block! }! 13

if example if (score > 90) {!!System.out.println( You got an A! );! } else if (score > 80) {!!System.out.println( You got a B. );! } else if (score > 70) {!!System.out.println( You got a C? );! } else if (score > 60) {!!System.out.println( You got a D :-( );! } else {!!System.out.println( You failed );! }!!

CondiPonal ExecuPon: switch switch (expression) {! case value:!!statements!!break;! case value:!!statements!!break;!...! default:!!statements! }! Works with basic value data types Works with String as of Java 7 ExecuPon starts at first matching case value or default if provided and no case matches ConPnues unpl break statement or end of switch.

Switch Example switch (c) {!!case 'a':!!case 'e':!!case 'i':!!case 'o':!!case 'u':!!!system.out.println("vowel");!!!break;!!default:!!!system.out.println("consonant");! }!!

lec02.ex3.example3 if and switch demo Variables scoped within block Style hint: Don t test boolean expression against true/false TesPng real numbers with epsilon bounds

Inside a method The body of a method is a sequence of statements. A statement ends in a semi- colon Types of statements: Variable declarapon Assignment CondiPonal Loop Method call Return statement Blocks Zero or more statements enclosed in curly braces { } Allowed anywhere a single statement is allowed. And vice versa

Loops: while while (expression) {!!block! }!! do {!!block! } while (expression);!

while example int sum = 0;! int n = 1;! while (n < 11) {! }! sum += n;! n++;! System.out.println( The sum of 1 to 10 is: + sum);!

Loops: for for (init; test; update) {!!block! }!

for example int sum = 0;! for(int n=1; n<11; n++) {! sum += n;! }! System.out.println( The sum of 1 to 10 is: + sum);!! Note that variable n is declared as part of init expression in for loop. This is a common programming idiom if loop variable is only needed for the loop. Scope of variable is limited to the loop block.

Loop odds and ends To skip to next iterapon of loop body use conpnue statement. To break out of the loop body use break statement.

Example 4 while and for while and for equivalence scope of for loop variable break / conpnue

Inside a method The body of a method is a sequence of statements. A statement ends in a semi- colon Types of statements: Variable declarapon Assignment CondiPonal Loop Method call Return statement Blocks Zero or more statements enclosed in curly braces { } Allowed anywhere a single statement is allowed. And vice versa

Calling Methods Calling a class method defined in the same class:!methodname(parameters);! Calling a class method defined in a different class (same package): ClassName.methodName(parameters);!! Calling a class method defined in a different package: PackageName.ClassName.methodName(parameters)!! In the above parameters is a comma separated list of values. A value can be also be an expression that results in a value. Must match in number and type according to method s signature. A method call that returns a value (i.e., not a void method) can be part of an expression. int max_times_min = max(a, b, c) * min(a, b, c);!

Inside a method The body of a method is a sequence of statements. A statement ends in a semi- colon Types of statements: Variable declarapon Assignment CondiPonal Loop Method call Return statement Blocks Zero or more statements enclosed in curly braces { } Allowed anywhere a single statement is allowed. And vice versa

Return Syntax: return expression;! Ends execupon of a method and returns the value of the expression as the result of the method. Must match type declared in method signature. If method return type is void, then simply: return;!

lec02.ex5.example5 Calling methods Compound expressions as part of method call to provide parameter value. Returning from middle of method Generally, try to avoid. Unreachable code error Calling method in same/different class, same/ different package lec02.ex5.example5other

Import DirecPve Maps class names from other packages into current name space. Convenient if going to use one or more class names repeatedly. Map all names from a package: import package.*;! Map a specific name from a package: import package.name;

Example5OtherRevisited import Math revisited Classes in java.lang package are automapcally imported.

Java ExecuPon Model Your program is always execupng within the context of some method. Starts off in the main class method defined in whatever class you told the program to start with. ExecuPon context includes: Local variable names that are in scope. Parameter names. Act just like local variables.

Java ExecuPon Model When you call a method: Current context is saved. A new context is created. Method parameter names are mapped to values provided when method was called. Local variables in scope in the called method. When a method returns: Current context is destroyed. Context where method call occurred is restored. Value returned is subsptuted as result of method call. Lecture 03, Example 1 This is why recursion works. Lecture 03, Example 2