SlideShare a Scribd company logo
Chapter 3 Numerical Data
Objectives After you have read and studied this chapter, you should be able to  Select proper types for numerical data. Write arithmetic expressions in Java. Evaluate arithmetic expressions using the precedence rules. Describe how the memory allocation works for objects and primitive data values. Write mathematical expressions, using methods in the Math class.  Use the GregorianCalendar class in manipulating date information such as year, month, and day. Use the DecimalFormat class to format numerical data Convert input string values to numerical data Perform input and output by using System.in and System.out
Manipulating Numbers In Java, to add two numbers x and y, we write x + y But before the actual addition of the two numbers takes place, we must declare their data type. If x and y are integers, we write int x, y; or int x; int y;
Variables When the declaration is made, memory space is allocated to store the values of x and y. x and y are called  variables . A variable has three properties: A memory location to store the value, The type of data stored in the memory location, and The name used to refer to the memory location.  Sample variable declarations: int x; int v, w, y;
Numerical Data Types There are six numerical data types:  byte ,  short ,  int ,  long ,  float , and  double . Sample variable declarations: int   i, j, k; float   numberOne, numberTwo; long  bigInteger; double  bigNumber; At the time a variable is declared, it also can be initialized. For example, we may initialize the integer variables count and height to 10 and 34 as int count = 10, height = 34;
Data Type Precisions The six data types differ in the precision of values they can store in memory.
Assignment Statements We assign a value to a variable using an  assignment statements . The syntax is   <variable> = <expression> ; Examples: sum = firstNumber + secondNumber; avg = (one + two + three) / 3.0;
Arithmetic Operators The following table summarizes the arithmetic operators available in Java. This is an integer division where the fractional part is truncated.
Arithmetic Expression How does the expression x + 3 * y get evaluated? Answer: x is added to 3*y. We determine the order of evaluation by following the  precedence rules .  A higher precedence operator is evaluated before the lower one. If two operators are the same precedence, then they are evaluated left to right for most operators.
Precedence Rules
Type Casting If  x  is a  float  and  y  is an  int , what will be the data type of the following expression?   x * y The answer is  float .  The above expression is called a  mixed expression .  The data types of the operands in mixed expressions are converted based on the  promotion rules . The promotion rules ensure that the data type of the expression will be the same as the data type of an operand whose type has the highest precision.
Explicit Type Casting Instead of relying on the promotion rules, we can make an explicit type cast by prefixing the operand with the data type using the following syntax: ( <data type> ) <expression> Example  (float) x / 3 (int) (x / y * 3.0) Type case  x  to  float  and then divide it by 3. Type cast the result of the expression  x / y * 3.0  to  int .
Implicit Type Casting Consider the following expression: double x = 3 + 5; The result of 3 + 5 is of type  int . However, since the variable  x  is  double , the value 8 (type  int ) is promoted to 8.0 (type  double ) before being assigned to  x . Notice that it is a promotion. Demotion is not allowed. int x = 3.5; A higher precision value cannot be assigned to a lower precision variable.
Constants We can change the value of a variable. If we want the value to remain the same, we use a  constant . final double PI  = 3.14159; final int  MONTH_IN_YEAR  = 12; final short  FARADAY_CONSTANT = 23060; These are constants, also called  named constant . The reserved word  final  is used to declare constants. These are called  literal constant.
Primitive vs. Reference Numerical data are called  primitive data types . Objects are called  reference data types , because the contents are addresses that refer to memory locations where the objects are actually stored.
Primitive Data Declaration and Assignments Code State of Memory int firstNumber, secondNumber; firstNumber  = 234; secondNumber = 87; A B firstNumber secondNumber A.  Variables are  allocated in memory. B.  Values are assigned  to variables. 234 87
Assigning Numerical Data Code State of Memory int number; number = 237; number A.  The variable  is allocated in  memory. B.  The value  237   is assigned to  number . 237 A B C number = 35; C.  The value  35   overwrites the previous value  237. 35
Assigning Objects Code State of Memory Customer customer; customer = new Customer( ); customer = new Customer( ); customer A.  The variable  is  allocated in memory. A B C B.  The reference to the  new object is assigned  to  customer . Customer C.  The reference to another object overwrites the reference in  customer. Customer
Having Two References to a Single Object Code State of Memory Customer clemens, twain, clemens = new Customer( ); twain  = clemens; A B C A.  Variables are  allocated in memory. clemens twain B.  The reference to the  new object is assigned  to  clemens . Customer C.  The reference in  clemens  is assigned to  customer.
Type Mismatch Suppose we want to input an age. Will this work? No.  String value cannot be assigned directly to an int variable. int   age; age = JOptionPane.showInputDialog( null , “Enter your age”);
Type Conversion Wrapper classes  are used to perform necessary type conversions, such as converting a String object to a numerical value. int   age; String  inputStr; inputStr = JOptionPane.showInputDialog( null , “Enter your age”); age = Integer.parseInt(inputStr);
Other Conversion Methods
Sample Code Fragment //code fragment to input radius and output //area and circumference double  radius, area, circumference; radiusStr = JOptionPane.showInputDialog( null ,  &quot;Enter radius: &quot;  ); radius = Double.parseDouble(radiusStr); //compute area and circumference area = PI * radius * radius; circumference = 2.0 * PI * radius; JOptionPane.showMessageDialog( null ,  &quot;Given Radius:  &quot;  + radius +  &quot;\n&quot;  +  &quot;Area:  &quot;  + area  +  &quot;\n&quot;  +  &quot;Circumference: &quot;  + circumference);
Overloaded Operator + The plus operator + can mean two different operations, depending on the context. <val1> + <val2>  is an addition if both are numbers. If either one of them is a String, the it is a concatenation. Evaluation goes from left to right. output = “test” + 1 + 2; output = 1 + 2 + “test”;
The DecimalFormat Class Use a  DecimalFormat  object to format the numerical output. double num = 123.45789345; DecimalFormat df = new DecimalFormat(“0.000”); //three decimal places System.out.print ( num ) ; System.out.print ( df.format ( num )) ; 123.45789345   123.458
3.5 Standard Output The  showMessageDialog  method is intended for displaying short one-line messages, not for a general-purpose output mechanism.  Using  System.out,  we can output multiple lines of text to the standard output window.
Standard Output Window A sample standard output window for displaying multiple lines of text.  The exact style of standard output window depends on the Java tool you use.
The print Method We use the  print  method to output a value to the standard output window. The  print  method will continue printing from the end of the currently displayed output. Example  System.out.print (  “Hello, Dr. Caffeine.”  );
The println Method We use  println  instead of  print  to skip a line. int  x = 123, y = x + x; System.out.println(  &quot;Hello, Dr. Caffeine.“  ); System.out.print(  &quot; x = “  ); System.out.println( x ); System.out.print(  &quot; x + x = “  ); System.out.println( y ); System.out.println(  &quot; THE END“  );
Standard Input The technique of using System.in to input data is called standard input. We can only input a single byte using System.in directly. To input primitive data values, we use the Scanner class (from Java 5.0).  Scanner scanner; scanner = Scanner.create(System.in); int num = scanner.nextInt();
Method Example nextByte( ) byte b = scanner.nextByte( ); nextDouble( ) double d = scanner.nextDouble( ); nextFloat( ) float f = scanner.nextFloat( ); nextInt( ) int i = scanner.nextInt( ); nextLong( ) long l = scanner.nextLong( ); nextShort( ) short s = scanner.nextShort( ); next()  String str = scanner.next(); Common Scanner Methods:
The Math class The  Math  class in the  java.lang  package contains class methods for commonly used mathematical functions. double   num, x, y; x = …; y = …; num = Math.sqrt(Math.max(x, y) + 12.4);
Some Math Class Methods Table 3.8 page 113 in the textbook contains a list of class methods defined in the  Math  class. The sine of  a . (Note: all trigonometric functions are computed in radians) sin(a) The square root of  a . sqrt(a) The larger of a and b. max(a,b) Natural logarithm (base  e ) of  a . log(a) The number  a  raised to the power of  b . pow(a,b) Natural number  e  raised to the power of  a . exp(a) The largest whole number less than or equal to  a . floor(a) Description Method
Computing the Height of a Pole alphaRad = Math.toRadians ( alpha ) ; betaRad  = Math.toRadians ( beta ) ; height =  (  distance * Math.sin ( alphaRad )  * Math.sin ( betaRad ) ) / Math.sqrt (  Math.sin ( alphaRad + betaRad )  * Math.sin ( alphaRad - betaRad ) ) ;
The GregorianCalendar Class Use a  GregorianCalendar  object to manipulate calendar information GregorianCalendar today, independenceDay; today  =  new  GregorianCalendar () ; independenceDay  =  new  GregorianCalendar ( 1776, 6, 4 ) ; //month 6 means July; 0 means January
Retrieving Calendar Information This table shows the class constants for retrieving different pieces of calendar information from  Date .
Sample Calendar Retrieval GregorianCalendar cal =  new  GregorianCalendar () ; //Assume today is Nov 9, 2003 System.out.print(“Today is ” + (cal.get(Calendar.MONTH)+1) + “/” + cal.get(Calendar.DATE) + “/” + cal.get(Calendar.YEAR)); Today is 11/9/2003 Output
Problem Statement Problem statement: Write a loan calculator program that computes both monthly and total payments for a given loan amount, annual interest rate, and loan period.
Overall Plan Tasks: Get three input values:  loanAmount ,  interestRate , and  loanPeriod . Compute the monthly and total payments. Output the results.
Required Classes
Development Steps We will develop this program in four steps: Start with code to accept three input values. Add code to output the results. Add code to compute the monthly and total payments. Update or modify code and tie up any loose ends.
Step 1 Design Call the  showInputDialog  method to accept three input values:  loan amount,  annual interest rate,  loan period. Data types are int in years loan period double in percent (e.g.,12.5) annual interest rate double dollars and cents loan amount Data Type Format Input
Step 1 Code Directory:   Chapter3/Step1 Source File:  Ch3LoanCalculator.java Program source file is too big to list here. From now on, we ask you to view the source files using your Java IDE.
Step 1 Test In the testing phase, we run the program multiple times and verify that we can enter three input values we see the entered values echo-printed correctly on the standard output window
Step 2 Design We will consider the display format for out. Two possibilities are (among many others)
Step 2 Code Directory:   Chapter3/Step2 Source File:  Ch3LoanCalculator.java
Step 2 Test We run the program numerous times with different types of input values and check the output display format. Adjust the formatting as appropriate
Step 3 Design The formula to compute the geometric progression is the one we can use to compute the monthly payment. The formula requires the loan period in months and interest rate as monthly interest rate. So we must convert the annual interest rate (input value) to a monthly interest rate (per the formula), and the loan period to the number of monthly payments.
Step 3 Code Directory:   Chapter3/Step3 Source File:  Ch3LoanCalculator.java
Step 3 Test We run the program numerous times with different types of input values and check the results.
Step 4: Finalize We will add a program description We will format the monthly and total payments to two decimal places using DecimalFormat. Directory:   Chapter3/Step4 Source File:  Ch3LoanCalculator.java

