Java Concepts Chapter 2 - Using Objects Mr. Smith AP Computer Science A.

Slides:



Advertisements
Similar presentations
L2:CSC © Dr. Basheer M. Nasef Lecture #2 By Dr. Basheer M. Nasef.
Advertisements

Slide 1 Chapter 4 Assignment Statement An assignment statement gives a value to a variable. Assignment can take several forms: x = 5; a literal (5) is.
Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
Primitive Data Types and Operations. Introducing Programming with an Example public class ComputeArea { /** Main method */ public static void main(String[]
Introduction to Computers and Programming Lecture 4: Mathematical Operators New York University.
Aalborg Media Lab 21-Jun-15 Software Design Lecture 2 “ Data and Expressions”
Fundamentals of Java Lesson 3: Syntax, Errors, and Debugging
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
JAVA PROGRAMMING Chapter 3 SYNTAX, ERRORS, AND DEBUGGING
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 2 Elementary Programming.
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 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
Lesson 3: Syntax, Errors, and Debugging. Objectives: –Construct and use numeric and string literals. –Name and use variables and constants. –Create arithmetic.
1 Do you have a CS account? Primitive types –“ building blocks ” for more complicated types Java is strongly typed –All variables in a Java program must.
Chapter 4 Variables and Constants. Goals and Objectives 1. Understand simple data types (int, boolean, double). 2. Declare and initialize variables using.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
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.
Chapter 2: Using Data.
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
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.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
CHAPTER 4 GC 101 Data types. DATA TYPES  For all data, assign a name (identifier) and a data type  Data type tells compiler:  How much memory to allocate.
1 Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
FUNDAMENTALS 2 CHAPTER 2. OPERATORS  Operators are special symbols used for:  mathematical functions  assignment statements  logical comparisons 
Data Types and Statements MIT 12043: Fundamentals of Programming Lesson 02 S. Sabraz Nawaz Fundamentals of Programming by
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[]
Operators and Expressions. 2 String Concatenation  The plus operator (+) is also used for arithmetic addition  The function that the + operator performs.
1 Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading:
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
COMP 110: Spring Announcements Lab 1 due Wednesday at Noon Assignment 1 available on website Online drop date is today.
Java – Variables and Constants By: Dan Lunney. Declaring Variables All variables must be declared before they can be used A declaration takes the form:
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
Variables and Constants Chapter 4 Review. Declaring Variables A variable is a name for a value stored in memory. Variables and constants are used in programs.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Elementary Programming.
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.
3.1 Language Elements Language elements: Vocabulary: The words and symbols in the language. Syntax: The rules for combining words into statements. Semantics:
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.
What will each of the following lines print? System.out.println("number" ); number645 System.out.println("number" + (6 + 4)+ 5); number105 System.out.println(6.
© 2004 Pearson Addison-Wesley. All rights reserved August 27, 2007 Primitive Data Types ComS 207: Programming I (in Java) Iowa State University, FALL 2007.
CompSci 230 S Programming Techniques
Chapter 2 Variables.
Chapter 4 Assignment Statement
TemperatureConversion
Chapter 3 Syntax, Errors, and Debugging
Elementary Programming
Primitive Data Types August 28, 2006 ComS 207: Programming I (in Java)
Lesson 3: Syntax, Errors, and Debugging
Multiple variables can be created in one declaration
Java Concepts Chapter 2 - Using Objects
Chapter 3 Assignment Statement
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 Variables.
elementary programming
Primitive Types and Expressions
Chapter 2 Variables.
Presentation transcript:

Java Concepts Chapter 2 - Using Objects Mr. Smith AP Computer Science A

Basic Java Syntax and Semantics Data Types: Primitive data types  Numbers (integer and floating point)  Characters (“A”, “B”, etc.) (char)  Booleans (true and false) (boolean)  Numbers use operators (addition and multiplication) Objects  Are sent messages  Must be instantiated before use (remember robots?) Strings  Are objects  Are sent messages  Do not need to be instantiated  Can be combined using the concatenation operator (+) Objects Strings

Basic Java Syntax and Semantics Numeric Data Types: 6 numeric data types are used in Java:  int (integer, no decimals)  double (double precision floating-point numbers; i.e. numbers with decimals)  short  long  byte  float Not in AP CS subset.

Basic Java Syntax and Semantics Some Java numeric data types: I hope I don’t have to memorize this

Basic Java Syntax and Semantics Literals: By literal, we mean any number, text, or other information that represents a specific value and does not change:  (PI)  7.21  “Hello World” In the statement:  int month = 10;  10 is the literal

Basic Java Syntax and Semantics Identifiers An identifier is the name of a variable, method, or class Java imposes the following rules on identifiers:  Can be made up of letters, digits, underscore (_), and dollar sign ($) characters.  Cannot start with a digit: score1 is legal but not 1score  Cannot use reserved symbols such as ! and %: money! is not a legal identifier.  Spaces are not permitted: myScore is legal but not my Score.  Cannot use reserved words such as new, public, while. int newNum = 2; is legal but int new = 2; is not valid.  Identifiers are case sensitive: myScore and myscore are different identifiers.

Basic Java Syntax and Semantics Questions/Practice: What is the data type of each of the following values?  56  “56”  56.0 Tell me whether each of these identifiers are legal or illegal:  100Answers  void  my_cash   money$value  lucky number Create a variable to store the school phone number and use camel case. int String double illegal legal illegal legal illegal

Basic Java Syntax and Semantics Declarations Variables  A variable is a storage location in memory that has a type, name (identifier), and value.  Before using a variable for the first time, the program must declare its type.  Declare a variable in a variable declaration statement (i.e. int year; )  Several variables can be declared in a single declaration.  Remember to use camelCase for variable names

Basic Java Syntax and Semantics Declarations Variables  Syntax: = ; OR ;  Initial values can be assigned in the same statement as its variable declaration: int x, y, z = 7; double p, q = 1.41, t; String name = “AP Computer Science”; UrRobot karel = new UrRobot(1,1,East,0); String name = 13; Types do not match is the same as: int x; int y; int z = 7;

Basic Java Syntax and Semantics Objects  Declare the object variable, instantiate or create an object, and assign the object to the variable. = new () Robot bot = new Robot(1, 1, North, 0); Constants  The value cannot change final double SALES_TAX_RATE = 7.00;  final indicates a variable is declared as a constant  The naming convention for constants is that they are written in UPPERCASE with underlines between words.  Trying to change the value of a constant after it is initialized will be flagged by the compiler as an error. Literal Constants

Basic Java Syntax and Semantics Assignment Statements The assignment operator is = An assignment statement has the following form: = ; The value of the expression on the right is assigned to the variable on the left. It simply replaces the value of the variable: double celsius; double fahrenheit = 82.5; //Assign 82.5 to variable fahrenheit celsius = (fahrenheit – 32.0) * 5.0 / 9.0;

Basic Java Syntax and Semantics Assignment Statements It is an error to use a variable that has never had anything assigned to it: int myNumber; System.out.println(myNumber); The solution to this problem is: int myNumber; myNumber = 20; // Assign a value to myNumber System.out.println(myNumber);

Basic Java Syntax and Semantics Arithmetic Expressions An arithmetic expression consists of operands and operators combined in a manner used in algebra. The usual rules apply:  Remember the mnemonic phrase: “Please Excuse My Dear Aunt Sally”  Multiplication and division are evaluated before addition and subtraction.  Operators of equal precedence are evaluated from left to right.  Parentheses can be used to change the order of evaluation.

Basic Java Syntax and Semantics Common operators and their precedence:

Basic Java Syntax and Semantics

Terminal I/O for Different Data types Scanner class: reads from the input stream **** new for Java 5.0, but not tested on AP exam Here are the methods in the Scanner class : METHODDESCRIPTION double nextDouble()Returns the first double in the input line. Leading and trailing spaces are ignored. int nextInt()Returns the first integer in the input line. Leading and trailing spaces are ignored. String nextLine()Returns the input line, including leading and trailing spaces. Warning: A leading newline is returned as an empty string.

Terminal I/O for Different Data types The following program illustrates the major features of terminal I/O: import java.util.Scanner; public class TestTerminalIO { public static void main (String [] args) { Scanner in = new Scanner(System.in); System.out.print ("Enter your name (a string): "); String name = in.nextLine(); System.out.print("Enter your age (an integer): "); int age = in.nextInt(); System.out.print("Enter your weight (a double): "); double weight = in.nextDouble();

Terminal I/O for Different Data types System.out.println ("Greetings " + name + ". You are " + age + " years old and you weigh " + weight + " pounds."); }

Terminal I/O for Different Data types Warning: A leading newline is returned as an empty string. // now change the order of the input, // putting the string last System.out.print("Enter your age (an integer): "); int age = in.nextInt(); System.out.print("Enter your weight (a double): "); double weight = in.nextDouble(); System.out.print ("Enter your name (a string): "); String name = in.nextLine();

Terminal I/O for Different Data types The string name is the empty string. The reason is that the method nextDouble ignored but did not consume the new line that the user entered following the number. Therefore, this newline character was waiting to be consumed by the next call of nextLine, which was expecting more data. To avoid this problem, you should either input all lines of text before the numbers or, when that is not feasible, run an extra nextLine after numeric input to eliminate the trailing newline characters.

Terminal I/O for Different Data types Warning: A leading newline is returned as an empty string. // now change the order of the input, // putting the string last System.out.print("Enter your age (an integer): "); int age = in.nextInt(); System.out.print("Enter your weight (a double): "); double weight = in.nextDouble(); in.nextLine(); // to consume the newline char System.out.print ("Enter your name (a string): "); String name = in.nextLine();

TemperatureConversion Create a TemperatureConversion class as follows:  Enter a prompt for the Fahrenheit temperature in the console (using the Scanner class), and allow the user to enter the temperature there.  Convert the temperature from Fahrenheit to Celsius  Convert the temperature from Fahrenheit to Kelvin  Print a message to the console that shows the conversion, such as: 50.0 F = 10.0 C 50.0 F = K  Do the same thing to allow the user to enter the temperature in Celsius and then print the conversion to Fahrenheit and Kelvin. 0.0 C = 32.0 F 0.0 C = K  Do the same thing to allow the user to enter the temperature in Kelvin and then print the conversion to Fahrenheit and Celsius K = 50.0 F K = 10.0 C  The conversion formulas can easily be found on the internet  Please try these conversions where Fahrenheit = 50 and Celsius = 0. Also try a couple of other examples of your choice to verify that the program is working correctly.

Basic Java Syntax and Semantics Division: The semantics of division are different for integer and floating-point operands. Thus: 5.0 / / 2 Modulus: The operator % yields the remainder obtained when one number is divided by another. Thus: 9 % % 5.1 yields 2.5 yields 2 (a quotient in which the decimal portion of the answer is simply dropped) yields 4 yields 4.2

Basic Java Syntax and Semantics Mixed-Mode Arithmetic Intermixing integers and floating-point numbers is called mixed-mode arithmetic. When arithmetic operations occur on operands of different numeric types, the less inclusive type ( int ) is temporarily and automatically converted to the more inclusive type ( double ) before the operation is performed. Examples: 5.0 / / / 2 yields 2.5 (both double) yields 2 (both int) yields 2.5 (mixed) but

Basic Java Syntax and Semantics Mixed-mode assignments are also allowed, provided the variable on the left is of a more inclusive type than the expression on the right. Otherwise, a syntax error occurs.  double d;  int i;  i = 45;  d = i;  i = d;  Can put an integer into a double but not a double into an integer. -- Syntax error because i is less inclusive than d. -- OK, because i is an integer and 45 is an integer. -- OK, because d is more inclusive than i. The value 45.0 is stored in d.

Basic Java Syntax and Semantics Difficulties associated with mixed-mode arithmetic can be circumvented using a technique called “casting”. This allows one data type to be explicitly converted to another. The cast operator, either (int) or (double), appears immediately before the expression it is supposed to convert. The (int) cast simply throws away the digits after the decimal part. The (double) cast inserts a.0 after the integer.

Basic Java Syntax and Semantics Examples: double x, y; int m, n; a)x = (double) 5 / 4; x = 5.0 / 4; x = 1.25 b)y = (double) (5 / 4); y = (double) (1); y = 1.0 c)m = (int) (x + 0.5); if x = 1.1, then m = (int) (1.6); m = 1

Basic Java Syntax and Semantics String Expressions and Methods Simple Concatention  The concatenation operator uses the plus symbol (+) String firstName, //declare four string lastName, //variables fullName, lastThenFirst; firstName = “Debbie”; //initialize firstName lastName = “Klipp”; //initialize lastName fullName = firstName +” “ + lastName; //yields “Debbie Klipp” lastThenFirst = lastName +”, “+ firstName; //yields “Klipp, Debbie”

Basic Java Syntax and Semantics Concatenating Strings and Numbers  Strings also can be concatenated to numbers. (The number is automatically converted to a string before the concatenation operator is applied.) String message; int x = 20, y = 35; message = “Bill sold ” + x + “ and Sylvia sold ” + y + “ subscriptions.”; // yields “Bill sold 20 and Sylvia sold 35 subscriptions.”

Basic Java Syntax and Semantics Precedence of Concatenation  The concatenation operator has the same precedence as addition, which can lead to unexpected results: a) “number ” b) “number ” + (3 + 4) c) “number ” + 3 * 4 d) “ number” number 34 number 7 number 12 7 number

