Java Fundamentals Asserting Java Chapter 2: Introduction to Computer Science ©Rick Mercer.

Slides:



Advertisements
Similar presentations
 2005 Pearson Education, Inc. All rights reserved Introduction.
Advertisements

1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
Primitive Data Types and Operations. Introducing Programming with an Example public class ComputeArea { /** Main method */ public static void main(String[]
CMT Programming Software Applications
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
Copyright 2008 by Pearson Education 1 Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading:
Hello, world! Dissect HelloWorld.java Compile it Run it.
1 The First Step Learning objectives write Java programs that display text on the screen. distinguish between the eight built-in scalar types of Java;
Introduction to C++ Programming
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 2 Elementary Programming.
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Primitive Types, Strings, and Console I/O Chapter 2.1 Variables and Values Declaration of Variables Primitive Types Assignment Statement Arithmetic Operators.
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Java Keywords  Reserved Words Part of the Java language Examples: public, static, void  Pre-defined Java Identifiers Defined in Java Libraries Examples:
CSC Programming I Lecture 5 August 30, 2002.
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
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.
Chapter 2 Elementary Programming
Chapter 2: Java Fundamentals
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Variables, Arithmetic, etc.)
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Java Programming: From Problem Analysis to Program Design, 5e Chapter 2 Basic Elements of Java.
A First Look at Java Chapter 2 1/29 & 2/2 Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010.
2-1 Chapter 2 A Little Java Computing Fundamentals with Java Rick Mercer Franklin, Beedle & Associates, 2002 ISBN Presentation Copyright.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
First Programs CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Copyright 2008 by Pearson Education 1 Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading:
2-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
Chapter 2 Variables.
Operators and Expressions. 2 String Concatenation  The plus operator (+) is also used for arithmetic addition  The function that the + operator performs.
Copyright 2010 by Pearson Education 1 Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading:
1 Chapter 2: Java Fundamentals cont’d Spring Lory Al Moakar.
Part:2.  Keywords are words with special meaning in JavaScript  Keyword var ◦ Used to declare the names of variables ◦ A variable is a location in the.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
COP 2551 Introduction to Object Oriented Programming with Java Topics –Introduction to the Java language –Code Commenting –Java Program Structure –Identifiers.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
1 1 Chapter 2 Elementary Programming. 2 2 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Chapter 2: Data and Expressions. Variable Declaration In Java when you declare a variable, you must also declare the type of information it will hold.
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
Java Keywords  Reserved Words Part of the Java language Examples: public, static, void  Pre-defined Java Identifiers Defined in Java Libraries Examples:
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.
Java Programming: Guided Learning with Early Objects Chapter 1 Basic Elements of Java.
Chapter 2 Variables.
Chapter 2 Basic Computation
Elementary Programming
BASIC ELEMENTS OF A COMPUTER PROGRAM
PowerPoint Presentation Authors of Exposure Java
Multiple variables can be created in one declaration
Java Programming: From Problem Analysis to Program Design, 4e
Introduction to C++ Programming
مساق: خوارزميات ومبادئ البرمجة الفصل الدراسي الثاني 2016/2015
Chapter 2 Edited by JJ Shepherd
Chapter 2: Basic Elements of Java
Chapter 2 C++ Fundamentals
Chapter 2 Variables.
Data Types, Concatenation, PEMDAS, Shortcuts, and Comments
Building Java Programs Chapter 2
elementary programming
Building Java Programs
Building Java Programs Chapter 2
Chapter 2 Variables.
Building Java Programs
Presentation transcript:

Java Fundamentals Asserting Java Chapter 2: Introduction to Computer Science ©Rick Mercer

Outline  Distinguish the syntactical parts of a program Tokens: special symbols, literals, identifiers, Tokens: special symbols, literals, identifiers, Output with System.out.println Output with System.out.println An executable program as a Java class with a main method An executable program as a Java class with a main method  Introduce two of Java's primitive types: int and double

Preview: A Complete Java program import java.util.Scanner; // Read number from user and then display its squared value public class ReadItAndSquareIt { public static void main(String[] args) { double x; double result = 0.0; Scanner keyboard = new Scanner(System.in); // 1. Input System.out.print("Enter a number: "); x = keyboard.nextDouble(); // 2. Process result = x * x; // 3. Output System.out.println(x + " squared = " + result); }

Programs have 4 types of tokens  The Java source code consists of 1)special symbols + = && || 2)identifiers customerName totalBill n 3)reserved identifiers int while if void 4)literals 123 "A String" true  These tokens build bigger things like variables, expressions, statements, methods, and classes.  Also, comments exist for humans to read // Document your code if it is unreadable :-( // Document your code if it is unreadable :-(

