Data Types in Java James Burns. Recitation Name some characteristics of objects Name some...
-
Upload
colin-simon-flynn -
Category
Documents
-
view
217 -
download
3
Transcript of Data Types in Java James Burns. Recitation Name some characteristics of objects Name some...
RecitationRecitationName some characteristics of objectsName some characteristics of objects
Chemical BankChemical BankDescribe the differences between Describe the differences between
interpreters and compilersinterpreters and compilersApplets—interpreted or compiled?Applets—interpreted or compiled?JAVA Apps—JAVA Apps—
What is a namespace?What is a namespace?Is it supported by JAVA?Is it supported by JAVA?A A usingusing keyword brings a namespace into keyword brings a namespace into
scopescope
Four common namespaces Four common namespaces (C#)(C#)
using System;using System;
using System.Collections.Generic;using System.Collections.Generic;
using System.Linq;using System.Linq;
using System.Text;using System.Text;
There are hundreds of classes in these There are hundreds of classes in these namespacesnamespaces
The .NET framework class library contains The .NET framework class library contains many thousands of classesmany thousands of classes
Namespaces are also called Namespaces are also called assemblies of classesassemblies of classes
When you select a particular When you select a particular template type upon creation of a template type upon creation of a project, that results in references to project, that results in references to the appropriate assemblies being the appropriate assemblies being included automatically for youincluded automatically for you
By clicking on references in the By clicking on references in the solution explorer box, you can see solution explorer box, you can see what assemblies have been selected what assemblies have been selected for youfor you
Boxes in the VS 2008 IDEBoxes in the VS 2008 IDE
Code and Text Editor—is also the Code and Text Editor—is also the Forms DesignerForms Designer
Solution Explorer—upper rightSolution Explorer—upper rightProperties Box—lower rightProperties Box—lower rightXAML Editor—lower middleXAML Editor—lower middleError List/Output box at the bottomError List/Output box at the bottom
SpecificsSpecifics
Code and Text Editor—also can be used as Code and Text Editor—also can be used as the forms designerthe forms designer
Use ICONS above Solution Explorer on the Use ICONS above Solution Explorer on the right to go from code editor to forms right to go from code editor to forms designerdesigner
Select an object on the form and change its Select an object on the form and change its properties byproperties byChanging them in the Properties window in the Changing them in the Properties window in the
lower rightlower rightChanging them in the XAML window at the Changing them in the XAML window at the
bottombottom
What is a Constant?What is a Constant?
456—a literal numerical constant456—a literal numerical constantSystem.out.println(456); // JavaSystem.out.println(456); // JavaConsole.writeline(456); // Visual C#Console.writeline(456); // Visual C#
““A Literal String Constant”A Literal String Constant”System.out.println(“My First Java”); // System.out.println(“My First Java”); //
JavaJavaConsole.writeline(“My First C#”); // Console.writeline(“My First C#”); //
Visual C#Visual C#
What is a variable?What is a variable? It is a named computer location in memory It is a named computer location in memory
that holds values that might varythat holds values that might varyMust that location have an address?Must that location have an address?
YESYESWhat has addresses? Bits, bytes, words, What has addresses? Bits, bytes, words,
what?what?BytesBytes
Can a variable be more than one byte Can a variable be more than one byte long?long?YESYES
Data type DeclarationsData type Declarations
Specify the type of data and the Specify the type of data and the length of the data item in byteslength of the data item in bytes
int, short, longint, short, longfloat, doublefloat, doublebooleanbooleancharchar
Data Types -- IntegerData Types -- Integer
Int – the default declaration – 4-byte Int – the default declaration – 4-byte integerinteger
Byte—1-byte integerByte—1-byte integerShort—2-byte integerShort—2-byte integerLong—8-byte integerLong—8-byte integer
Floating PointFloating Point
Float—a 4-byte floating point numberFloat—a 4-byte floating point numberDouble—an 8-byte floating point Double—an 8-byte floating point
numbernumber
There are eight primitive data There are eight primitive data typestypes
Name themName themBoolean, byte, char, double, float, int, Boolean, byte, char, double, float, int,
long, shortlong, short In bytes, how long is the short data In bytes, how long is the short data
type? The int data type, the long data type? The int data type, the long data type?type?
In bytes, how long is the float data In bytes, how long is the float data type? The double data type?type? The double data type?
How long is the char data type?How long is the char data type?
Primitives sizes and RangesPrimitives sizes and Ranges
PRIMITIVE SIZE IN BITS RANGE
int 32 -2 to the 31st to 2 to the 31st
int 4 bytes 2147483648
long 64 -- 8 bytes -2 to the 63rd to 2 to the 63rd
float 32 +- 1.5 x 10^45
double 64 +- 5.0 x 10^324
decimal (C# only) 128 28 significant figures
string 16 bits per char
Not applicable
char 16 One character
bool (boolean in Java)
8 True or false
The assignment operator =The assignment operator =
A = 36;A = 36;Sets a = to the constant 36 at execution Sets a = to the constant 36 at execution
timetime Int A =36;Int A =36;
Sets A = to the constant 36 at compile Sets A = to the constant 36 at compile timetime
Initializes A to 36 at the time memory is Initializes A to 36 at the time memory is set aside for itset aside for it
Name a Method that many Java Name a Method that many Java classes haveclasses have
The Main methodThe Main methodWhy??Why??
It is used as an entry point to the program It is used as an entry point to the program for some types of programs.for some types of programs.
Which of these do we usually Which of these do we usually use in connection with a class?use in connection with a class?
Which of these do we use in Which of these do we use in connection with the declaration of a connection with the declaration of a main?main?
Consider the following:Consider the following:
Public class NumbersPrintlnPublic class NumbersPrintln{{ public static void main(String[] args)public static void main(String[] args) {{ int billingDate = 5;int billingDate = 5; System.out.print(“Bills are sent on the “);System.out.print(“Bills are sent on the “); System.out.print(billingDate);System.out.print(billingDate);
System.out.println(“th”); System.out.println(“th”); System.out.println(“Next bill: October “ + billingDate);System.out.println(“Next bill: October “ + billingDate); }}}}
The above produces the The above produces the following outputfollowing output
C:\Java>_C:\Java>_
C:\Java>Java NumbersPrintlnC:\Java>Java NumbersPrintln
Bills are sent on the 5Bills are sent on the 5thth
Next bill: October 5Next bill: October 5
C:\Java>_C:\Java>_
This program would produce the This program would produce the same outputsame output
Public class NumbersPrintlnPublic class NumbersPrintln{{ public static void main(String[] args)public static void main(String[] args) {{ int billingDate = 5;int billingDate = 5; System.out.println(“Bills are sent on the “ System.out.println(“Bills are sent on the “
+ billingDate + “th\nNext bill: October “ + + billingDate + “th\nNext bill: October “ + billingDate);billingDate);
}}}}
Simple Arithmetic OperatorsSimple Arithmetic Operators
• * / % (multiplication, division, * / % (multiplication, division, modulus)modulus)
• + - (addition, subtraction—on a + - (addition, subtraction—on a lower level of the precedence lower level of the precedence hierarchy)hierarchy)
• int result = 2 + 3 * 4;int result = 2 + 3 * 4;• Is result 14 or 20??Is result 14 or 20??• int result = (2 + 3) * 4int result = (2 + 3) * 4
Binary OperatorsBinary Operators
The simple arithmetic operators are The simple arithmetic operators are also called binary operators because also called binary operators because they have two operands exactlythey have two operands exactly
Never threeNever threeNever oneNever one
Using the Boolean data typeUsing the Boolean data type
• Boolean variables can hold only one Boolean variables can hold only one of two values—true or falseof two values—true or false
Boolean isItPayday = false;Boolean isItPayday = false;
Boolean areYouBroke = true;Boolean areYouBroke = true;
Comparison operatorsComparison operators
The result is boolean, alwaysThe result is boolean, always
< less than< less than
> greater than> greater than
== equal to== equal to
<= less than or equal to<= less than or equal to
>= greater than or equal to>= greater than or equal to
!= not equal to!= not equal to
Boolean examplesBoolean examples
boolean is SixBigger = (6 > 5);boolean is SixBigger = (6 > 5);
// value stored in is SixBigger is true// value stored in is SixBigger is true
Boolean is SevenSmaller = (7 <= 4);Boolean is SevenSmaller = (7 <= 4);
// value stored in is SevenSmaller is // value stored in is SevenSmaller is falsefalse
Data formatsData formats
The character format—uses an The character format—uses an assigned decimal valueassigned decimal value
The integer formatThe integer format
The floating point format—consists of The floating point format—consists of an exponent part and a mantissa an exponent part and a mantissa part—for example the 4-byte floating part—for example the 4-byte floating point word might have a 1-byte point word might have a 1-byte exponent and a 3-byte mantissa.exponent and a 3-byte mantissa.
What happens when you try to What happens when you try to do arithmetic with different data do arithmetic with different data
types?types?The lower-level data type is converted The lower-level data type is converted
to the higher-level data type before to the higher-level data type before the binary operation is performedthe binary operation is performed
1.1. doubledouble
2.2. floatfloat
3.3. longlong
4.4. intint
ExampleExample
int hoursWorked = 37;int hoursWorked = 37;
Double payRate = 6.73;Double payRate = 6.73;
Double grossPay = hoursWorked * Double grossPay = hoursWorked * payRate;payRate;
Here, hoursWorked is converted from int Here, hoursWorked is converted from int to double before the * operation is to double before the * operation is performed; the result, grossPay performed; the result, grossPay contains 249.01 stored as a doublecontains 249.01 stored as a double
Type castingType casting
• Forces a value of one data type to be Forces a value of one data type to be used as a value of another typeused as a value of another type
• ExampleExample
Double bankBalance = 189.66;Double bankBalance = 189.66;
Float weeklyBudget = (float) Float weeklyBudget = (float) bankBalance / 4;bankBalance / 4;
/* weeklyBudget is 47.415, one-forth of /* weeklyBudget is 47.415, one-forth of bankBalance */bankBalance */
In the above…In the above…
Without the use of the (float), the Without the use of the (float), the code segment would not compilecode segment would not compile
Another type casting Another type casting exampleexample
float myMoney = 47.82f;float myMoney = 47.82f;
int dollars = (int) myMoney;int dollars = (int) myMoney;
// dollars is 47, the integer part of // dollars is 47, the integer part of myMoneymyMoney
// note that myMoney was not // note that myMoney was not roundedrounded
The char data typeThe char data type
Holds only a single characterHolds only a single character
Legal ExamplesLegal Exampleschar myMiddleInitial = ‘M’;char myMiddleInitial = ‘M’;
char myGradeInChemistry = ‘A’;char myGradeInChemistry = ‘A’;
char aStar = ‘*’;char aStar = ‘*’;
char aCharValue = ‘9’;char aCharValue = ‘9’;
char aNewLine = ‘\n’;char aNewLine = ‘\n’;
char aTabChar = ‘\t’;char aTabChar = ‘\t’;
In the latter two cases In the latter two cases above…above…
The char variables still hold a single The char variables still hold a single charactercharacter
The backslash gives a new meaning The backslash gives a new meaning to the character that followsto the character that follows
The pair together represents a single The pair together represents a single nonprinting characternonprinting character
To hold strings in a variable…To hold strings in a variable…
Use the string class that is built-inUse the string class that is built-in
string firstName = “Audrey”;string firstName = “Audrey”;
Using the Joption Pane Class Using the Joption Pane Class for GUI Inputfor GUI Input
An input dialog box asks a question and An input dialog box asks a question and provides a text field in which the user provides a text field in which the user can enter a response.can enter a response.
The user’s response is returned by the The user’s response is returned by the method and placed in a string variablemethod and placed in a string variable
An exampleAn example
Import javax.swing.JOptionPane;Import javax.swing.JOptionPane;
Public class HelloNameDialogPublic class HelloNameDialog
{{Public static void main(string[] args)Public static void main(string[] args)
{{String result;String result;
result = JOptionPane.ShowInputDialog(“What is your name?”);result = JOptionPane.ShowInputDialog(“What is your name?”);
JOptionPane.showMessageDialog(null, “Hello, “ + result + JOptionPane.showMessageDialog(null, “Hello, “ + result + “!”);“!”);
System.exit(0);System.exit(0);
}}
}}
Using Methods, classes, and Using Methods, classes, and ObjectsObjects
Methods are similar to procedures, Methods are similar to procedures, functions, or subroutinesfunctions, or subroutines
Statements within a method execute Statements within a method execute only when the method is calledonly when the method is called
To execute a method, you call it from To execute a method, you call it from another methodanother method““The calling method makes a method The calling method makes a method
call”call”
Simple methods….Simple methods….
Don’t require any data items Don’t require any data items (arguments or parameters), nor do (arguments or parameters), nor do they return any data items backthey return any data items back
You can create a method once and You can create a method once and use it many times in different use it many times in different contextscontexts
ExampleExample
Public class FirstPublic class First
{{Public static void main(String[] args)Public static void main(String[] args)
{{System.out.println(“First Java application”);System.out.println(“First Java application”);
}}
}}
Method DeclarationMethod Declaration
Is the first line or header of a method Is the first line or header of a method and containsand containsOptional access modifiersOptional access modifiersThe return type for the methodThe return type for the methodThe method nameThe method nameAn opening parenthesisAn opening parenthesisAn optional list of method arguments An optional list of method arguments
separated by commasseparated by commasA closing parenthesisA closing parenthesis
Access ModifiersAccess Modifiers
publicpublic – accessible anywhere – accessible anywhere
privateprivate – accessible only within the class – accessible only within the class in which it is definedin which it is defined
protected – protected – allows members of a allows members of a derived class to access members of its derived class to access members of its parent classesparent classes
staticstatic – does not require instantiation – does not require instantiation before it can be used and remains in before it can be used and remains in place after use, without being destroyedplace after use, without being destroyed