More Related Content

What's hot (20)

PDF
The Basics of MATLAB
Muhammad Alli
 
PDF
Data mining assignment 4
BarryK88
 
PDF
Introduction to Arrays in C
Thesis Scientist Private Limited
 
PPT
Array
PRN USM
 
DOCX
Visual basic bt0082
Divyam Pateriya
 
PPTX
Variables and calculations_chpt_4
cmontanez
 
PDF
Data mining assignment 5
BarryK88
 
PPTX
Probability Assignment Help
Statistics Assignment Help
 
PPTX
Arrays 1D and 2D , and multi dimensional
Appili Vamsi Krishna
 
PPT
Savitch Ch 02
Terry Yoast
 
PDF
4 linear regeression with multiple variables
TanmayVijay1
 
PPTX
Arrays & Strings
Munazza-Mah-Jabeen
 
PPTX
R교육1
Kangwook Lee
 
PPTX
Operators , Functions and Options in VB.NET
Shyam Sir
 
PDF
design and analysis of algorithm
Muhammad Arish
 
PDF
01 Notes Introduction Analysis of Algorithms Notes
Andres Mendez-Vazquez
 
PPTX
Machnical Engineering Assignment Help
Matlab Assignment Experts
 
PPTX
Arrays C#
Raghuveer Guthikonda
 