Overloaded Symbols  Some special symbols are operators and have different things in different contexts with two integers, + sums integers with two integers, + sums integers evaluates to the integer evaluates to the integer 7 with two floating point literals, + sums to floating point (types make a difference) with two floating point literals, + sums to floating point (types make a difference) evaluates to evaluates to 7.0 with two strings, + concatenates with two strings, + concatenates "2" + "5" evaluates to the new string "25" "2" + "5" evaluates to the new string "25"

Identifiers  An identifier is a collection of certain characters that could mean a variety of things  There are some identifiers that are Java defines: sqrt String Integer System in out sqrt String Integer System in out  We can make up our own new identifiers test1 lastName dailyNumber MAXIMUM $A_1 test1 lastName dailyNumber MAXIMUM $A_1

Valid identifiers Valid identifiers  Identifiers have from 1 to many characters: 'a'..'z', 'A'..'Z', '0'..'9', '_', $ Identifiers start with letter a1 is legal, 1a is not Identifiers start with letter a1 is legal, 1a is not can also start with underscore or dollar sign: _ $ can also start with underscore or dollar sign: _ $ Java is case sensitive. A and a are different Java is case sensitive. A and a are different  Which letters represent valid identifiers? a) abcd) $$$i) a_1 a) abcd) $$$i) a_1 b) m/he) 25or6to4j) student Number b) m/he) 25or6to4j) student Number c) mainf) 1_timek) String c) mainf) 1_timek) String

Reserved Identifiers (keywords)  A keyword is an identifier with a pre-defined meaning that can't be changed it's reserved doubleint double int  Other Java reserved identifiers not a complete list booleandefaultfor new booleandefaultfor new breakdoif private breakdoif private casedoubleimport public casedoubleimport public catchelseinstanceOfreturn catchelseinstanceOfreturn charextendsint void charextendsint void classfloatlong while classfloatlong while

Literals -- Java has 6 Floating-point literals e10 0.1e-5 String literals "characters between double quotes" "'10" "_" Integer literals ( Integer.MIN_VALUE and Integer.MIN_VALUE ) Boolean literals (there are only two) true false true false Null (there is only this one value) null null Character literals 'A' 'b' '\n' '1' ' ' 'A' 'b' '\n' '1' ' '

Comments Provide internal documentation to explain program Provide internal documentation to explain program Provide external documentation with javadoc Provide external documentation with javadoc Helps programmers understand code--including their own Helps programmers understand code--including their own There are three type of comments There are three type of comments // on one line, or /* between slash star and star slash you can mash lines down real far, or */ /** * javadoc comments for external documentation The square root of x */ public static double sqrt(double x)

General Forms  The book uses general forms to introduce parts of the Java programming language  General forms provide information to create syntactically correct programs Anything in yellow boldface must be written exactly as shown ( println for example) Anything in yellow boldface must be written exactly as shown ( println for example) Anything in italic represents something that must be supplied by the user Anything in italic represents something that must be supplied by the user The italicized portions are defined elsewhere The italicized portions are defined elsewhere

Output Statements  A statement, made up of tokens, is code that causes something to happen while the program runs  General Forms for three output statements System.out.print( expression ); System.out.println(); System.out.println( expression ); System.out.print( expression ); System.out.println(); System.out.println( expression );  Example Java code that writes text to the console System.out.print("hello world."); System.out.print("hello world."); System.out.println(); // print a blank line System.out.println(); // print a blank line System.out.println("Add new line after this"); System.out.println("Add new line after this");

General Form: A Java program // This Java code must be in a file named class-name.java public class class-name { public static void main(String[] args ) { public static void main(String[] args ) { statement(s) statement(s) }} // Example Program stored in the file HelloWorld.java import java.util.Scanner; public class HelloWorld { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); System.out.print("Enter your name: "); String myName = keyboard.next(); // keyboard input System.out.println("Hi Rick"); System.out.println("This is " + myName); }

Primitive Numeric Types  Type: A set of values with associated operations  Java has many types, a few for storing numbers Stores integers in int variables Stores integers in int variables Store floating-point numbers in double variables Store floating-point numbers in double variables  A few operations for numeric types Assignment Store a new value into a variable Assignment Store a new value into a variable Arithmetic +, -, * (multiplication), / Arithmetic +, -, * (multiplication), / Methods Math.sqrt(4.0) Math.max(3, -9) Methods Math.sqrt(4.0) Math.max(3, -9) See class Math for others class Mathclass Math

Variables to store numbers  To declare and give initial value: type identifier = initial-value ; type identifier = initial-value ;  Examples int creditsA = 4; int creditsA = 4; double gradeA = 3.67; double gradeA = 3.67; String name = "Chris"; String name = "Chris"; int hours = 10; int hours = 10; boolean ready = hours >= 8; boolean ready = hours >= 8;