Basic Java Syntax and Semantics The length Method Strings are objects and implement several methods. A String returns its length in response to a length message: String theString; int theLength; theString = “the cat sat on the mat.”; theLength = theString.length(); // yields 23

What is the result of printing the following to the console? If you don’t know the answer, then create a client class and print it to the console using a System.out.println() statement.  Calculate the following and print the results to the console: 15 / 6 ______________________ 15.0 / 6.0 ______________________ 15.0 / 6 ______________________ 15 / 6.0 ______________________ Find the remainder of 8 / 3 Syntax: _____________ Answer: _______ Find the remainder of 8.95 / 1.1 Syntax: _____________ Answer: _______ (double) 15 / 6 ______________________ (double) (15 / 6) ______________________ (double) 15 / ______________________ (int) ((double) 15 / ) ______________________  Output the following string functions to the console: “Age “ ______________________ “Age “ + (2 + 8) ______________________ “Age “ + 2 * 8 ______________________ “ Age” ______________________ If name = “John Doe”, then what is name.length(); _______

What is the result of printing the following to the console? If you don’t know the answer, then create a client class and print it to the console using a System.out.println() statement.  Calculate the following and print the results to the console: 15 / / / 6 15 / 6.0 Find the remainder of 8 / 3 Syntax: Answer: Find the remainder of 8.95 / 1.1 Syntax: Answer: (double) 15 / 6 (double) (15 / 6) (double) 15 / (int) ((double) 15 / )  Output the following string functions to the console: “Age “ “Age “ + (2 + 8) “Age “ + 2 * “ Age” If name = “John Doe”, then what is name.length(); % % Age 28 Age 10 Age Age 8