Integer numerical data types. The integer data types (multiple !) The integer data types use the binary number system as encoding method There are a number.

Slides:



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

1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
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.
A Review. a review of lessons learned so far… ( 2 steps forward - 1 step back) Software Development Cycle: design, implement, test, debug, document Large.
Numeric literals and named constants. Numeric literals Numeric literal: Example: A numeric literal is a constant value that appears in a Java program.
Introduction to Computers and Programming Lecture 4: Mathematical Operators New York University.
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Expressions and Operators Program Style.
1 Data types, operations, and expressions Overview l Format of a Java Application l Primitive Data Types l Variable Declaration l Arithmetic Operations.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
1 Chapter 2: Elementary Programming Shahriar Hossain.
Hello, world! Dissect HelloWorld.java Compile it Run it.
The switch statement: an N-way selection statement.
Writing algorithms using the while-statement. Previously discussed Syntax of while-statement:
Writing algorithms using the for-statement. Programming example 1: find all divisors of a number We have seen a program using a while-statement to solve.
Programming a computer. What does programming a computer mean ? Programming a computer: Since a computer can only execute machine instructions (encoded.
The break and continue statements. Introduction There are 2 special statements that can affect the execution of loop statements (such as a while-statement)
Using Java's Math & Scanner class. Java's Mathematical functions (methods) (1)
Week 2 - Friday.  What did we talk about last time?  Data representation  Binary numbers  Types  int  boolean  double  char  String.
Shorthand operators.
© The McGraw-Hill Companies, 2006 Chapter 1 The first step.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 2 Elementary Programming.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 2 Elementary Programming.
Floating point variables of different lengths. Trade-off: accuracy vs. memory space Recall that the computer can combine adjacent bytes in the RAM memory.
Copyright © 2003 Pearson Education, Inc. Slide 2-1 Problem Solving with Java™ Second Edition Elliot Koffman and Ursula Wolz Copyright © 2003 Pearson Education,
The character data type char
 Value, Variable and Data Type  Type Conversion  Arithmetic Expression Evaluation  Scope of variable.
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA 1 CST 221 OBJECT ORIENTED PROGRAMMING(OOP) ( 2 CREDITS.
The string data type String. String (in general) A string is a sequence of characters enclosed between the double quotes "..." Example: Each character.
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?
The dangling-else ambiguity. Previously discussed The Java compiler (translator) consider white space characters (i.e., SPACE, TAB and New line) as insignificant.
Summary of what we learned yesterday Basics of C++ Format of a program Syntax of literals, keywords, symbols, variables Simple data types and arithmetic.
Floating point numerical information. Previously discussed Recall that: A byte is a memory cell consisting of 8 switches and can store a binary number.
The scope of local variables. Murphy's Law The famous Murphy's Law says: Anything that can possibly go wrong, does. (Wikipedia page on Murphy's Law:
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Variables, Arithmetic, etc.)
Boolean expressions, part 2: Logical operators. Previously discussed Recall that there are 2 types of operators that return a boolean result (true or.
Integer numerical data types. The integer data types The integer data types use the binary number system as encoding method There are a number of different.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
Working with arrays (we will use an array of double as example)
Introduction to programming in the Java programming language.
Assignment statements using the same variable in LHS and RHS.
Mixing integer and floating point numbers in an arithmetic operation.
Introduction to Methods. Previously discussed There are similarities in make up of that can help you remember the construct of a class a class in the.
Using the while-statement to process data files. General procedure to access a data file General procedure in computer programming to read data from a.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
COMP Primitive and Class Types Yi Hong May 14, 2015.
The assignment expressions. The assignment operator in an assignment statement We have seen the assignment statement: Effect: var = expr; Stores the value.
Arithmetic expressions containing Mathematical functions.
Reading input from the console input. Java's console input The console is the terminal window that is running the Java program I.e., that's the terminal.
Introduction to array: why use arrays ?. Motivational example Problem: Write a program that reads in and stores away 5 double numbers After reading in.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Working with floating point expressions. Arithmetic expressions Using the arithmetic operators: and brackets (... ), we can construct arithmetic expression.
Boolean expressions, part 1: Compare operators. Compare operators Compare operators compare 2 numerical values and return a Boolean (logical) value A.
Simple algorithms on an array - compute sum and min.
The ++ and -- expressions. The ++ and -- operators You guessed it: The ++ and -- are operators that return a value.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
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.
The if-else statement. Introducing the if-else statement Programming problem: Re-write the a,b,c-formula program to solve for complex number solutions.
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.
CompSci 230 S Programming Techniques
Lecture 3 Java Operators.
Chapter 2 Elementary Programming
Multiple variables can be created in one declaration
Assignment and Arithmetic expressions
Type Conversion, Constants, and the String Object
Java Programming: From Problem Analysis to Program Design, 4e
Expressions and Assignment
CS2011 Introduction to Programming I Elementary Programming
Primitive Types and Expressions
Presentation transcript:

Integer numerical data types

The integer data types (multiple !) The integer data types use the binary number system as encoding method There are a number of different integer types in Java The difference between the various integer types is in the size I.e., the number of bytes used in the encoding

The integer data types (multiple !) (cont.) Warning: Java considers an integer data type of different sizes as different data types !!! (We saw this also when we discussed the float and double)

The integer data types (multiple !) (cont.) The integer data types have very similar properties and operations as the floating point data types (float and double I will only highlight the differences I will be brief on properties and operations that are similar

The various integer types in Java Integer types in Java: Type name (keyword) Number of bytes Range of values byte1− short2− int4−2,147,483, ,147,483,647 long8 −9,223,372,036,8 54,775, ,223,372,036,854, 775,807

The various integer types in Java (cont.) Note: There is a strict hierarchy among the integer types: The byte type is the least accurate integer type The short type is the more accurate than the byte type The int type is the more accurate than the short type (and the byte type) The long type is the more accurate than the int type (and short and byte)

The various integer types in Java (cont.) Safe conversions: Unsafe conversions: byte ⇒ short ⇒ int ⇒ long long ⇒ int ⇒ short ⇒ byte

The various integer types in Java (cont.) Remember that in an arithmetic expression involving different types of values, Java will automatically convert a lower accuracy typed value to the higher accuracy type In other words: auto convert to byte value + short value > short value + short value byte value + int value > int value + int value... short value + int value > int value + int value

Behind the scene of a safe and an unsafe conversions Example of a safe conversion: public class Safe { public static void main(String[] args) { int x; short y; y = 1; x = y; // Safe conversion System.out.println(x); }

Behind the scene of a safe and an unsafe conversions (cont.) What happens inside the computer (behind the scene): The variable y is of the type short and has 16 bits It is assigned the value 1: (The bit pattern encodes the number 1 in using 16 bits)

Behind the scene of a safe and an unsafe conversions (cont.) The statement x = y; will achieve the following: This statement copies the value from a short typed variable into an more accurate (wider) int typed variable. You cannot loose accuracy !!!

Behind the scene of a safe and an unsafe conversions (cont.) Example of an unsafe conversion: public class UnSafe { public static void main(String[] args) { int x; // x uses 4 bytes short y; // y uses 2 bytes x = 65538; // = 2^ // Binary: y = (short) x; // Unsafe conversion // y = (lower half of x) // (Correct only for numbers < 65535) System.out.println(y); //***** Prints 2 !!! // Because is equal to 2 }

Behind the scene of a safe and an unsafe conversions (cont.) What happens inside the computer (behind the scene): The variable x is of the type int and has 32 bits It is assigned the value 65538: (The bit pattern encodes the number in using 32 bits)

Behind the scene of a safe and an unsafe conversions (cont.) The statement y = (short) x; will achieve the following:

Behind the scene of a safe and an unsafe conversions (cont.) This statement copies the last 16 bits from a int typed variable into an less accurate (narrower) 16 bits short typed variable. You have lost the upper 16 bits bits from the int type variable !!! The conversion will result in incorrect value for large values (values > 65535)

Behind the scene of a safe and an unsafe conversions (cont.) Example Program: (Demo above code) –Prog file: UnSafe.java How to run the program: Right click on link and save in a scratch directory To compile: javac UnSafe.java To run: java UnSafe

Reading integer input from the keyboard The steps to read in an integer value from the keyboard is the same as those described for floating point values The only differences are: You need to define an int typed variable to receive the input (because we are reading in an integer number) You need to use the nextInt() method which will read in an integer value

Reading integer input from the keyboard (cont.) Summary of the steps to read in an integer value: We will look at an example a little bit later.

Integer operators Integer operators are arithmetic operators that manipulate (operate on) integer values A integer operator only operates on integer values The result of an integer operator is always an integer value (And the result of an floating point operator is always a floating point value) Specifically: An integer operator cannot operate on floating point values (Nor can a floating point operator operate on integer values)

Integer operators (cont.) Most of the integer (arithmetic) operators should look familiar to you... (Except for the % operator)

Integer operators (cont.) Integer arithmetic operators: Operator symbol OperationNote +additionBinary operator, e.g.: = 13 −subtractionBinary operator, e.g.: 9 − 4 = 5 * multiplication Binary operator, e.g.: 9 * 4 = 36 / division (= quotient)Binary operator, e.g.: 9 / 4 = 2 %modulus (= remainder)Binary operator, e.g.: 9 % 4 = 1 (... )bracketsChanges order of computation −negationChanges the sign of the value: − 4 = (−4) (Read as: − 4 = negative 4)

Quotient and remainder From elementary school:

Quotient and remainder (cont.) The / operator (quotient) will always produce an integer result It does so by truncating the floating point division Examples: 9 / 4 = (floating point result = 2.25) = 2 -9 / 4 = (floating point result = -2.25) = -2 9 / -4 = (floating point result = -2.25) = / -4 = (floating point result = 2.25) = 2

Quotient and remainder (cont.) The % operator (remainder) will also produce an integer result The sign of the result is always equal to the sign of the dividend Examples: 9 % 4 = (floating point result = 2.25) = 1 -9 % 4 = (floating point result = -2.25) = -1 9 % -4 = (floating point result = -2.25) = 1 -9 % -4 = (floating point result = 2.25) = -1

Quotient and remainder (cont.) Property of integer division: Example: dividend = quotient × divisor + remainder 9 / 4 = 2 9 % 4 = 1 9 = 2 * / 4 = % 4 = = (-2)* 4 + (-1) 9 / -4 = -2 9 % -4 = 1 9 = (-2)*(-4) / -4 = 2 -9 % -4 = = 2 *(-4) + (-1)

How to tell if "+", "-", "*" and "/" is a floating point or an integer operation You must have noticed that the "+", "-", "*" and "/" can represent: a floating point operation, or an integer operation

How to tell if "+", "-", "*" and "/" is a floating point or an integer operation (cont.) Special emphasis: The Java compiler (and you also) can tell the difference between integer division and floating point division by the operands used. Example 1: 9 / 5 (Operands are 2 integers => / is integer division) 9.0 / 5.0 (Operands are 2 floating point numbers => / floating point division)

How to tell if "+", "-", "*" and "/" is a floating point or an integer operation (cont.) Example 2: int a, b; double x, y; a / b (Operands are 2 integers ⇒ / is integer division) x / y (Operands are 2 floating point numbers ⇒ / floating point division)

How to tell if "+", "-", "*" and "/" is a floating point or an integer operation (cont.) The computer does not have any instructions that operates on operands of different types. Example: this operations cannot be performed directly: One of the operands must be converted into the other type before the operation can be performed. We focus on integer-only operations in this webnote. We will delay this discussion of mixed types operations for the next webnote. 9 / 5.0 (2 types of operands: integer and floating point)

Priority and associativity of the integer arithmetic operators Each arithmetic operator in Java has a priority and an associativity Operator priority was discussed in: s/04/float-expr.html#priority Operator associativity was discussed in: s/04/float-expr.html#associativity

Priority and associativity of the integer arithmetic operators (cont.) Priority of the integer arithmetic operators: Operator PriorityNote (.... )Highest − (negation)Higher Unary operator, e.g.: −3 * / %High Binary operator, e.g.: 4 * 5 + −Lowest Binary operator, e.g.: 4 + 5

Priority and associativity of the integer arithmetic operators (cont.) Example 1: (This is how you compute the sum of the digits in the number 72 !!!) Integer expression: 72 / % 10 Evaluated as follows: 72 / % 10 = % 10 = = 9

Priority and associativity of the integer arithmetic operators (cont.) Example 2: using the negation operator Integer expression: * Evaluated as follows: * = 22 - (-3) * = 22 - (-3) * (-4) = 22 - (-3) * (-4) + - (-1) = 22 - (-3) * (-4) + (+1) = (Use associativity rule) = = 11

Priority and associativity of the integer arithmetic operators (cont.) Example 3: using brackets Integer expression: ( ) * - ( ) Evaluated as follows: ( ) * - ( ) = (22 - (-3)) * - ( ) = (22 - (-3)) * - (4 + - (-1)) = (22 - (-3)) * - (4 + 1) = 25 * - (4 + 1) = 25 * - 5 = 25 * (-5) = -125

Priority and associativity of the integer arithmetic operators (cont.) Example Program: (Demo above code) –Prog file: Priority02.java How to run the program: Right click on link and save in a scratch directory To compile: javac Priority02.java To run: java Priority02

Example using integers: convert seconds to (hours, minutes, seconds) Problem description: Given n seconds Example: Compute the number of hours, number of minutes and number of seconds in n seconds n = seconds = 4*(60*60) + 17*(60) + 12 = 4 hours + 17 minutes + 12 seconds

Example using integers: convert seconds to (hours, minutes, seconds) (cont.) Advice on developing algorithms: Use a concrete example to discover the steps that need to be performed to solve the problem. Determine the steps that you must do to complete the task (solve the problem) Write down the steps in "psuedo code" (see below) Verify that the algorithm in pseudo code is correct. After you have Verify that the algorithm in pseudo code is correct, You can verify an algorithm by running the algorithm by hand with a small example

Example using integers: convert seconds to (hours, minutes, seconds) (cont.) Pseudo code: Pseudo code is a compact and informal high-level description of an algorithm Pseudo code uses the structural conventions of a programming language, but is intended for human reading (rather than machine reading). Pseudo code omits details that are not essential for human understanding of the algorithm, such as variable declarations In other words: Pseudo code are commands that are easy for humans to follow (no complex descriptions) Pseudo code are not Java statements !!

Example using integers: convert seconds to (hours, minutes, seconds) (cont.) Pseudo code is made up by yourself There is no "standard pseudo code" Requirement for pseudo code: An algorithm in pseudo code must be easily translated into any programming language

Example using integers: convert seconds to (hours, minutes, seconds) (cont.) Purpose: rapid prototyping algorithms An algorithm written in pseudo code is very easy to change You can correct errors easily in an algorithm written in pseudo code (Trust me, correcting errors in a large computer program is a pain - talk to someone in Microsoft....)

Example using integers: convert seconds to (hours, minutes, seconds) (cont.) Use a concrete example to determine the steps used to find (hours, minutes, seconds): Let n = seconds 1. We can find the # seconds as follows: / So: seconds = 257 minutes + 12 seconds Or: seconds = 15432/60 minutes /60 seconds 2. Next we convert the remaining 257 minutes into hours: / Therefore: 257 minutes = 257/60 hours + 257%60 minutes

Example using integers: convert seconds to (hours, minutes, seconds) (cont.) Pseudo code: input n; // n = total number of seconds seconds = n % 60; // computes seconds n = n / 60; // n is now = remaining minutes minutes = n % 60; // computes minutes n = n / 60; // n is now = remaining hours hours = n;

Example using integers: convert seconds to (hours, minutes, seconds) (cont.) Verify the algorithm (in pseudo code): (use a small example, e.g. n = 15432) n = 15432; hours = / 3600 = 4 r = % 3600 = 1032 minutes = 1032 / 60 = 17 seconds = 1032 % 60 = 12

Example using integers: convert seconds to (hours, minutes, seconds) (cont.) Write the algorithm in Java (translate from pseudo code): import java.util.Scanner; public class Hours { public static void main(String[] args) { int n, r, hours, minutes, seconds; Scanner in = new Scanner(System.in); System.out.print("Enter # seconds: "); n = in.nextInt(); // in.nextInt() reads in an integer value seconds = n % 60; // computes seconds n = n / 60; // n is now = remaining minutes minutes = n % 60; // computes minutes n = n / 60; // n is now = remaining hours hours = n;

Example using integers: convert seconds to (hours, minutes, seconds) (cont.) System.out.print(n); System.out.print(" seconds = "); System.out.print(hours); System.out.print(" hours + "); System.out.print(minutes); System.out.print(" minutes+ "); System.out.print(seconds); System.out.println(" seconds."); }

Example using integers: convert seconds to (hours, minutes, seconds) (cont.) Example Program: (Demo above code) –Prog file: Hours.java How to run the program: Right click on link and save in a scratch directory To compile: javac Hours.java To run: java Hours

Programming example: tell the time of the day Preliminary: The method System.currentTimeMillis() will return the following value: System.currentTimeMillis() returns the number of milli seconds (1/1000 second) since midnight, Jan in GMT

Programming example: tell the time of the day (cont.) Problem description: Find the current time HH:MM:SS GMT

Programming example: tell the time of the day (cont.) Use a concrete example to determine the steps used to find (hours, minutes, seconds): Let n = millisec 1. Find total number of seconds since midnight, Jan : n = n / 1000 = / 1000 = (total # seconds) 2. Find seconds in current time: seconds = n % 60 = % 1000 = 40 *** part of answer n = n / 60 = / 60 = 1666 (total # minutes) 3. Find minutes in current time: minutes = n % 60 = 1666 / 60 = 46 *** part of answer n = n / 60 = 1666 % 60 = 27 (total # hours) 3. Find hours in current time: hours = n % 27 = 27 % 24 = 3 *** part of answer

Programming example: tell the time of the day (cont.) Algorithm in pseudo code: n = System.currentTimeMillis(); // n = total # milli sec n = n / 1000; // n is now = total # sec seconds = n % 60; // Compute seconds in current time n = n / 60; // n is now = total # minutes minutes = n % 60; // Compute minutes in current time n = n / 60; // n is now = total # hours hours = n % 60; // Compute hours in current time

Programming example: tell the time of the day (cont.) Java program: public class ShowCurrentTime { public static void main(String[] args) { long nMillis; // We need long for accuracy !!! long n, hours, minutes, seconds; nMillis = System.currentTimeMillis(); n = nMillis/1000; // Total # Second; seconds = n % 60; // Seconds n = n / 60; // Total # minutes; minutes = n % 60; // Minutes n = n / 60; // Total # hours; hours = n % 24; // Hours

Programming example: tell the time of the day (cont.) System.out.print(hours); System.out.print(":"); System.out.print(minutes); System.out.print(":"); System.out.print(seconds); System.out.println(" GMT"); }

Programming example: tell the time of the day (cont.) Example Program: (Demo above code) –Prog file: ShowCurrentTime.java How to run the program: Right click on link and save in a scratch directory To compile: javac ShowCurrentTime.java To run: java ShowCurrentTime

Automatic conversion to int in arithmetic operations It is extremely inconvenient for programmers to have to write conversion operations when values of different integer types are used in the same arithmetic expression Java makes writing programs less painful by providing a number of automatic integer conversions

Automatic conversion to int in arithmetic operations (cont.) Java's automatic integer conversion in arithmetic operations: Arithmetic operations on integer types: All values are converted to int type before an arithmetic operation (+, −, *, /, %) in performed. However, if one of the values in an arithmetic operation is long, then all values are converted to long type before the arithmetic operation in performed.

Automatic conversion to int in arithmetic operations (cont.) Example 1: short a = 2; int b = 3, c; c = a + b; // a (short) is first converted to an int value // Then the addition is performed.

Automatic conversion to int in arithmetic operations (cont.) Example 2: short a = 2, b = 2; int c; c = a + b; // a and b (short) is first converted to an int value // Then the addition is performed.

Automatic conversion to int in arithmetic operations (cont.) Example 3: int a = 2; long b = 3, c; c = a + b; // a (int) is first converted to an long value // Then the addition is performed.

Quiz: can you spot what is wrong with this program Java program with an error: Can you see why the statement c = a + b will cause a compilation error ? public class Caveat2 { public static void main(String[] args) { short a, b, c; a = 2; b = 3; c = a + b; // Compilation error ! }

Quiz: can you spot what is wrong with this program (cont.) Answer: Because all value are first converted to int, the RHS a + b will produce a result that is of the type int The receiving variable c has the type short A int typed value cannot be assigned to a short typed variable We must use a casting operator: c = (short) (a + b);

Quiz: can you spot what is wrong with this program (cont.) Note: This solution will not work: because the casting operator (short) has a higher priority than the + operation c = (short) a + b;

Automatic type conversion in the assignment operation The automatic safe conversion rule of the assignment operator = is also applicable to integer types Recall the safe integer conversions are: byte ⇒ short ⇒ int ⇒ long

Automatic type conversion in the assignment operation (cont.) These assignments are allowed: (because they are safe): long a; int b; short c; byte d; /* Automatic conversion happens in all the following assignments */ a = b; a = c; a = d; b = c; b = d; c = d;

Automatic type conversion in the assignment operation (cont.) You need casting operators to perform the following (unsafe) assignments: long a; int b; short c; byte d; /* Unsafe assignment requires casting */ b = (int) a; c = (short) a; c = (short) b; d = (byte) a; d = (byte) b; d = (byte) c;

Exercise What is the output of the following program public class Exercise1 { public static void main(String[] args) { int a = 15; int b = 24; System.out.println(b - a + 7); System.out.println(b - a - 4); System.out.println(b % a / 2); System.out.println(b % (a / 2)); System.out.println(b * a / 2); System.out.println(b * (a / 2)); System.out.println(b / 2 * a); System.out.println(b / (2 * a)); }

Exercise (cont.) Answers:

Exercise (cont.) Example Program: (Demo above code) –Prog file: Exercise1.java How to run the program: Right click on link and save in a scratch directory To compile: javac Exercise1.java To run: java Exercise1

Programming trick: divisibility of numbers Fact: If a number x is divisible by the number d, then the remainder of the division of x by d is equal to zero

Programming trick: divisibility of numbers Examples: Later in the course, we will use this property to find all divisors of a number. 12 is divisible by 2  12 % 2 = 0 12 is divisible by 3  12 % 3 = 0 12 is divisible by 4  12 % 4 = 0 12 is not divisible by 5  12 % 5 = 2 12 is divisible by 6  12 % 6 = 0 12 is not divisible by 7  12 % 7 = 5

Overflow Range of the integer types in Java: Type name (keyword) Number of bytes Range of values byte1− short2− int4−2,147,483, ,147,483,647 long8 −9,223,372,036,8 54,775, ,223,372,036,854, 775,807

Overflow (cont.) When an operation results in a value that is outside the range of a variable, then there is an overflow error

Overflow (cont.) Example: public class Overflow { public static void main(String[] args) { int x, y, z; long a, b, c; x = ; y = 3000; z = x * y; // 3,000,000,000 is outside the range of int System.out.println(z); a = ; b = 3000; c = a * b; // 3,000,000,000 is within the range of long System.out.println(c); }

Overflow (cont.) Output: Explanation: (not !!!) You need more than 32 bits to represent the value 3,000,000,000 in the binary number system We do not have sufficient number of bits in an int variable to represent the value 3,000,000,000

Overflow (cont.) Example Program: (Demo above code) –Prog file: Overflow.java How to run the program: Right click on link and save in a scratch directory To compile: javac Overflow.java To run: java Overflow

Overflow (cont.) What can you do about overflow ? You must know how large the values can be If you are not sure, then use the largest possible data type available.