PDF
02 Notes Divide and Conquer
Andres Mendez-Vazquez
 
The Basics of MATLAB
Muhammad Alli
 
Data mining assignment 4
BarryK88
 
Introduction to Arrays in C
Thesis Scientist Private Limited
 
Array
PRN USM
 
Visual basic bt0082
Divyam Pateriya
 
Variables and calculations_chpt_4
cmontanez
 
Data mining assignment 5
BarryK88
 
Probability Assignment Help
Statistics Assignment Help
 
Arrays 1D and 2D , and multi dimensional
Appili Vamsi Krishna
 
Savitch Ch 02
Terry Yoast
 
4 linear regeression with multiple variables
TanmayVijay1
 
Arrays & Strings
Munazza-Mah-Jabeen
 
R교육1
Kangwook Lee
 
Operators , Functions and Options in VB.NET
Shyam Sir
 
design and analysis of algorithm
Muhammad Arish
 
01 Notes Introduction Analysis of Algorithms Notes
Andres Mendez-Vazquez
 
Machnical Engineering Assignment Help
Matlab Assignment Experts
 
02 Notes Divide and Conquer
Andres Mendez-Vazquez
 

Viewers also liked (6)

PPTX
Excepionalities
kacielledurham
 
DOCX
Marketing
Dhaval Bhatt
 