Assignment  We change the values of variables with assignment operations of this general form variable-name = expression ;  Examples: double x; // Undefined variables double x; // Undefined variables int j; // can not be evaluated int j; // can not be evaluated j = 1; j = 1; x = j ; x = j ;

Memory before and after  The primitive variables x and j are undefined at first Variable Initial Assigned Variable Initial Assigned Name ValueValue Name ValueValue j ? 1 x ? 1.23  The expression to the right of = must be a value that the variable can store assignment compatible x = "oooooh nooooo, you can't do that"; // <-Error x = "oooooh nooooo, you can't do that"; // <-Error j = x; // <-Error, can't assign a float to an int j = x; // <-Error, can't assign a float to an int ? ? means undefined

Assignment double bill; double bill; What is value for bill now? _________ bill = 10.00; bill = 10.00; bill = bill + (0.06 * bill); bill = bill + (0.06 * bill); What is value for bill now? ________ Which letters represent valid assignments given these 3 variable initializations? String s = "abc"; String s = "abc"; int n = 0; int n = 0; double x = 0.0; double x = 0.0; a) s = n; e) n = 1.0; b) n = x; f) x = 999; c) x = n; g) s = "abc" + 1; d) s = 1; h) n = ;

Arithmetic Expressions  Arithmetic expressions consist of operators such as + - / * and operands such as 40, 1.5, payRate and hoursWorked  Example expression used in an assignment: grossPay = payRate * hoursWorked; grossPay = payRate * hoursWorked;  Another example expression: 5 / 9 * (fahrenheit - 32); 5 / 9 * (fahrenheit - 32); For the previous expression, Which are the operators?_____ Which are the operands?_____

Arithmetic Expressions a numeric variable double x = 1.2; a numeric variable double x = 1.2; or a numeric constant 100 or 99.5 or expression + expression x or expression - expression x or expression * expression2 * x or expression / expression x / 2.0 or (expression ) ( ) Arithmetic expressions take many forms

Precedence of Arithmetic Operators  Expressions with more than one operator require some sort of precedence rules: * / evaluated in a left to right order * / evaluated in a left to right order - + evaluated in a left to right order in the absence of parentheses - + evaluated in a left to right order in the absence of parentheses Evaluate * 8.0 / 6.0 Evaluate * 8.0 / 6.0  Use (parentheses) for readability or to intentionally alter an expression: double C, F; double C, F; F = 212.0; F = 212.0; C = 5.0 / 9.0 * (F - 32); C = 5.0 / 9.0 * (F - 32); What is the current value of C ____? What is the current value of C ____?

Math functions  Java’s Math class provides a collection of mathematical and trigonometric functions Math.sqrt(16.0) returns 4.0 Math.min(-3, -9) returns -0 Math.max(-3.0, -9.0) returns -3.0 Math.abs(4 - 8) returns 4 Math.floor(1.9) returns 1.0 Math.pow(-2.0, 4.0) returns 16.0

int Arithmetic  int variables are similar to double, except they can only store whole numbers (integers) int anInt = 0; int anInt = 0; int another = 123; int another = 123; int noCanDo = 1.99; // ERROR int noCanDo = 1.99; // ERROR  Division with integers is also different Performs quotient remainder whole numbers only Performs quotient remainder whole numbers only anInt = 9 / 2; // anInt = 4, not 4.5 anInt = 9 / 2; // anInt = 4, not 4.5 anInt = anInt / 5; What is anInt now? ___ anInt = anInt / 5; What is anInt now? ___ anInt = 5 / 2; What is anInt now? ___ anInt = 5 / 2; What is anInt now? ___

The integer % operation  The Java % operator returns the remainder anInt = 9 % 2;// anInt ___ 1 ___ anInt = 9 % 2;// anInt ___ 1 ___ anInt = 101 % 2; What is anInt now? ___ anInt = 101 % 2; What is anInt now? ___ anInt = 5 % 11; What is anInt now? ___ anInt = 5 % 11; What is anInt now? ___ anInt = 361 % 60; What is anInt now? ___ anInt = 361 % 60; What is anInt now? ___ int quarter; int quarter; quarter = 79 % 50 / 25; What is quarter? ___ quarter = 79 % 50 / 25; What is quarter? ___ quarter = 57 % 50 / 25; What is quarter now? ___ quarter = 57 % 50 / 25; What is quarter now? ___

Integer Division, watch out … What is the current value of celcius _____? What is the current value of celcius _____? int celcius, fahrenheit; fahrenheit = 212; celcius = 5 / 9 * (fahrenheit - 32);