Variables, Data Types, & Constants. Topics & Objectives Declaring Variables Assignment Statement Reserve Words Data Types Constants Packages & Libraries.

Slides:



Advertisements
Similar presentations
© 2007 Lawrenceville Press Slide 1 Assignment Statement An assignment statement gives a value to a variable. Assignment can take several forms: x = 5;
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.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 2 1 Chapter 2 Primitive.
Primitive Data Types There are a number of common objects we encounter and are treated specially by almost any programming language These are called basic.
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.
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.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
1 9/20/06CS150 Introduction to Computer Science 1 Review: Exam 1.
ECE122 L3: Expression Evaluation February 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 3 Expression Evaluation and Program Interaction.
Chapter 3 Numerical Data. Topics Variables Numeric data types Assignment Expressions.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
Chapter 2 Data Types, Declarations, and Displays
1 Identifiers  Identifiers are the words a programmer uses in a program  An identifier can be made up of letters, digits, the underscore character (
Variable Declaration  It is possible to declare multiple variables of the same data type on the same line.  Ex. double hours, rate, total;  Variables.
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.
Chapter 4 Variables and Constants. Goals and Objectives 1. Understand simple data types (int, boolean, double). 2. Declare and initialize variables using.
The Java Programming Language
Lecture 2 Object Oriented Programming Basics of Java Language MBY.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
C Derived Languages C is the base upon which many build C++ conventions also influence others *SmallTalk is where most OOP comes Java and Javascript have.
Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes.
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.
Java Programming: From Problem Analysis to Program Design, 5e 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.
Chapter 2 Variables.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 2A Reading, Processing and Displaying Data (Concepts)
© 2005 Lawrenceville Press Slide 1 Chapter 4 Assignment Statement An assignment statement gives a value to a variable. Assignment can take several forms:
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Tokens in C  Keywords  These are reserved words of the C language. For example int, float, if, else, for, while etc.  Identifiers  An Identifier is.
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.
Slide 1 Chapter 3 Variables  A variable is a name for a value stored in memory.  Variables are used in programs so that values can be represented with.
© 2006 Lawrenceville Press Slide 1 Chapter 4 Variables  A variable is a name for a value stored in memory.  Variables are created using a declaration.
Slide 1 Chapter 3 Variables  A variable is a name for a value stored in memory.  Variables are created using a declaration statement. For example: Dim.
M105 - Week 2 Chapter 3 Numerical Data 1 Prepared by: M105 Team - AOU - SAB.
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.
CompSci 230 S Programming Techniques
A variable is a name for a value stored in memory.
Chapter 2 Variables.
Chapter 2 Basic Computation
Chapter 4 Assignment Statement
Elementary Programming
BASIC ELEMENTS OF A COMPUTER PROGRAM
Lecture 2: Data Types, Variables, Operators, and Expressions
Multiple variables can be created in one declaration
Chapter 3 Assignment Statement
Java Programming: From Problem Analysis to Program Design, 4e
Chapter 2 Basic Computation
Starting JavaProgramming
null, true, and false are also reserved.
Introduction to Java Programming
Chapter 2: Basic Elements of Java
Chapter 2 Variables.
Fundamentals 2.
Expressions and Assignment
Primitive Types and Expressions
Chap 2. Identifiers, Keywords, and Types
Chapter 2 Variables.
Review of Java Fundamentals
Presentation transcript:

Variables, Data Types, & Constants

Topics & Objectives Declaring Variables Assignment Statement Reserve Words Data Types Constants Packages & Libraries Scanner Class Math Class Arithmetic Compound Assignment Flow Charting

Variable Is a name for a value stored in memory Containers for values Is a name for a location in memory used to hold a data value.

Variable Declaration Tells the compiler to reserve a portion of main memory space large enough to hold the value. All variables must be declared with a name and a type before they can be used. –int myValue = 3; //Declared & Initialized myValue to 3 Variable can only store one value of its type at a time.

Assignment Statement (=) symbol is used as the assignment statement. – (=) - is known as the assignment operator. All assignments occurs from right to left. Meaning the right side of the equal sign is evaluated first and then stored to the variable on the left side. –Identifier variable = expression ; –myVariable = myValue + 3; myValue + 3 is evaluated first The result is then stored in myVariable

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

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

Naming Variables 1 st letter of a variable name should be lowercase. Name should consist of letters and numbers and underscore. No spaces No symbols If using two words join together, the 1 st letter of the second word should be capitalized. –myHouse, totalSum Do not use reserve or keywords

Reserve Reserve Words – words that have a predefine meaning –boolean, char, byte, int, short, long, float, double, void, true, false, public, private, protected, static, final, import, class, interface, extends, implements, this, super, abstract, new, if, else, for, while, do, switch, case, default, break, return, try, catch, finally, throw, throws, continue, package, native, volatile, transient, synchronized, instanceof All reserved words use only lowercase letter

Java Keywords abstractdoubleintstrictfp booleanelseinterfacesuper breakextendslongswitch bytefinalnativesynchronized casefinallynewthis catchfloatpackagethrow charforprivatethrows classgotoprotectedtransient constifpublictry continueimplementsreturnvoid defaultimportshortvolatile doinstanceofstaticwhile

Primitive Data Types or built-in data types Data type – determines the type of data the variable will store They are called primitive because data types have no properties.

Eight Primitive Data Types 4 kinds of Integers data types 2 kinds of floating point data types 1 character data type 1 boolean data type

Primitive Data Types TypeStorage Required int 4 bytes //AP EXAM double 8 bytes //AP EXAM char 2 bytes //Not on AP Exam boolean 1 bit //AP EXAM

Integer Data Types Use for whole numbers byte – 1 byte range –2 7 to or –128 to 127 short – 2 bytes range –2 15 to 2 15 – 1 or 32,768 to 32,767 int – 4 bytes range –2 31 to long – 8 bytes range –2 63 to 2 63 – 1

Floating Points Data Types Use for real numbers (numbers with decimal). float – 4 bytes –3.4 x to 3.4 x double – 8 bytes –1.8 x to 1.8 x

Character Data Type Used for single letters in single quotes char – 2 bytes Unicode character set (with ASCII subset)

Boolean Data Type Used for true or false boolean – 1 byte true or false

Choosing a data type It is important to choose the most appropriate type for the quantity being represented.

Constants Literal – A primitive value used in a program. oNumeric literal – 8, 9, 427 oString literal – “hello” Symbolic - uses the keyword final when declaring variables –final int SUM = 8; –Use all caps the distinguish constant variables from other variables. Constants are like variables, but they have the same value throughout the program. Constant can’t change their value once they are assigned a value.

Named Constants  A named memory location that cannot be changed from its initial value.  The keyword final is used in a constant declaration.  Constant identifiers are typically all uppercase with an underscore ( _ ) separating words within the identifier name.  Example: final double TAX = 0.08;

Constants Advantages Prevent accidental changing during the program run by another source. Maintenance - by changing the assignment where it is assigned. It will change throughout the program.

ASCII American Standard Code for Information Interchange –Represents the numeric code for each character –One Byte per character –0 to 127 Extended ASCII –128 to 255

Unicode Two bytes per character –ASCII is a subset of Unicode Represents 65,000 characters for most world languages

Import, Arithmetic, Casting, Logical Operators, Relational Operators

Java Packages  Numerous packages are included with JDK  Packages contain classes  Packages can be added to an application with an import statement. For example, the statement import java.util.Scanner; makes the Scanner class and its methods accessible to the application.

Packages Group of related classes by one name. Eamples: java.lang – java.util

Class Libraries Class Library – is a set of classes that supports the development of programs. The Java standard class Library is a useful set of classes that anyone can use when writing Java programs. Java APIs – Application Programmer Interfaces. Class library made up of several sets of related classes.

Import Declaration import – keyword used to identify packages and classes that will be used by the program. import java.util.Random; –Gains access to the Random Class import java.util.*; –Gains access to the package that contains class Random

java.lang.*; Automatically imported Classes in java.lang package –String –System –Double –Integer –Comparable –Math –Object –Etc.

java.util.*; Random ArrayList HashMap HashSet Iterator LinkedList List ListIterator Map Set TreeMap TreeSet

Inputting

Scanner Class next() nextLine() nextInt() nextDouble() nextBoolean() nextFloat() nextLong() nextShort()

Creating a Scanner object Scanner console = new Scanner(System.in); console is the object of Scanner console has access to all the methods using the dot operator.

Scanner Class Methods next() –Returns a string nextLine() –Returns a string of the entire sentence nextInt() –Returns an integer nextInt() –Returns an integer nextDouble() –Returns a double value nextBoolean() –Returns a Boolean value nextFloat() –Returns a float value nextLong() –Returns a long value nextShort() –Returns a short value

Inputting Char No methods for inputting chars Scanner console = new console Scanner(System.in); char dude = console.next().charAt(0); //return the char at the 0 index

Program import java.util.*; public class Scan{ public static void main(String args[]){ int x=0,y=0, z=0; String temp = new String(); Scanner console = new Scanner(System.in); System.out.println("Input 3 values"); x = console.nextInt(); y=console.nextInt(); z=console.nextInt(); System.out.println(x); System.out.println(y); System.out.println(z); }

When inputting values, do not use the enter keys between the values.

The Math Class  Part of the java.lang package  The random() methods generates a double between 0 and 1.0. For example, double rNum; rNum = Math.random();  A random integer in a range is generated by using the expression: (highNum – lowNum + 1) * Math.random() + lowNum

Math Class abs(int) or abs(double) - absolute value acos(double) – arc cos asin(double) – arc sin atan(double) – arc tan cos(double) – cosine sin(double) - sine tan(double) - tangent ceil(double) – smallest whole number greater than or equal to num exp(double) - power floor(double) – largest whole number less than or equal to num. pow(double, double) – return num raised to a power random() – 0.0 to < 1.0 sqrt(double) – square root

Built-in arithmetic operators * - multiplication % - modulus division / - division + - addition - - subtraction

Modulus Division Modulus division ( % ) returns the remainder of a division operation:

Compound Assignment Operators OperatorOperation += addition and then assignment -= subtraction and then assignment *= multiplication and then assignment /= division and then assignment %= modulus division and then assignment

Order of Precedence !, (unary) -, Cast, ++, -- *, /, % +, -, =, ==, != && || In the absence of parentheses, binary operators of the same rank are performed left to right, and unary operators right to left. If in doubt use parentheses!

Parentheses Operations inside of parentheses are evaluated first. The order in which operators are evaluated can be changed by using parentheses. For example, addition is performed first, then multiplication, and finally division: Example: –6 + 4 * 2 – 1 // 13 –(6 + 4) * (2 – 1) // 10 –(5 + 6) * 4 / 2 // 22

Type promotion (implicit conversion) Occurs when using a math expression of different data types. Example: int + double will return a double and the int will be promoted to a double by the compiler automatically. You will need to have a double data type to store the result. If you try to store it in an int memory location, you will get a loss of precision error.

+, -, *, % Will return the data type of the operand if they of same data type. Mixed mode operands will use type promotion to determine the data type that will be return. Can’t % by a 0 –5 % 0; Can 0%8 = 0

Mixed Mode Operands int + int  int int + double  double double + double  double int * int  int int *double  double double * double  double int / int  int int / double  double double / double  double Just as long as one of the operand is a double, the other operand will be promoted up and result will be a double.

/ division Must be careful when working with division. int/int will return an int and the remainder is dropped. One or both of the sides of the division must be a double to return a double Can’t divide by 0 example 5/0; Can 0/5 = 0;

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

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

Division & Modulus Can use if statement to eliminate errors if(x != 0) 8 / x Eliminates any errors if x = 0;

Casting or Type Casting Converts a value Data Type temporary to another type. Examples: int x, i = 2; double d = 3.7; x = i * (int) d; // d is explicitly cast Type casting is necessary in this case because one of the operands has less precision than the variable that will store the result. Explicit casting also makes it clear that the programmer intended for the calculation result to be an int.

Type Casting 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

Casting real division Casting is useful when real division with integers is preferred result = (double) 8/ (double) 5; //explicitly result = (double) 8/ 5; // explicitly & implicitly Java will implicitly type cast operands in a mixed expression to match the precision of the variable storing the value. Although explicitly type casting is not necessary, it is better programming style to include casts. Casting makes the programmer’s intentions clear and makes bugs easier to find.

Truncate Casting a double to an int truncates the decimal portion of the number.

Rounding Rounding can be simulated when casting a double to an int by adding.5 to the number before the casting. x = i * (int)(d + 0.5);

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()

Programming Errors  Syntax errors violate the rules of Java.  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.

Flowchart Symbols process

The BirthdayGame Flowchart