PPT
Reasoning Skills
rozthesciencedoc
 
DOCX
CUIDADO DE ENFERMERIA Y PROMOCION DE LA SALUD
CECILIA SANCHEZ
 
DOCX
Chapter one
FavourChukwuemekaUroko59
 
PDF
Master thesis: Developing strategic relationships at Volvo Powertrain
Karl Tiselius
 
Excepionalities
kacielledurham
 
Marketing
Dhaval Bhatt
 
Reasoning Skills
rozthesciencedoc
 
CUIDADO DE ENFERMERIA Y PROMOCION DE LA SALUD
CECILIA SANCHEZ
 
Master thesis: Developing strategic relationships at Volvo Powertrain
Karl Tiselius
 
Ad

Similar to Java căn bản - Chapter3 (20)

PPTX
Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.) I...
GANESHBABUVelu
 
PPT
Java: Primitive Data Types
Tareq Hasan
 
PPTX
Numerical data.
Adewumi Ezekiel Adebayo
 
PPT
M C6java2
mbruggen
 
PPTX
java Basic Programming Needs
Raja Sekhar
 
PPTX
Chapter i(introduction to java)
Chhom Karath
 
PPTX
Java chapter 2
Abdii Rashid
 
PPTX
03 and 04 .Operators, Expressions, working with the console and conditional s...
Intro C# Book
 
PPTX
130717666736980000
Tanzeel Ahmad
 
PPTX
Java fundamentals
HCMUTE
 
PPT
Ap Power Point Chpt2
dplunkett
 
PPT
lecture2 (1).ppt variable s and operators
ChittyAvula
 
PDF
03 expressions.ppt
Business man
 
PPTX
OOP - Lecture04 - Variables, DataTypes and TypeConversion.pptx
AhmedMehmood35
 
PPT
Java Basics
Brandon Black
 
PPTX
Chapter 3.4
sotlsoc
 
PPTX
OOP-java-variables.pptx
ssuserb1a18d
 
PPTX
Introduction to Java Basics Programming-II.pptx
SANDHYAP32
 
PPTX
Java Datatypes
Mayank Aggarwal
 
PPTX
Lecture 3 and 4.pptx
MAHAMASADIK
 
Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.) I...
GANESHBABUVelu
 
Java: Primitive Data Types
Tareq Hasan
 
Numerical data.
Adewumi Ezekiel Adebayo
 
