Basic Java Syntax, cont’d COMP 401, Fall 2014 Lecture 3 8/26/2014.

Slides:



Advertisements
Similar presentations
Java Control Statements
Advertisements

COMP 110: Introduction to Programming Tyler Johnson Feb 11, 2009 MWF 11:00AM-12:15PM Sitterson 014.
Selection Feature of C: Decision making statements: It allow us to take decisions as to which code is to be executed next. Since these statements control.
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Repetition Statements Perform the same task repeatedly Allow the computer to do the tedious, boring things.
3-1 Chapter 3 Flow of Control (part a - branching)
Program Looping EE2372 Software Design I Dr. Gerardo Rosiles.
The if-else Statements
Programming In C++ Spring Semester 2013 Lecture 3 Programming In C++, Lecture 3 By Umer Rana.
C++ Statements represent the lowest-level building blocks of a program and it may be like:. A simple statement is a computation terminated by a semicolon.
Chapter 9 Interactive Multimedia Authoring with Flash Introduction to Programming 1.
ICE1341 Programming Languages Spring 2005 Lecture #13 Lecture #13 In-Young Ko iko.AT. icu.ac.kr iko.AT. icu.ac.kr Information and Communications University.
Fundamental Programming Structures in Java: Control Flow, Arrays and Vectors.
July 13 th.  If/ Else if / Else  Variable Scope  Nested if/else's  Switch statements  Conditional Operator.
Branching Constructs Review l what are branching constructs? what type of branching constructs have we studied? l what is nested if? l what is multiway.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
A loop is a repetition control structure. it causes a single statement or block to be executed repeatedly What is a loop?
Repetition Statements repeat block of code until a condition is satisfied also called loops Java supports 3 kinds of loops: while statement – repeats a.
Loops – While, Do, For Repetition Statements Introduction to Arrays
Repetition Structures: For Loop Constants CSC 1401: Introduction to Programming with Java Week 5 Wanda M. Kunkle.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
1 Midterm Review COMP 102. Tips l Eat a light meal before the exam l NO electronic devices (including calculators, dictionaries, phones, pagers, etc.)
Parameters, Arguments, Local Variables, and Scope CSC 1401: Introduction to Programming with Java Week 8 – Lecture 1 Wanda M. Kunkle.
Loops Programming. COMP104 Lecture 9 / Slide 2 Shortcut Assignment l C++ has a set of operators for applying an operation to a variable and then storing.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
TODAY’S LECTURE Review Chapter 2 Go over exercises.
L EC. 03: C ONTROL STATEMENTS Fall Java Programming.
CSci 125 Lecture 10 Martin van Bommel. Simple Statements Expression followed by semicolon Assignments total = n1 + n2; Function calls printf(”Hello.\n”);
DiagrammaticRepresentation Iteration Construct False True Condition Exit from Statement (s) loop Sequence construct Selection construct Statement 1 Statement.
/* Documentations */ Pre process / Linking statements Global declarations; main( ) { Local Declarations; Program statements / Executable statements; }
Repetition Statements.  Often it is necessary to repeat statements many times  Java has two ways of doing this  while statements  for statements.
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 2: Variables & Data Types.
LOOPS In the Name of Allah The Most Merciful The Most Compassionate LOOPS
Repetition. Control of Flow SEQUENCE SELECTION (if..else, switch…case) REPETITION.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
Basic Java Syntax COMP 401, Spring 2014 Lecture 2 1/14/2014.
J AVA P ROGRAMMING 2 C H 03: C ONTROL STATEMENTS if, for loop (review) switch, while, do while break, continue Fall Java Programming.
Chapter 15 JavaScript: Part III The Web Warrior Guide to Web Design Technologies.
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
Java Nuts and Bolts Variables and Data Types Operators Expressions Control Flow Statements Arrays and Strings.
In the last lesson we discussed about: Casting Precedence The “=“ used as an assignment operator Made a calculate average program.
Repetition Control Structure. Introduction Many applications require certain operations to be carried out more than once. Such situations require repetition.
CSC 107 – Programming For Science. Today’s Goal  Know how to use and write for loops  Explain why to use for, while, & do-while loops  Convert between.
1 For Loops l From Chapter 9 l A shorthand way of coding count loops.
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
COMP Loop Statements Yi Hong May 21, 2015.
Control structures in C by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
Chapter 3. Control Structure C++ Programing. Conditional structure C++ programming language provides following types of decision making statements. Click.
Five-Minute Review 1.What are classes and objects? What is a class hierarchy? 2.What is an expression? A term? 3.What is a variable declaration? 4.What.
Chapter 7 Control Structures. Java has very flexible three looping mechanisms. You can use one of the following three loops:  while Loop  do...while.
Loops causes program to execute the certain block of code repeatedly until some conditions are satisfied. Suppose you want to execute some code/s 10 times.
Lecture 4b Repeating With Loops
Loops in Java.
Java for Android is specific
Operator Precedence Operators Precedence Parentheses () unary
Programming Fundamentals
Conditinoal Constructs Review
Debugging October 3, 2007 ComS 207: Programming I (in Java)
LRobot Game.
Lecture Notes – Week 3 Lecture-2
Conditinoal Constructs Review
Variables Numbers can be stored and retrieved while a program is running if they are given a home. The way that integers and decimal numbers are stored.
Repetition Control Structure
Debugging October 4, 2006 ComS 207: Programming I (in Java)
Program Flow.
Decisions, decisions, decisions
PROGRAM FLOWCHART Iteration Statements.
Chap 7. Advanced Control Statements in Java
Loops CGS3416 Spring 2019 Lecture 7.
Looping and Repetition
Presentation transcript:

Basic Java Syntax, cont’d COMP 401, Fall 2014 Lecture 3 8/26/2014

Our TAs Grad Students: – Brian Cristante – Xufeng Han

UTAs Shashank Adepu Jade Enns Jennifer Hines Catherine Jarrett Henry Ji KJ Moon Nate Weatherly

lec02.ex3.Example3 if and switch demo Variables scoped within block Style hint: – Don’t test boolean expression against true/false Testing 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 declaration Assignment Conditional 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 iteration of loop body use “continue” statement. To break out of the loop body use “break” statement.

Lecture 2 Example 4 while and for while and for equivalence scope of for loop variable break / continue

Inside a method The body of a method is a sequence of statements. A statement ends in a semi-colon – Types of statements: Variable declaration Assignment Conditional 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 declaration Assignment Conditional 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 execution 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 Unreachable code error Calling method in same/different class, same/different package

Import Directive 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 automatically imported.

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

Java Execution 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 substituted as result of method call. Lecture 03, Example 1 This is why recursion works. – Lecture 03, Example 2

String, our first object In Java, a string is an immutable sequence of characters. – Strings are objects. Objects have a type. – The name of the class that defines them. – Example: String Objects have methods – Dereferenced using the “.” operator – Example: String s = “This is a string”; int length = s.length(); Objects have fields – Properties that can be directly accessed as values. – Accessed via the “.” operator like methods reference.field

Creating Strings As a literal. – Enclosed in double quotes. – Escape sequences for common non-printable or untypeable characters. \”, \\, \t, \n, \u#### Using the “new” operator. – Generally almost never need to do this. As the result of a string concatenation operator Lecture 3, Example 3

Useful String methods length() charAt() equals() substring() trim() indexOf() Lecture 3, Example 4

Strings are immutable Once created, can’t change. – Some other languages treat strings as a type of array of characters. Not Java. Any operation that manipulates a string is creating a new string. Why immutability? – If the same string occurs twice, can simply reuse the same object. This is an optimization that Java performs automatically if it can. Side effect of this is that it may appear that == can be used to test equality, but you should not do that. Lecture 3, Example 5

Arrays Another object type. – A little different because it is a type that combines with another type. The array itself is of type Array, but the type of the individual elements must also be specified. – Can’t have an array of different types mixed together. – Also different from other objects in its creation syntax. Arrays are fixed length. – Must be specified when created. – Once created, can not be resized.

Creating / Initializing Arrays Type indicator for an array is type name of individual elements followed by [] As a literal list of values. – Comma-separated, in curly braces – Example: int[] iarray = {1, 2, 3}; String[] sarray = {“one”, “two”, “three”}; Using the new operator type[] vname = new type[length]; – Array will be created, and initialized with default values. For numeric types and char: 0 For boolean: false For reference types: null

Indexing Arrays 0-based indexing Length is provided by length field – Note, for String objects, length() was a method – Here, length is a field Size of array can not change once created, but individual elements may change. Lecture 3, Example 6

null Special value that is always valid for any reference type. – Indicates “no value” – Any reference type variable can be set to null. – Default value for reference type arrays.

Assignment 1