1 CS1001 Lecture 13. 2 Overview Java Programming Java Programming.

Slides:



Advertisements
Similar presentations
10-Jun-15 Just Enough Java. Variables A variable is a “box” that holds data Every variable has a name Examples: name, age, address, isMarried Variables.
Advertisements

1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Declaring Variables You must first declare a variable before you can use it! Declaring involves: – Establishing the variable’s spot in memory – Specifying.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
Chapter 2: Introduction to C++.
String Escape Sequences
CPS120: Introduction to Computer Science Lecture 8.
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
1 Identifiers  Identifiers are the words a programmer uses in a program  An identifier can be made up of letters, digits, the underscore character (
Primitive Data Types and Operations Identifiers, Variables, and Constants Primitive Data Types Byte, short, int, long, float, double, char, boolean Casting.
Chapter 2 Primitive Data Types and Operations F Introduce Programming with an Example  The MyInput class F Identifiers, Variables, and Constants F Primitive.
1 Chapter 2 Primitive Data Types and Operations F Introduce Programming with an Example  The MyInput class F Identifiers, Variables, and Constants F Primitive.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
The Java Programming Language
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
JAVA Tokens. Introduction A token is an individual element in a program. More than one token can appear in a single line separated by white spaces.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
CPS120: Introduction to Computer Science
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Style Guidelines. Why do we need style?  Good programming style helps promote the readability, clarity and comprehensibility of your code.
Java Syntax and Style JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin, Gary Litvin,
Copyright © 2012 Pearson Education, Inc. Chapter 2: Introduction to C++
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 2: Variables & Data Types.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 2: Introduction to C++
Java Classes, Objects, and Events: A Preview JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria.
Data Types, Variables, and Arithmetic JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin,
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
Chapter 3 – Variables and Arithmetic Operations. Variable Rules u Must declare all variable names –List name and type u Keep length to 31 characters –Older.
Chapter 2 Variables.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
Data Types, Variables, and Arithmetic Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by.
1 Week 5 l Primitive Data types l Assignment l Expressions l Documentation & Style Primitive Types, Assignments, and Expressions.
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Agenda Comments Identifiers Keywords Syntax and Symentics Indentation Variables Datatype Operator.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 2 Introduction to C++
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 1: Computer Systems Presentation slides for Java Software Solutions for AP* Computer Science.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
The Essentials of a Java Program JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin,
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
2.1 The Part of a C++ Program. The Parts of a C++ Program // sample C++ program #include using namespace std; int main() { cout
Java Programming: Guided Learning with Early Objects Chapter 1 Basic Elements of Java.
Chapter 2 Variables.
Working with Java.
Java Methods /** * Chapter 5 */ Java Syntax and Style
Multiple variables can be created in one declaration
Java Programming: From Problem Analysis to Program Design, 4e
2.1 Parts of a C++ Program.
Chapter 2: Basic Elements of Java
Chapter 1: Computer Systems
MSIS 655 Advanced Business Applications Programming
Chapter 2 Variables.
Unit 6 - Variables - Fundamental Data Types
Java Methods /** * Chapter 5 */ Java Syntax and Style A & AB
Expressions and Assignment
elementary programming
Anatomy of a Java Program
Focus of the Course Object-Oriented Software Development
Chapter 2: Introduction to C++.
Primitive Types and Expressions
Chap 2. Identifiers, Keywords, and Types
Chapter 2 Variables.
Chapter 2 Primitive Data Types and Operations
Presentation transcript:

1 CS1001 Lecture 13

2 Overview Java Programming Java Programming

3 Goals Understand the basics of Java programming Understand the basics of Java programming

4 Assignments Brookshear: Ch 4, Ch 5 (Read) Brookshear: Ch 4, Ch 5 (Read) Read linked documents on these slides (slides will be posted in courseworks) Read linked documents on these slides (slides will be posted in courseworks)

5 Objectives: Learn to distinguish the required syntax from the conventional style Learn to distinguish the required syntax from the conventional style Learn when to use comments and how to mark them Learn when to use comments and how to mark them Review reserved words and standard names Review reserved words and standard names Learn the proper style for naming classes, methods, and variables Learn the proper style for naming classes, methods, and variables Learn to space and indent blocks of code Learn to space and indent blocks of code

6 Comments Comments are notes in plain English inserted in the source code. Comments are notes in plain English inserted in the source code. Comments are used to: Comments are used to: –document the program’s purpose, author, revision history, copyright notices, etc. –describe fields, constructors, and methods –explain obscure or unusual places in the code –temporarily “comment out” fragments of code

7 Formats for Comments A “block” comment is placed between /* and */ marks: A “block” comment is placed between /* and */ marks: /* Exercise 5-2 for Java Methods Author: Miss Brace Author: Miss Brace Date: 3/5/2010 Date: 3/5/2010 Rev. 1.0 */ Rev. 1.0 */ A single-line comment goes from // to the end of the line: A single-line comment goes from // to the end of the line: wt * = ; // Convert to kilograms

8 Reserved Words In Java a number of words are reserved for a special purpose. In Java a number of words are reserved for a special purpose. Reserved words use only lowercase letters. Reserved words use only lowercase letters. Reserved words include: Reserved words include: –primitive data types: int, double, char, boolean, etc. –storage modifiers: public, private, static, final, etc. –control statements: if, else, switch, while, for, etc. –built-in constants: true, false, null There are about 50 reserved words total. There are about 50 reserved words total.

9 Programmer-Defined Names In addition to reserved words, Java uses standard names for library packages and classes: In addition to reserved words, Java uses standard names for library packages and classes: String, Graphics, javax.swing, JApplet, JButton, ActionListener, java.awt The programmer gives names to his or her classes, methods, fields, and variables. The programmer gives names to his or her classes, methods, fields, and variables.

10 Names (cont’d) Syntax: A name can include: Syntax: A name can include: –upper- and lowercase letters –digits –underscore characters Syntax: A name cannot begin with a digit. Syntax: A name cannot begin with a digit. Style: Names should be descriptive to improve readability. Style: Names should be descriptive to improve readability.

11 Names (cont’d) Programmers follow strict style conventions. Programmers follow strict style conventions. Style: Names of classes begin with an uppercase letter, subsequent words are capitalized: Style: Names of classes begin with an uppercase letter, subsequent words are capitalized: public class FallingCube Style: Names of methods, fields, and variables begin with a lowercase letter, subsequent words are capitalized. Style: Names of methods, fields, and variables begin with a lowercase letter, subsequent words are capitalized. private final int delay = 30; public void dropCube()

12 Names (cont’d) Method names often sound like verbs: Method names often sound like verbs: setBackground, getText, dropCube, start Field names often sound like nouns: Field names often sound like nouns: cube, delay, button, whiteboard Constants sometimes use all caps: Constants sometimes use all caps: PI, CUBESIZE It is OK to use standard short names for temporary “throwaway” variables: It is OK to use standard short names for temporary “throwaway” variables: i, k, x, y, str

13 Syntax vs. Style Syntax is part of the language. The compiler checks it. Syntax is part of the language. The compiler checks it. Style is a convention widely adopted by software professionals. Style is a convention widely adopted by software professionals. The main purpose of style is to improve the readability of programs. The main purpose of style is to improve the readability of programs.

14 Syntax The compiler catches syntax errors and generates error messages. The compiler catches syntax errors and generates error messages. Text in comments and literal strings within double quotes are excluded from syntax checking. Text in comments and literal strings within double quotes are excluded from syntax checking. Before compiling, carefully read your code a couple of times to check for syntax and logic errors. Before compiling, carefully read your code a couple of times to check for syntax and logic errors.

15 Syntax (cont’d) Pay attention to and check for: Pay attention to and check for: –matching braces { }, parentheses ( ), and brackets [ ] –missing and extraneous semicolons –correct symbols for operators +, -, =, <, <=, ==, ++, &&, etc. –correct spelling of reserved words, library names and programmer-defined names, including case

16 Syntax (cont’d) Common syntax errors: Common syntax errors: Missing closing brace Public static int abs (int x) { If (x < 0); { x = - x } return x; public static int sign (int x)... Extraneous semicolon Spelling (p  P, if  If) Missing semicolon

17 Style Arrange code on separate lines; insert blank lines between fragments of code. Arrange code on separate lines; insert blank lines between fragments of code. Use comments. Use comments. Indent blocks within braces. Indent blocks within braces.

18 Style (cont’d) public boolean moveDown(){if (cubeY<6*cubeX) {cubeY+=yStep; return true;}else return false;} public boolean moveDown() { if (cubeY < 6 * cubeX) { cubeY += yStep; return true; } else { return false; } Before:After: Compiles fine!

19 Style (cont’d) public void fill (char ch) { int rows = grid.length, cols = grid[0].length; int r, c; for (r = 0; r < rows; r++) { for (c = 0; c < cols; c++) { grid[r][c] = ch; } Add blank lines for readability Add spaces around operators and after semicolons

20 Blocks, Indentation Java code consists mainly of declarations and control statements. Java code consists mainly of declarations and control statements. Declarations describe objects and methods. Declarations describe objects and methods. Control statement describe actions. Control statement describe actions. Declarations and control statements end with a semicolon. Declarations and control statements end with a semicolon. No semicolon is used after a closing brace (except certain array declarations). No semicolon is used after a closing brace (except certain array declarations).

21 Braces divide code into nested blocks. Braces divide code into nested blocks. A block in braces indicates a number of statements that form one compound statement. A block in braces indicates a number of statements that form one compound statement. Statements inside a block are indented, usually by two spaces or one tab. Statements inside a block are indented, usually by two spaces or one tab. Blocks, Indentation (cont’d)

22 Blocks, Indentation (cont’d) public void fill (char ch) { int rows = grid.length, cols = grid[0].length; int r, c; for (r = 0; r < rows; r++) { for (c = 0; c < cols; c++) { grid[r][c] = ch; }

23 Review: Name as many uses of comments as you can. Name as many uses of comments as you can. Explain the difference between syntax and style. Explain the difference between syntax and style. Why is style important? Why is style important? Roughly how many reserved words does Java have? Roughly how many reserved words does Java have?

24 Review (cont’d): Explain the convention for naming classes, methods and variables. Explain the convention for naming classes, methods and variables. Which of the following are syntactically valid names for variables: C, _denom_, my. num, AvgScore? Which of them are in good style? Which of the following are syntactically valid names for variables: C, _denom_, my. num, AvgScore? Which of them are in good style? What can happen if you put an extra semicolon in your program? What can happen if you put an extra semicolon in your program? What are braces used for in Java? What are braces used for in Java? Is indentation required by Java syntax or style? Is indentation required by Java syntax or style?

25 Objectives: Review primitive data types Review primitive data types Learn how to declare fields and local variables Learn how to declare fields and local variables Learn about arithmetic operators, compound assignment operators, and increment / decrement operators Learn about arithmetic operators, compound assignment operators, and increment / decrement operators Learn how to avoid common mistakes in arithmetic Learn how to avoid common mistakes in arithmetic

26 Variables A variable is a “named container” that holds a value. A variable is a “named container” that holds a value. q = q; q = q;means: 1. Read the current value of q 2. Subtract it from Move the result back into q count 5 mov ax,q mov bx,100 sub bx,ax mov q,bx

27 Variables (cont’d) Variables can be of different data types: int, char, double, boolean, etc. Variables can be of different data types: int, char, double, boolean, etc. Variables can hold objects; then the type is the class of the object. Variables can hold objects; then the type is the class of the object. The programmer gives names to variables. The programmer gives names to variables. Names usually start with a lowercase letter. Names usually start with a lowercase letter.

28 Variables (cont’d) A variable must be declared before it can be used: A variable must be declared before it can be used: int count; double x, y; JButton go; FallingCube cube; String firstName; Declarations Type Name(s)

29 Variables (cont’d) The assignment operator = sets the variable’s value: The assignment operator = sets the variable’s value: A variable can be initialized in its declaration: A variable can be initialized in its declaration: count = 5; x = 0; go = new JButton("Go"); firstName = args[0]; Assignments int count = 5; JButton go = new JButton("Go"); String firstName = args[0]; Declarations with initialization

30 Variables (cont’d) Each variable has a scope — the area in the source code where it is “visible.” Each variable has a scope — the area in the source code where it is “visible.” If you use a variable outside its scope, the compiler reports a syntax error. If you use a variable outside its scope, the compiler reports a syntax error. Variables can have the same name. Caution: use only when their scopes do not intersect. Variables can have the same name. Caution: use only when their scopes do not intersect. { int k;... } { int k;... }

31 Fields vs. Local Variables Fields are declared outside all constructors and methods. Fields are declared outside all constructors and methods. Local variables are declared inside a constructor or a method. Local variables are declared inside a constructor or a method.

32 Fields vs. Local Variables (cont’d) Fields vs. Local Variables (cont’d) Fields are usually grouped together, either at the top or at the bottom of the class. Fields are usually grouped together, either at the top or at the bottom of the class. The scope of a field is the whole class. The scope of a field is the whole class.

33 Fields public class SomeClass { } Fields Constructors and methods public class SomeClass { } Scope Fields Constructors and methods

34 Variables (cont’d) Common mistakes: Common mistakes: public void SomeMethod (...) { int x;... int x = 5; // should be: x = 5;... Variable declared twice — syntax error

35 Primitive Data Types int int double double char char boolean boolean byte byte short short long long float float Used in Java Methods

36 Constants 'A', '+', '\n', '\t' // char - 99, 2010, 0 // int 0.75, , 8.,.5 // double new line tab

37 Constants (cont’d) private final int delay = 30; private final double aspectRatio = 0.7; Symbolic constants are initialized final variables: Symbolic constants are initialized final variables:

38 Constants (cont’d) Why use symbolic constants? Why use symbolic constants? –easier to change the value throughout, if necessary –easy to change into a variable –more readable, self-documenting code –additional data type checking

39 Arithmetic Operators: +, -, /, *, % Operators: +, -, /, *, % The precedence of operators and parentheses work the same way as in algebra. The precedence of operators and parentheses work the same way as in algebra. m % n means the remainder when m is divided by n (e.g. 17 % 5 is 2). m % n means the remainder when m is divided by n (e.g. 17 % 5 is 2). % has the same rank as / and * % has the same rank as / and * Same-rank binary operators are performed in order from left to right. Same-rank binary operators are performed in order from left to right.

40 Arithmetic (cont’d) The type of the result is determined by the types of the operands, not their values; this rule applies to all intermediate results in expressions. The type of the result is determined by the types of the operands, not their values; this rule applies to all intermediate results in expressions. If one operand is an int and another is a double, the result is a double; if both operands are ints, the result is an int. If one operand is an int and another is a double, the result is a double; if both operands are ints, the result is an int.

41 Arithmetic (cont’d) Caution: if a and b are ints, then a / b is truncated to an int… Caution: if a and b are ints, then a / b is truncated to an int… 17 / 5 gives 3 3 / 4 gives 0 3 / 4 gives 0 …even if you assign the result to a double: …even if you assign the result to a double: double ratio = 2 / 3; double ratio = 2 / 3; The double type of the result doesn’t help: ratio still gets the value 0.0.

42 Arithmetic (cont’d) To get the correct double result, use double constants or the cast operator: To get the correct double result, use double constants or the cast operator: double ratio = 2.0 / 3; double ratio = 2.0 / 3; double ratio = 2 / 3.0; double ratio = 2 / 3.0; double factor = (double) m / (double) n; double factor = (double) m / (double) n; double factor = m / (double) n; double factor = m / (double) n; double r2 = k / 2.0; double r2 = k / 2.0; double r2 = (double) k / 2; double r2 = (double) k / 2; Casts

43 Arithmetic (cont’d) Caution: the range for ints is from to (about - 2·10 9 to 2·10 9 ) Caution: the range for ints is from to (about - 2·10 9 to 2·10 9 ) Overflow is not detected by the Java compiler or interpreter Overflow is not detected by the Java compiler or interpreter n = 8 10^n = n! = n = 9 10^n = n! = n = 10 10^n = n! = n = 11 10^n = n! = n = 12 10^n = n! = n = 13 10^n = n! = n = 14 10^n = n! =

44 Arithmetic (cont’d) Use compound assignment operators: Use compound assignment operators: a = a + b; a += b; a = a - b; a -= b; a = a * b; a *= b; a = a / b; a /= b; a = a % b; a % = b; Use increment and decrement operators: Use increment and decrement operators: a = a + 1; a ++ ; a = a - 1; a -- ; Do not use these in larger expressions

45 Review: What is a variable? What is a variable? What is the type of variable that holds an object? What is the type of variable that holds an object?

46 Review (cont’d): What is the range for ints? What is the range for ints? When is a cast to double used? When is a cast to double used? Given Given double dF = 68.0; double dC = 5 / 9 * (dF - 32); what is the value of dC? When is a cast to int used? When is a cast to int used? Should compound assignment operators be avoided? Should compound assignment operators be avoided?