M C6java2
mbruggen
 
java Basic Programming Needs
Raja Sekhar
 
Chapter i(introduction to java)
Chhom Karath
 
Java chapter 2
Abdii Rashid
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
Intro C# Book
 
130717666736980000
Tanzeel Ahmad
 
Java fundamentals
HCMUTE
 
Ap Power Point Chpt2
dplunkett
 
lecture2 (1).ppt variable s and operators
ChittyAvula
 
03 expressions.ppt
Business man
 
OOP - Lecture04 - Variables, DataTypes and TypeConversion.pptx
AhmedMehmood35
 
Java Basics
Brandon Black
 
Chapter 3.4
sotlsoc
 
OOP-java-variables.pptx
ssuserb1a18d
 
Introduction to Java Basics Programming-II.pptx
SANDHYAP32
 
Java Datatypes
Mayank Aggarwal
 
Lecture 3 and 4.pptx
MAHAMASADIK
 
Ad

More from Vince Vo (20)

PPT
Java căn bản - Chapter13
Vince Vo
 
PPT
Java căn bản - Chapter12
Vince Vo
 
PPT
Java căn bản - Chapter10
Vince Vo
 
PPT
Java căn bản - Chapter9
Vince Vo
 
PPT
Java căn bản - Chapter8
Vince Vo
 
PPT
Java căn bản - Chapter7
Vince Vo
 
PPT
Java căn bản - Chapter6
Vince Vo
 
PPT
Java căn bản - Chapter5
Vince Vo
 
PPT
Java căn bản - Chapter4
Vince Vo
 
PPT
Java căn bản - Chapter2
Vince Vo
 
PPT
Java căn bản- Chapter1
Vince Vo
 
DOC
Hướng dẫn cài đặt Java
Vince Vo
 
PDF
Rama Ch14
Vince Vo
 
PDF
Rama Ch13
Vince Vo
 
PDF
Rama Ch12
Vince Vo
 
PDF
Rama Ch12
Vince Vo
 
PDF
Rama Ch11
Vince Vo
 
PDF
Rama Ch10
Vince Vo
 
PDF
Rama Ch8
Vince Vo
 
PDF
Rama Ch9
Vince Vo
 
Java căn bản - Chapter13
Vince Vo
 
Java căn bản - Chapter12
Vince Vo
 
Java căn bản - Chapter10
Vince Vo
 
Java căn bản - Chapter9
Vince Vo
 
Java căn bản - Chapter8
Vince Vo
 
Java căn bản - Chapter7
Vince Vo
 
Java căn bản - Chapter6
Vince Vo
 
Java căn bản - Chapter5
Vince Vo
 
Java căn bản - Chapter4
Vince Vo
 
Java căn bản - Chapter2
Vince Vo
 
Java căn bản- Chapter1
Vince Vo
 
Hướng dẫn cài đặt Java
Vince Vo
 
Rama Ch14
Vince Vo
 
Rama Ch13
Vince Vo
 
Rama Ch12
Vince Vo
 
Rama Ch12
Vince Vo
 
Rama Ch11
Vince Vo
 
Rama Ch10
Vince Vo
 
Rama Ch8
Vince Vo
 
Rama Ch9
Vince Vo
 

Recently uploaded (20)

PPTX
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
PDF
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
PPTX
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
PDF
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
PPTX
How to Set Maximum Difference Odoo 18 POS
Celine George
 
PDF
Lesson 2 - WATER,pH, BUFFERS, AND ACID-BASE.pdf
marvinnbustamante1
 
PPTX
How to Handle Salesperson Commision in Odoo 18 Sales
Celine George
 
PPT
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
PPTX
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
PPTX
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
PDF
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
PDF
The-Ever-Evolving-World-of-Science (1).pdf/7TH CLASS CURIOSITY /1ST CHAPTER/B...
Sandeep Swamy
 
PDF
The dynastic history of the Chahmana.pdf
PrachiSontakke5
 
PDF
LAW OF CONTRACT (5 YEAR LLB & UNITARY LLB )- MODULE - 1.& 2 - LEARN THROUGH P...
APARNA T SHAIL KUMAR
 
