Java Concepts Chapter 2 - Using Objects

Slides:



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

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[]
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.
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?
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.
Java Concepts Chapter 2 - Using Objects Mr. Smith AP Computer Science A.
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.
Chapter 2 Variables.
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 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: 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.
© 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
Topic 2 Elementary Programming
Chapter 2 Variables.
Chapter 4 Assignment Statement
TemperatureConversion
Chapter 3 Syntax, Errors, and Debugging
Elementary Programming
Introduction to Computer Science / Procedural – 67130
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
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
Building Java Programs
Chapter 2 Variables.
Fundamentals 2.
Chapter 2: Java Fundamentals
Building Java Programs Chapter 2
elementary programming
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Primitive Types and Expressions
Building Java Programs
Unit 3: Variables in Java
Building Java Programs Chapter 2
Building Java Programs
Chapter 2 Variables.
Building Java Programs
Building Java Programs
Building Java Programs
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 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 <myVar> money$value lucky number Create a variable to store the school phone number and use camel case. int String double illegal legal

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: <typeName> <variableName> = <value>; OR <typeName> <variableName>; 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; is the same as: int x; int y; int z = 7; Types do not match

Basic Java Syntax and Semantics Objects Declare the object variable, instantiate or create an object, and assign the object to the variable. <className> <variableName> = new <className>() 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. Constants Literal

Basic Java Syntax and Semantics Assignment Statements The assignment operator is = An assignment statement has the following form: <variableName> = <expression>; 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: myNumber = 20; // Assign a value to 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: METHOD DESCRIPTION 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 = 283.15 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 = 273.15 K Do the same thing to allow the user to enter the temperature in Kelvin and then print the conversion to Fahrenheit and Celsius. 283.15 K = 50.0 F 283.15 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.0 5 / 2 Modulus: The operator % yields the remainder obtained when one number is divided by another. Thus: 9 % 5 9.3 % 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.0 5 / 2 5.0 / 2 yields 2.5 (both double) yields 2 (both int) but yields 2.5 (mixed)

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. -- 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. -- Syntax error because i is less inclusive than 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 ” + 3 + 4 b) “number ” + (3 + 4) c) “number ” + 3 * 4 d) 3 + 4 + “ 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 / 6 + 0.6 ______________________ (int) ((double) 15 / 6 + 0.6) ______________________ Output the following string functions to the console: “Age “ + 2 + 8 ______________________ “Age “ + (2 + 8) ______________________ “Age “ + 2 * 8 ______________________ 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.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 / 6 + 0.6 (int) ((double) 15 / 6 + 0.6) Output the following string functions to the console: “Age “ + 2 + 8 “Age “ + (2 + 8) “Age “ + 2 * 8 2 + 8 + “ Age” If name = “John Doe”, then what is name.length(); 2 2.5 8 % 3 2 8.95 % 1.1 .15 2.0 3.1 3 Age 28 Age 10 Age 16 10 Age 8

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: (3.0 + 6.0) / 2 * 3 3.0 + 6.0 / 2 * 3 3.0 + 6.0 / (2 * 3) 8 + 6 + 3.5 - 6.0 (int) 15.0 / 4 * 4 (double) (15 / 6 + 9) (int) Math.PI * 10 (int) (4.0 / 2) * 3 + 1 .5 3.0 / 6.0 + (3 * 3) 3 / 6 + 7 / 14 (((6 * 4) + (7 * 2)* 2) + 5) 13.5 12.0 4.0 11.5 12 11.0 30 7.5 9.5 57