JAVA Ch. 4. Variables and Constants Lawrenceville Press

Similar documents
Chapter 2. Elementary Programming

Computer Components. Software{ User Programs. Operating System. Hardware

Programming with Java

CSC 1214: Object-Oriented Programming

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Computer Components. Software{ User Programs. Operating System. Hardware

CEN 414 Java Programming

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Chapter 2 ELEMENTARY PROGRAMMING

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

Elementary Programming

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

3. Java - Language Constructs I

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Program Fundamentals

COMP 202 Java in one week

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

CS313D: ADVANCED PROGRAMMING LANGUAGE

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

More Things We Can Do With It! Overview. Circle Calculations. πr 2. π = More operators and expression types More statements

Introduction to Programming Using Java (98-388)

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Computer Programming, I. Laboratory Manual. Experiment #3. Selections

Lecture 2: Variables and Operators. AITI Nigeria Summer 2012 University of Lagos.

Chapter 2 Elementary Programming

Lecture Notes. System.out.println( Circle radius: + radius + area: + area); radius radius area area value

Computational Expression

Accelerating Information Technology Innovation

Chapter 3 Syntax, Errors, and Debugging. Fundamentals of Java

Introduction to C# Applications

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont.

Chapter 02: Using Data

-Alfred North Whitehead. Copyright Pearson Education, 2010 Based on slides by Marty Stepp and Stuart Reges from

DM550 Introduction to Programming part 2. Jan Baumbach.

Chapter 3. Selections

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

Java Identifiers. Java Language Essentials. Java Keywords. Java Applications have Class. Slide Set 2: Java Essentials. Copyright 2012 R.M.

Introduction to Computer Programming

Chapter 2: Basic Elements of Java

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

Java Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2

Object Oriented Programming. Java-Lecture 1

PROGRAMMING FUNDAMENTALS

Programming Lecture 3

Chapter 2: Using Data

CHAPTER 2 Java Fundamentals

Basic Operations jgrasp debugger Writing Programs & Checkstyle

Course Outline. Introduction to java

Java Programming. Atul Prakash

Java Programming Language Mr.Rungrote Phonkam

An overview of Java, Data types and variables

Chapter 12 Exception Handling

Software Practice 1 Basic Grammar

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

Chapter 3: Operators, Expressions and Type Conversion

AP CS A Exam Review Answer Section

Simple Java Reference

Chapter 2: Using Data

Fundamentals of Programming

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

C: How to Program. Week /Mar/05

BASIC ELEMENTS OF A COMPUTER PROGRAM

Basics of Java Programming

COMP 202 Java in one week

DM503 Programming B. Peter Schneider-Kamp.

3. Java - Language Constructs I

Chapter 2 Elementary Programming

Full file at

Entry Point of Execution: the main Method. Elementary Programming. Compile Time vs. Run Time. Learning Outcomes

Java for Python Programmers. Comparison of Python and Java Constructs Reading: L&C, App B

Getting started with Java

COMP 202. Java in one week

More on variables and methods

I. Variables and Data Type week 3

Fundamental of Programming (C)

Software Practice 1 - Basic Grammar Basic Syntax Data Type Loop Control Making Decision

The keyword list thus far: The Random class. Generating "Random" Numbers. Topic 16

Lecture 6. Assignments. Java Scanner. User Input 1/29/18. Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4

Language Fundamentals Summary

Oct Decision Structures cont d

2.5 Another Application: Adding Integers

Creating a C++ Program

CS 302: Introduction to Programming

Topic 16. battle -they are strictly limited in number, they require fresh horses, and must only be made at decisive moments." -Alfred North Whitehead

Elementary Programming. CSE 114, Computer Science 1 Stony Brook University

2 rd class Department of Programming. OOP with Java Programming

Midterm Examination (MTA)

Reading Input from Text File

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Java Programming Language. 0 A history

CS111: PROGRAMMING LANGUAGE II

Introduction to Java Applications; Input/Output and Operators

Motivations. Chapter 2: Elementary Programming 8/24/18. Introducing Programming with an Example. Trace a Program Execution. Trace a Program Execution

COMP-202: Foundations of Programming. Lecture 2: Variables, and Data Types Sandeep Manjanna, Summer 2015

Full download all chapters instantly please go to Solutions Manual, Test Bank site: testbanklive.com

Lecture Set 2: Starting Java

JAVA Programming Fundamentals

Transcription:

JAVA Ch. 4 Variables and Constants Slide 1

Slide 2 Warm up/introduction int A = 13; int B = 23; int C; C = A+B; System.out.print( The answer is +C);

Slide 3 Declaring and using variables

Slide 4 Declaring Variables Variable name for a value stored in memory. Variables must be declared before they are used. Variable declarations take the form: <data type> <variable name/identifier>; int length;

Slide 5 Using Variables An assignment statement is formed with the variable type and name on the left side of an equal sign; and the value it is to receive on the right side of the equal sign. int A = 40; Operator the equal sign (=) Literal the value to the right of the equal sign.

Slide 6 Chapter 4 Assignment Statement An assignment statement gives a value to a variable. Assignment can take several forms: x = 5; a literal (5) is assigned to x x = y + 2; the value of an expression (y + 2) is assigned to x x = z; the value of another variable (z) is assigned to x

Slide 7 Using Variables int A = 10; int A; What is the difference between the two assignments statements above? If a variable does not include a literal, that variable s value is going to change as we navigate its class.

Slide 8 Chapter 4 Variable Assignment A variable can store only one value at any time. int x; x = 5; x = 10; x 10 5

Slide 9 Types of Variables

Slide 10 Chapter 4 Primitive Data Types Type Storage Required int 4 bytes double 8 bytes char 2 bytes boolean 1 bit Notes: int integer double decimal number char character boolean true or false

Slide 11 Outputting variable values

Slide 12 Outputting Variables When outputting variables we must concatenate the value of the variable to a string. To do this we put a (+) in front of the variable name in our output statement. int s = 90; System.out.print( My score is +s out of 100. ); My score is 90 out of 100.

Slide 13 Current Class Format

Slide 14 /*Name *Date *Class *Period *Class name */ public class ClassName { public static void main(string[] args) { int A = 10; int Variable B = 20; int C; Initialization } C= A + B; System.out.print("this Program statements is my score "+C); }

Slide 15 /*Name *Date *Class *Period *Class name */ public class ClassName { public static void main(string[] args) { int A = 10; int B = 80; int C; } C= A + B; System.out.print("this is my score "+C); }

Slide 16 Practice -

Slide 17 Creating a Ch. 4 Project Create a new project. Call it First initial, last name Chapter 4 BBarrett Chapter 4

Slide 18 Practice - In your chapter 4 project, create a class titled: RectanglePerimeter We will do this together In your chapter 4 project, create a class titled: DistancePtOne Pg. 79 You are responsible for completing tis on your own. Mr. Barrett will help you if needed.

Slide 19 Java Packages

Slide 20 Java Packages Java has tools that are available to the programmer. They are called packages, and Java comes ready equipped for them to be used. These classes contain general utility classes, and special purpose packages. The most fundamental packages is the Java.util.*; package

Slide 21 Java Packages: Receiving input from your end-user

Slide 22 Java Packages The first package we will introduce will be the: Package. import java.util.scanner; This is the import statement used to make the package accessible to a method/project.

Slide 23 Java Packages Instantiation after importing our readymade package, we must initialize the package. This process is called instantiation. The following statement is used to initialize our scanner: Scanner input = new Scanner(System.in);

Class importation Slide 24 /* *Name *Date *Class *Period *Class name */ public class ClassName { public static void main(string[] args) { Variable Initialization Package Instantiation Program statements } }

Slide 25 import java.util.scanner; /* *Name *Date *Class *Period *Class name */ public class ClassName { public static void main(string[] args) { int x = 10; int y = 5; int c; Scanner input = new Scanner(System.in); - Program statements } }

Slide 26 Receiving Data From your end user Part of the java.util.scanner package To receive data from the end user, the following methods are required. Methods include: variablename = input.nextint(); variablename = input.nextline(); variablename = input.next(); variablename = input.nextdouble(); variablename = input.nextboolean(); Input.close();

Slide 27 Receiving Data From your end user Methods include: input.nextint(); - integer input.next(); - string input.nextdouble(); - decimal input.nextboolean(); - boolean input.close(); - closes the input stream

Slide 28 Receiving data example: import java.util.scanner; int x, y, z; Scanner input = new Scanner(System.in); System.out.print("Enter your first value: "); x = input.nextint(); System.out.print("Enter your second value: "); y = input.nextint(); input.close(); z=x+y; System.out.print("The sum of your numbers is "+z);

Slide 29 Abstract Data Types

Slide 30 Primitive data types We already discussed primitive data types, i.e., integers, doubles, characters, and Booleans; but there is another type of data that we must cover

Slide 31 Abstract Data Types Abstract data type A class. A data type that can store data and methods. Method A named set of statements that perform a single, well-defined task. Object A variable declared with a class.

Slide 32 Creating a new object Creating a new object is called instantiation. In addition to declaring a variable to refer to the object, the object must be created and initialized in a statement that takes the form: <class> <variable name> = new <class>(<arguments>);

Slide 33 Abstract Data Types Where have we seen this before? <class> <variable name> = new <class>(<arguments>); Scanner input = new Scanner(System.in); Our scanner class is the first abstract data type you have been exposed to.

Slide 34 Chapter 4 Abstract Data Types A variable declared with a class is called an object. For example, the object spot is type Circle: Circle spot = new Circle(4); spot getradius() area()

Slide 35 Practice

Slide 36 Practice In your chapter 4 project, create a class titled: DistancePtTwo Page 82 (bottom) You are responsible for completing this on your own. Mr. Barrett will help you if needed.

Slide 37 Algorithms

Slide 38 Algorithms Algorithm A set of steps that outline how to solve a problem.

Slide 39 Algorithms Algorithm for DistancePtTwo Class 1. Set class template 2. Initialize our variables 3. Initialize our scanner 4. Prompt end user to enter our needed values 5. Calculate the total distance 6. Output total distance

Slide 40 Numeric Expressions

Slide 41 Numeric Expressions A numeric expression contains at least one operand (a value or primitive variable), and my contain operators.

Slide 42 Numeric Expressions Our Operators + : addition - : subtraction / : division % : modulus division (the remainder) * : multiplication = : equals > : greater than < : less than

Slide 43 Numeric Expressions Our Operators >= : greater than or equal to <= : less than or equal to!= : not equal to

Slide 44 Chapter 4 Integer Division Integer division (/) is performed when both operands are integers. Only the integer portion of the quotient is returned:

Slide 45 Chapter 4 Real Division Real division (/) is performed when one or both operands are type double. The entire quotient, including the decimal portion is returned: double result; result = 20.0/7.0; //result is 2.857

Slide 46 Chapter 4 Modulus Division Modulus division (%) returns the remainder of a division operation:

Slide 47 Chapter 4 Modulus Division 7 % 20 = 7 (zero with a remainder of seven.) 7 %? = (a number between 0 and 6) 100 %? = (a number between 0 and 99)

Chapter 4 Slide 48 Operator Precedence Operators in Java have the following precedence: 1. multiplication and division 2. addition and subtraction Operators of the same precedence are evaluated in order from left to right. For example, multiplication is performed first, then division, and finally addition: 5 + 6 * 4 / 2 = 17

Chapter 4 Changing the Order of Operations Slide 49 The order in which operators are evaluated can be changed by using parentheses. For example, addition is performed first, then multiplication, and finally division: (5 + 6) * 4 / 2 = 22

Slide 50 Practice

Slide 51 Practice In your chapter 4 project, create a class titled: DivisionOperators Follow along with Mr. Barrett when writing this program. Program found on pages 83 and 84.

Slide 52 Practice In your chapter 4 project, create a class titled: Digits Page 84. Write the digits program.

Slide 53 Assignment Operators

Slide 54 Chapter 4 Assignment Operators Operator Operation += addition and then assignment -= subtraction and then assignment *= multiplication and then assignment /= division and then assignment %= modulus division and then assignment

Slide 55 Assignment Operators (+) int A = 10; int B = 5; A += B; System.out.print( Our output is +A); 15

Slide 56 Assignment Operators (-) int A = 10; int B = 5; A -= B; System.out.print( Our output is +A); 5

Slide 57 Assignment Operators (*) int A = 10; int B = 5; A *= B; System.out.print( Our output is +A); 50

Slide 58 Assignment Operators (/) int A = 10; int B = 5; A /= B; System.out.print( Our output is +A); 2

Slide 59 Assignment Operators (%) int A = 17; int B = 5; A %= B; System.out.print( Our output is +A); 2

Slide 60

Slide 61 Type Casting

Chapter 4 Type Casting Slide 62 Type Casting converts a number of one type to a number of a different, but compatible type. Type casting is used to: 1. make the operand types in an expression match. For example, wholenum = (int)y * 2 2. truncate the decimal portion of a double. For example, wholenum = (int)z 3. change the way in which a division (/) operation will be performed. For example, realdivision = (double)a / (double)b

Slide 63 Type Casting Casting a double to an int truncates, or removes, the decimal portion of the number.

Slide 64 Type Casting public class TypeCasting { public static void main(string[] args) { int a = 2; int b = 3; int c; } } c=(double)a*b; System.out.print(+c); 6.0

Slide 65 Type Casting: Truncating public class TypeCasting { public static void main(string[] args) { double a = 2.2; double b = 3.1; double c; } } c=a*b; System.out.print(+(int)c); 6

Slide 66 Programming Errors

Slide 67 Chapter 4 Programming Errors Syntax errors violate the rules of Java. look for the red (X) Logic errors, also called semantic errors, occur in statements that are syntactically correct, but produce undesired or unexpected results. Run-time errors, also called exceptions, halt program execution at the statement that cannot be executed. One type of exception is called InputMismatchException. Look for the error that appears in your console.

Slide 68 Practice

Slide 69 Practice In your chapter 4 project, create a class titled: GradeAvg1of2 Follow along with Mr. Barrett when writing this program. Program found on page 85.

Slide 70 Practice In your chapter 4 project, create a class titled: TempConverter Follow along with Mr. Barrett when writing this program. Program found on page 85.

Slide 71 Number Formatting Class

Slide 72 Numeric Output The NumberFormat class is used to create objects that format numbers. NumberFormat objects return a string that contains a formatted number. 1. $21.00 2. 1,342 3. 0.667 4. 33%

Slide 73 Numeric Output The number format class allows us to output 1. Money - $x.xx 2. Number Format xx,xxx 3. Decimal - x.xxx 4. Percentage - xx%

Slide 74 Numeric Output (step 1) Import the NumberFormating class on line one or two of your class. import java.text.numberformat

Slide 75 Numeric Output (step 2) Initialize the format you need to use: 1. NumberFormat money = NumberFormat.getCurrencyInstance(); 2. NumberFormat number = NumberFormat.getIntegerInstance(); 3. NumberFormat decimal = NumberFormat.getNumberInstance(); 4. NumberFormat percent = NumberFormat.getPercentInstance();

Slide 76 Numeric Output (step 3) Prepare output statement: 1. System.out.print(money.format(variableName)); 2. System.out.print(number.format(variableName)); 3. System.out.print(decimal.format(variableName)); 4. System.out.print(percent.format(variableName));

Slide 77 Numeric Output The number format class allows us to output Money - $x.xx - Number Format xx,xxx Decimal - x.xxx Percentage - xx%

Slide 78 Practice In your chapter 4 project, create a class titled: FormattingNumericOutput Copy this class into your chapter 4 project. (P 86)

Slide 79 Named Constants

Chapter 4 Slide 80 Named Constants A constant is a name for a memory location that stores a value that cannot be changed from its initial assignment. The keyword final is used in the variable s declaration. Constant identifiers are typically all uppercase with an underscore (_) separating words within the identifier name. EX: final int LAST_NUMBER = 100 final double PI = 3.14

Slide 81 Public class CircleArea{ public static void main (String[] args){ final double PI = 3.14; double radius = 5; double area; } } area = PI* radius * radius; System.out.print( The area is +area);

Slide 82 Final CH 4 Programs

Slide 83 Final CH 4 Programs PizzaCost (p.99) Change (p.100) TimeConversion (p.101) Sleep (p.101) Spending (p.102)

Slide 84

Chapter 4 Slide 85 Java Keywords abstract double int strictfp boolean else interface super break extends long switch byte final native synchronized case finally new this catch float package throw char for private throws class goto protected transient const if public try continue implements return void default import short volatile do instanceof static While

Slide 86 Chapter 4 Flowchart Symbols process

Slide 87 Chapter 4 The BirthdayGame Flowchart