PPTX
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
PDF
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
PPTX
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
PPT
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
PDF
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
PDF
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
How to Set Maximum Difference Odoo 18 POS
Celine George
 
Lesson 2 - WATER,pH, BUFFERS, AND ACID-BASE.pdf
marvinnbustamante1
 
How to Handle Salesperson Commision in Odoo 18 Sales
Celine George
 
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
The-Ever-Evolving-World-of-Science (1).pdf/7TH CLASS CURIOSITY /1ST CHAPTER/B...
Sandeep Swamy
 
The dynastic history of the Chahmana.pdf
PrachiSontakke5
 
LAW OF CONTRACT (5 YEAR LLB & UNITARY LLB )- MODULE - 1.& 2 - LEARN THROUGH P...
APARNA T SHAIL KUMAR
 
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 

Java căn bản - Chapter3

  • 2. Objectives After you have read and studied this chapter, you should be able to Select proper types for numerical data. Write arithmetic expressions in Java. Evaluate arithmetic expressions using the precedence rules. Describe how the memory allocation works for objects and primitive data values. Write mathematical expressions, using methods in the Math class. Use the GregorianCalendar class in manipulating date information such as year, month, and day. Use the DecimalFormat class to format numerical data Convert input string values to numerical data Perform input and output by using System.in and System.out
  • 3. Manipulating Numbers In Java, to add two numbers x and y, we write x + y But before the actual addition of the two numbers takes place, we must declare their data type. If x and y are integers, we write int x, y; or int x; int y;
  • 4. Variables When the declaration is made, memory space is allocated to store the values of x and y. x and y are called variables . A variable has three properties: A memory location to store the value, The type of data stored in the memory location, and The name used to refer to the memory location. Sample variable declarations: int x; int v, w, y;
  • 5. Numerical Data Types There are six numerical data types: byte , short , int , long , float , and double . Sample variable declarations: int i, j, k; float numberOne, numberTwo; long bigInteger; double bigNumber; At the time a variable is declared, it also can be initialized. For example, we may initialize the integer variables count and height to 10 and 34 as int count = 10, height = 34;
  • 6. Data Type Precisions The six data types differ in the precision of values they can store in memory.
  • 7. Assignment Statements We assign a value to a variable using an assignment statements . The syntax is <variable> = <expression> ; Examples: sum = firstNumber + secondNumber; avg = (one + two + three) / 3.0;
  • 8. Arithmetic Operators The following table summarizes the arithmetic operators available in Java. This is an integer division where the fractional part is truncated.
  • 9. Arithmetic Expression How does the expression x + 3 * y get evaluated? Answer: x is added to 3*y. We determine the order of evaluation by following the precedence rules . A higher precedence operator is evaluated before the lower one. If two operators are the same precedence, then they are evaluated left to right for most operators.
  • 11. Type Casting If x is a float and y is an int , what will be the data type of the following expression? x * y The answer is float . The above expression is called a mixed expression . The data types of the operands in mixed expressions are converted based on the promotion rules . The promotion rules ensure that the data type of the expression will be the same as the data type of an operand whose type has the highest precision.
  • 12. Explicit Type Casting Instead of relying on the promotion rules, we can make an explicit type cast by prefixing the operand with the data type using the following syntax: ( <data type> ) <expression> Example (float) x / 3 (int) (x / y * 3.0) Type case x to float and then divide it by 3. Type cast the result of the expression x / y * 3.0 to int .
  • 13. Implicit Type Casting Consider the following expression: double x = 3 + 5; The result of 3 + 5 is of type int . However, since the variable x is double , the value 8 (type int ) is promoted to 8.0 (type double ) before being assigned to x . Notice that it is a promotion. Demotion is not allowed. int x = 3.5; A higher precision value cannot be assigned to a lower precision variable.
  • 14. Constants We can change the value of a variable. If we want the value to remain the same, we use a constant . final double PI = 3.14159; final int MONTH_IN_YEAR = 12; final short FARADAY_CONSTANT = 23060; These are constants, also called named constant . The reserved word final is used to declare constants. These are called literal constant.
  • 15. Primitive vs. Reference Numerical data are called primitive data types . Objects are called reference data types , because the contents are addresses that refer to memory locations where the objects are actually stored.
  • 16. Primitive Data Declaration and Assignments Code State of Memory int firstNumber, secondNumber; firstNumber = 234; secondNumber = 87; A B firstNumber secondNumber A. Variables are allocated in memory. B. Values are assigned to variables. 234 87
  • 17. Assigning Numerical Data Code State of Memory int number; number = 237; number A. The variable is allocated in memory. B. The value 237 is assigned to number . 237 A B C number = 35; C. The value 35 overwrites the previous value 237. 35
  • 18. Assigning Objects Code State of Memory Customer customer; customer = new Customer( ); customer = new Customer( ); customer A. The variable is allocated in memory. A B C B. The reference to the new object is assigned to customer . Customer C. The reference to another object overwrites the reference in customer. Customer
  • 19. Having Two References to a Single Object Code State of Memory Customer clemens, twain, clemens = new Customer( ); twain = clemens; A B C A. Variables are allocated in memory. clemens twain B. The reference to the new object is assigned to clemens . Customer C. The reference in clemens is assigned to customer.
  • 20. Type Mismatch Suppose we want to input an age. Will this work? No. String value cannot be assigned directly to an int variable. int age; age = JOptionPane.showInputDialog( null , “Enter your age”);
  • 21. Type Conversion Wrapper classes are used to perform necessary type conversions, such as converting a String object to a numerical value. int age; String inputStr; inputStr = JOptionPane.showInputDialog( null , “Enter your age”); age = Integer.parseInt(inputStr);
  • 23. Sample Code Fragment //code fragment to input radius and output //area and circumference double radius, area, circumference; radiusStr = JOptionPane.showInputDialog( null , &quot;Enter radius: &quot; ); radius = Double.parseDouble(radiusStr); //compute area and circumference area = PI * radius * radius; circumference = 2.0 * PI * radius; JOptionPane.showMessageDialog( null , &quot;Given Radius: &quot; + radius + &quot;\n&quot; + &quot;Area: &quot; + area + &quot;\n&quot; + &quot;Circumference: &quot; + circumference);
  • 24. Overloaded Operator + The plus operator + can mean two different operations, depending on the context. <val1> + <val2> is an addition if both are numbers. If either one of them is a String, the it is a concatenation. Evaluation goes from left to right. output = “test” + 1 + 2; output = 1 + 2 + “test”;
  • 25. The DecimalFormat Class Use a DecimalFormat object to format the numerical output. double num = 123.45789345; DecimalFormat df = new DecimalFormat(“0.000”); //three decimal places System.out.print ( num ) ; System.out.print ( df.format ( num )) ; 123.45789345 123.458
  • 26. 3.5 Standard Output The showMessageDialog method is intended for displaying short one-line messages, not for a general-purpose output mechanism. Using System.out, we can output multiple lines of text to the standard output window.
  • 27. Standard Output Window A sample standard output window for displaying multiple lines of text. The exact style of standard output window depends on the Java tool you use.
  • 28. The print Method We use the print method to output a value to the standard output window. The print method will continue printing from the end of the currently displayed output. Example System.out.print ( “Hello, Dr. Caffeine.” );
  • 29. The println Method We use println instead of print to skip a line. int x = 123, y = x + x; System.out.println( &quot;Hello, Dr. Caffeine.“ ); System.out.print( &quot; x = “ ); System.out.println( x ); System.out.print( &quot; x + x = “ ); System.out.println( y ); System.out.println( &quot; THE END“ );
  • 30. Standard Input The technique of using System.in to input data is called standard input. We can only input a single byte using System.in directly. To input primitive data values, we use the Scanner class (from Java 5.0). Scanner scanner; scanner = Scanner.create(System.in); int num = scanner.nextInt();
  • 31. Method Example nextByte( ) byte b = scanner.nextByte( ); nextDouble( ) double d = scanner.nextDouble( ); nextFloat( ) float f = scanner.nextFloat( ); nextInt( ) int i = scanner.nextInt( ); nextLong( ) long l = scanner.nextLong( ); nextShort( ) short s = scanner.nextShort( ); next() String str = scanner.next(); Common Scanner Methods:
  • 32. The Math class The Math class in the java.lang package contains class methods for commonly used mathematical functions. double num, x, y; x = …; y = …; num = Math.sqrt(Math.max(x, y) + 12.4);
  • 33. Some Math Class Methods Table 3.8 page 113 in the textbook contains a list of class methods defined in the Math class. The sine of a . (Note: all trigonometric functions are computed in radians) sin(a) The square root of a . sqrt(a) The larger of a and b. max(a,b) Natural logarithm (base e ) of a . log(a) The number a raised to the power of b . pow(a,b) Natural number e raised to the power of a . exp(a) The largest whole number less than or equal to a . floor(a) Description Method
  • 34. Computing the Height of a Pole alphaRad = Math.toRadians ( alpha ) ; betaRad = Math.toRadians ( beta ) ; height = ( distance * Math.sin ( alphaRad ) * Math.sin ( betaRad ) ) / Math.sqrt ( Math.sin ( alphaRad + betaRad ) * Math.sin ( alphaRad - betaRad ) ) ;
  • 35. The GregorianCalendar Class Use a GregorianCalendar object to manipulate calendar information GregorianCalendar today, independenceDay; today = new GregorianCalendar () ; independenceDay = new GregorianCalendar ( 1776, 6, 4 ) ; //month 6 means July; 0 means January
  • 36. Retrieving Calendar Information This table shows the class constants for retrieving different pieces of calendar information from Date .
  • 37. Sample Calendar Retrieval GregorianCalendar cal = new GregorianCalendar () ; //Assume today is Nov 9, 2003 System.out.print(“Today is ” + (cal.get(Calendar.MONTH)+1) + “/” + cal.get(Calendar.DATE) + “/” + cal.get(Calendar.YEAR)); Today is 11/9/2003 Output
  • 38. Problem Statement Problem statement: Write a loan calculator program that computes both monthly and total payments for a given loan amount, annual interest rate, and loan period.
  • 39. Overall Plan Tasks: Get three input values: loanAmount , interestRate , and loanPeriod . Compute the monthly and total payments. Output the results.
  • 41. Development Steps We will develop this program in four steps: Start with code to accept three input values. Add code to output the results. Add code to compute the monthly and total payments. Update or modify code and tie up any loose ends.
  • 42. Step 1 Design Call the showInputDialog method to accept three input values: loan amount, annual interest rate, loan period. Data types are int in years loan period double in percent (e.g.,12.5) annual interest rate double dollars and cents loan amount Data Type Format Input
  • 43. Step 1 Code Directory: Chapter3/Step1 Source File: Ch3LoanCalculator.java Program source file is too big to list here. From now on, we ask you to view the source files using your Java IDE.
  • 44. Step 1 Test In the testing phase, we run the program multiple times and verify that we can enter three input values we see the entered values echo-printed correctly on the standard output window
  • 45. Step 2 Design We will consider the display format for out. Two possibilities are (among many others)
  • 46. Step 2 Code Directory: Chapter3/Step2 Source File: Ch3LoanCalculator.java
  • 47. Step 2 Test We run the program numerous times with different types of input values and check the output display format. Adjust the formatting as appropriate
  • 48. Step 3 Design The formula to compute the geometric progression is the one we can use to compute the monthly payment. The formula requires the loan period in months and interest rate as monthly interest rate. So we must convert the annual interest rate (input value) to a monthly interest rate (per the formula), and the loan period to the number of monthly payments.
  • 49. Step 3 Code Directory: Chapter3/Step3 Source File: Ch3LoanCalculator.java
  • 50. Step 3 Test We run the program numerous times with different types of input values and check the results.
  • 51. Step 4: Finalize We will add a program description We will format the monthly and total payments to two decimal places using DecimalFormat. Directory: Chapter3/Step4 Source File: Ch3LoanCalculator.java