4 Copyright © 2005, Oracle. All rights reserved. Exploring Primitive Data Types and Operators.

Slides:



Advertisements
Similar presentations
1 C Programming. 2 Operators 3 Operators in C An operator is a symbol that tells the computer to perform certain mathematical or logical manipulation.
Advertisements

12 Copyright © 2005, Oracle. All rights reserved. Structuring Code Using Abstract Classes and Interfaces.
3 Copyright © 2005, Oracle. All rights reserved. Basic Java Syntax and Coding Conventions.
11 Copyright © 2005, Oracle. All rights reserved. Using Arrays and Collections.
7 Copyright © 2005, Oracle. All rights reserved. Creating Classes and Objects.
10 Copyright © 2005, Oracle. All rights reserved. Reusing Code with Inheritance and Polymorphism.
© Vinny Cahill 1 Writing a Program in Java. © Vinny Cahill 2 The Hello World Program l Want to write a program to print a message on the screen.
1 Variables and Data Types. 2 Variable Definition a location in memory, referenced by a name (identifier), where data of a given type can be stored, changed,
CSci 1130 Intro to Programming in Java
Chapter Three Arithmetic Expressions and Assignment Statements
Types of selection structures
Chapter 2 JAVA FUNDAMENTALS
1 Chapter 3:Operators and Expressions| SCP1103 Programming Technique C | Jumail, FSKSM, UTM, 2006 | Last Updated: July 2006 Slide 1 Operators and Expressions.
PSSA Preparation.
COMP 14 Introduction to Programming
DATA TYPES, VARIABLES, ARITHMETIC. Variables A variable is a “named container” that holds a value. A name for a spot in the computer’s memory This value.
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.
IntroductionIntroduction  Computer program: an ordered sequence of statements whose objective is to accomplish a task.  Programming: process of planning.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Review… Yong Choi BPA CSUB. Access Modifier public class HelloWorldApp –More detailes of Java key (reserved) wordJava key (reserved) word –The keyword,
Aalborg Media Lab 21-Jun-15 Software Design Lecture 2 “ Data and Expressions”
Program Elements We can now examine the core elements of programming (as implemented in Java) We focuse on: data types variable declaration and use, constants.
ECE122 L3: Expression Evaluation February 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 3 Expression Evaluation and Program Interaction.
0 Chap. 2. Types, Operators, and Expressions 2.1Variable Names 2.2Data Types and Sizes 2.3Constants 2.4Declarations Imperative Programming, B. Hirsbrunner,
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
Primitive Types Java supports two kinds of types of values – objects, and – values of primitive data types variables store – either references to objects.
JavaScript, Third Edition
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
Expressions Java 3.1 Primitive data types 3.2 Constants and variables
1 Chapter Two Using Data. 2 Objectives Learn about variable types and how to declare variables Learn how to display variable values Learn about the integral.
1 Identifiers  Identifiers are the words a programmer uses in a program  An identifier can be made up of letters, digits, the underscore character (
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
General Features of Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.
2440: 211 Interactive Web Programming Expressions & 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 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.
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.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
SE-1010 Dr. Mark L. Hornick 1 Variables & Datatypes.
Copyright Curt Hill Variables What are they? Why do we need them?
Java Language Basics By Keywords Keywords of Java are given below – abstract continue for new switch assert *** default goto * package.
Programming in Java (COP 2250) Lecture 4 Chengyong Yang Fall, 2005.
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
0 Chap.2. Types, Operators, and Expressions 2.1Variable Names 2.2Data Types and Sizes 2.3Constants 2.4Declarations 2.5Arithmetic Operators 2.6Relational.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
Java Basics. Tokens: 1.Keywords int test12 = 10, i; int TEst12 = 20; Int keyword is used to declare integer variables All Key words are lower case java.
Programming – Lecture 3 Expressions (Chapter 3) Primitive types Aside: Context Free Grammars Constants, variables Identifiers Variable declarations Arithmetic.
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.
Chapter 4 Assignment Statement
University of Central Florida COP 3330 Object Oriented Programming
Lecture 2: Data Types, Variables, Operators, and Expressions
University of Central Florida COP 3330 Object Oriented Programming
CS180 – Week 1 Lecture 3: Foundation Ismail abumuhfouz.
Multiple variables can be created in one declaration
Variables and Arithmetic Operators in JavaScript
Chapter 3 Assignment Statement
Java Programming: From Problem Analysis to Program Design, 4e
Starting JavaProgramming
null, true, and false are also reserved.
Introduction to Java Programming
Chapter 2: Basic Elements of Java
Expressions Java 3.1 Primitive data types 3.2 Constants and variables
Chap 2. Identifiers, Keywords, and Types
Module 2 Variables, Data Types and Arithmetic
ENERGY 211 / CME 211 Lecture 5 October 1, 2008.
Presentation transcript:

4 Copyright © 2005, Oracle. All rights reserved. Exploring Primitive Data Types and Operators

4-2 Copyright © 2005, Oracle. All rights reserved. Objectives After completing this lesson, you should be able to do the following: Distinguish between reserved words and other names in Java Describe Java primitive data types and variables Declare and initialize primitive variables Use operators to manipulate primitive variables Describe uses of literals and Java operators Identify valid operator categories and operator precedence Use String object literals and the concatenation operator

4-3 Copyright © 2005, Oracle. All rights reserved. Notes Page

4-4 Copyright © 2005, Oracle. All rights reserved. Reserved Keywords abstract final native private protected public static synchronized transient volatile strictfp break case catch continue default do else finally for if return switch throw try while boolean byte char double float int long short void true false null class extends implements interface throws instanceof new super this import package

4-5 Copyright © 2005, Oracle. All rights reserved. Variable Types Eight primitive data types: –Six numeric types –A character type –A Boolean type (for truth values) User-defined types: –Classes –Interfaces –Arrays a b c

4-6 Copyright © 2005, Oracle. All rights reserved. Notes Page

4-7 Copyright © 2005, Oracle. All rights reserved. Primitive Data Types Append uppercase or lowercase L or F to the number to specify a long or a float number. Integer Floating Point Character True False byte short int long float double charboolean 1, 2, 3, xff 0 3.0F.3337F 4.022E23 0.0f 'a' '\141' '\u0061' '\n' \u0000 true false

4-8 Copyright © 2005, Oracle. All rights reserved. Notes Page

4-9 Copyright © 2005, Oracle. All rights reserved. What Are Variables? A variable is a basic unit of storage. Variables must be explicitly declared. Each variable has a type, an identifier, and a scope. There are three types of variables: class, instance, and method. int myAge; boolean isAMovie; float maxItemCost = 17.98F; Type Identifier Initial value Title: Blue Moon

4-10 Copyright © 2005, Oracle. All rights reserved. Declaring Variables Basic form of variable declaration: – type identifier [ = value]; Variables can be initialized when declared. public static void main(String[] args) { int itemsRented = 1; float itemCost; int i, j, k; double interestRate; }

4-11 Copyright © 2005, Oracle. All rights reserved. Local Variables Local variables are defined only within a method or code block. They must be initialized before their contents are read or referenced. class Rental { private int instVar; // instance variable public void addItem() { float itemCost = 3.50F; // local variable int numOfDays = 3; // local variable }

4-12 Copyright © 2005, Oracle. All rights reserved. Defining Variable Names Variable names must start with a letter of the alphabet, an underscore, or a $ symbol. Other characters may include digits. Use meaningful names for variables, such as customerFirstName and ageNextBirthday. aitem_Cost itemCost_itemCost item$CostitemCost2 item#Cost item-Cost item*Cost abstract 2itemCost

4-13 Copyright © 2005, Oracle. All rights reserved. What Are Numeric Literals? (decimal) (octal) 0x0 0x2a 0X1FF(hex) 365L 077L 0x1000L (long) e E-9 6.2f 6.21F Integer literals Floating-point literals Six types: byte, short, int, long, float, double

4-14 Copyright © 2005, Oracle. All rights reserved. Notes Page

4-15 Copyright © 2005, Oracle. All rights reserved. What Are Nonnumeric Literals? true false 'a' '\n' '\t' '\077' '\u006F' "Hello, world\n" Boolean literals String literals Character literals

4-16 Copyright © 2005, Oracle. All rights reserved. Notes Page

4-17 Copyright © 2005, Oracle. All rights reserved. Guided Practice: Declaring Variables Find the mistakes in this code and fix them: byte sizeof = 200; short mom = 43; short hello mom; int big = sizeof * sizeof * sizeof; long bigger = big + big + big // ouch double old = 78.0; double new = 0.1; boolean consequence = true; boolean max = big > bigger; char maine = "New England state"; char ming = 'd';

4-18 Copyright © 2005, Oracle. All rights reserved. Notes Page

4-19 Copyright © 2005, Oracle. All rights reserved. What Are Operators? Operators manipulate data and objects. Operators take one or more arguments and produce a value. There are 44 different operators. Some operators change the value of the operand.

4-20 Copyright © 2005, Oracle. All rights reserved. Categorizing Operators There are five types of operators: Assignment Arithmetic Integer bitwise Relational Boolean

4-21 Copyright © 2005, Oracle. All rights reserved. Using the Assignment Operator The result of an assignment operation is a value and can be used whenever an expression is permitted. The value on the right is assigned to the identifier on the left: The expression on the right is always evaluated before the assignment. Assignments can be strung together: int var1 = 0, var2 = 0; var1 = 50; // var1 now equals 50 var2 = var1 + 10; // var2 now equals 60 var1 = var2 = var3 = 50;

4-22 Copyright © 2005, Oracle. All rights reserved. Working with Arithmetic Operators Perform basic arithmetic operations. Work on numeric variables and literals. int a, b, c, d, e; a = 2 + 2; // addition b = a * 3; // multiplication c = b - 2; // subtraction d = b / 2; // division e = b % 2; // returns the remainder of division

4-23 Copyright © 2005, Oracle. All rights reserved. More on Arithmetic Operators Most operations result in int or long : byte, char, and short values are promoted to int before the operation. If either argument is of the long type, then the other is also promoted to long, and the result is of the long type. byte b1 = 1, b2 = 2, b3; b3 = b1 + b2; // ERROR: result is an int // b3 is byte

4-24 Copyright © 2005, Oracle. All rights reserved. Examining Conversions and Casts Java automatically converts a value of one numeric type to a larger type. Java does not automatically downcast. byte short char int long bytelongint short char

4-25 Copyright © 2005, Oracle. All rights reserved. Notes Page

4-26 Copyright © 2005, Oracle. All rights reserved. Incrementing and Decrementing Values The ++ and -- operators increment and decrement by 1, respectively: The ++ and -- operators can be used in two ways: int var1 = 3; var1++; // var1 now equals 4 int var1 = 3, var2 = 0; var2 = ++var1; // Prefix: Increment var1 first, // then assign to var2. var2 = var1++; // Postfix: Assign to var2 first, // then increment var1.

4-27 Copyright © 2005, Oracle. All rights reserved. greater than greater than or equal to less than less than or equal to equal to not equal to > >= < <= == != Relational and Equality Operators int var1 = 7, var2 = 13; boolean res = true; res = (var1 == var2); // res now equals false res = (var2 > var1); // res now equals true

4-28 Copyright © 2005, Oracle. All rights reserved. Using the Conditional Operator ( ?: ) Useful alternative to if…else : If boolean_expr is true, the result is expr1 ; otherwise, the result is expr2 : boolean_expr ? expr1 : expr2 int val1 = 120, val2 = 0; int highest; highest = (val1 > val2) ? val1 : val2; System.out.println("Highest value is " + highest);

4-29 Copyright © 2005, Oracle. All rights reserved. Using Logical Operators Results of Boolean expressions can be combined by using logical operators: and (with or without short-circuit evaluation) or (with or without short-circuit evaluation) exclusive or not && & || | ^ ! int var0 = 0, var1 = 1, var2 = 2; boolean res = true; highest = (val1 > val2)? val1 : val2; res = !res;

4-30 Copyright © 2005, Oracle. All rights reserved. Compound Assignment Operators An assignment operator can be combined with any conventional binary operator: double total=0, num = 1; double percentage =.50; … total = total + num;// total is now 1 total += num;// total is now 2 total -= num;// total is now 1 total *= percentage;// total is now.5 total /= 2; // total is now 0.25 num %= percentage; // num is now 0

4-31 Copyright © 2005, Oracle. All rights reserved. Operator Precedence Operators ~ ! (type) * / % > >>> = instanceof == != & ^ | && || ?: = op= Comments Unary operators Multiply, divide, remainder Add, subtract, add string Shift ( >>> is zero-fill shift) Relational, type compare Equality Bit/logical AND Bit/logical exclusive OR Bit/logical inclusive OR Logical AND Logical OR Conditional operator Assignment operators Order Assoc. R L L L L L L L L R R

4-32 Copyright © 2005, Oracle. All rights reserved. More on Operator Precedence Operator precedence determines the order in which operators are executed: Operators with the same precedence are executed from left to right (see note in text below): Use parentheses to override the default order. int var1 = 0; var1 = * 4; // var1 now equals 14 int var1 = 0; var1 = ; // var1 now equals 9

4-33 Copyright © 2005, Oracle. All rights reserved. Concatenating Strings The + operator creates and concatenates strings: String name = "Jane "; String lastName = "Hathaway"; String fullName; name = name + lastName; // name is now //"Jane Hathaway" // OR name += lastName;// same result fullName = name;

4-34 Copyright © 2005, Oracle. All rights reserved. Summary In this lesson, you should have learned the following: Java has eight primitive data types. A variable must be declared before it can be used. Java provides a comprehensive set of operators. Explicit casting may be necessary if you use data types smaller than int. The + and += operators can be used to create and concatenate strings.

4-35 Copyright © 2005, Oracle. All rights reserved. Practice 4: Overview This practice covers: Declaring and initializing variables Using various operators to compute new values Displaying results on the console

4-36 Copyright © 2005, Oracle. All rights reserved. Notes Page for Practice 4

4-37 Copyright © 2005, Oracle. All rights reserved. Practice 4: Notes

4-38 Copyright © 2005, Oracle. All rights reserved.