Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Java Data Types: A Comprehensive Guide, Assignments of Computer Science

An in-depth exploration of java data types, including integers, real numbers, boolean, characters, and strings. It covers topics such as declarations, initializations, assignments, and arithmetic operations. The document also discusses the use of symbols, constants, and the difference between objects and primitives.

Typology: Assignments

Pre 2010

Uploaded on 11/08/2009

koofers-user-0ft
koofers-user-0ft 🇺🇸

10 documents

1 / 16

Toggle sidebar

Related documents


Partial preview of the text

Download Java Data Types: A Comprehensive Guide and more Assignments Computer Science in PDF only on Docsity! data types ©cs160 2006 Fundamental Data Types of Java Ch. 2,3.1, 3.2, 3.3, 3.5, 3.6 Lewis et al. Numbers Declarations, initialization, assignment Strings, characters Basic memory model data types ©cs160 2006 Hello World Chapter Preview In this chapter we will:  Discuss four primitive data types  integers  real numbers  boolean  characters  Describe the process of developing and debugging a Java program data types ©cs160 2006 Hello World Primitive Data Types  4 most common primitive data types Data Type Description Example  int - integer values 5  double - floating-point values 3.14  char - characters ‘J’  boolean - either true or false true data types ©cs160 2006 Hello World Declaring Data Types  Declaration of a variable we specify dataType variableName ;  Examples:  int age;  double salesTax;  char myInitial;  boolean isDone;  int ageMary, ageJoe, ageAbby; data types ©cs160 2006 Hello World Initializing Data Types  Initialization is when we assign a value to a variable for the first time.  Initializing a variable we specify variableName = value;  Examples:  age = 13;  salesTax = 6.7;  myInitial = ‘E’;  isDone = false; data types ©cs160 2006 Hello World Declare and initialize Data Types  We can declare and initialize in one step  Examples:  int age = 13;  double salesTax = 6.7;  char myInitial = ‘E’;  boolean isDone = true;  int ageMary = 13, ageJoe = 15, ageVal = 22;  boolean isDone = true, isMax = false; Can’t do this: int ageMary, ageJoe, ageVal; ageMary = 13, ageJoe=15; data types ©cs160 2006 Hello World Initialization  May be used to give variables initial values int x = 5; int y = 6;  Can be written more concisely int x = 5, y = 6;  Can use expressions on the right hand side int x = 5, y = x + 1; What does y evaluate to?What is the final value of x? Always evaluate stuff to the right of the = first, then store the value into the variable listed left of the = data types ©cs160 2006 Hello World Symbolic Constants  Useful when you want a variable whose value never changes  Use the modifier final in its declaration  Example final int days_of_week = 7;  If declared final, you can NOT days_of_week = 3; Illegal! data types ©cs160 2006 Hello World Additional Integer Operators  Self-assignment int temperature = 32; temperature = temperature + 10; What is temperature = ?  Increment cent++; equivalent to cent = cent + 1; cent+=10; equivalent to cent = cent + 10;  Decrement cent--; equivalent to cent = cent - 1; cent-=10; equivalent to cent = cent - 10; data types ©cs160 2006 Hello World Unary minus  Unary = An operator that takes only one operand.  Unary minus = Indicates a negative number.  Has the highest precedence (evaluated first).  Example:  -1*-2  -1- -2 (negative 1 minus negative 2)  int x = -5, y = 2; int z = 9 - -x * y; What is z = ? data types ©cs160 2006 Hello World Number Theory  Basic concepts of integers, conversion of bases and division and remainder are covered from a mathematical theory viewpoint in Rosen  Edition 6: Chapter 3.4 and 3.5.  Edition 5: 2.5  Please read! – We will cover next week! data types ©cs160 2006 Hello World Real Numbers  Numbers with fractional parts 3.14159, 7.12, 9.0, 0.5e001, -16.3e+002  Declared using the data type double double pricePerPound = 3.99, taxRate = 0.05, shippingCost = 5.55; double pctProfit = 12.997; Note: double is not R, it isn’t even Q Why? data types ©cs160 2006 Hello World double Arithmetic Operations 96.0 / 2.0Division/ 70.0 * 3.0Multiplication* 657.0 – 5.7Subtraction- 45.0 + 5.30Addition+ ExampleOperationSymbol data types ©cs160 2006 Hello World Methods working with doubles … (see text or java.sun.com) Returns, as a double, the largest int value not more than x double Math.floor(double x) Returns, as a double, the smallest int value not less than x double Math.ceil(double x) Absolute value of xdouble Math.abs(double x) data types ©cs160 2006 Hello World Math class methods - Example public class Functions { public static void main(String[] args) { double real = -92.49102; System.out.println( Math.abs( real ) ); System.out.println( Math.pow( 2,4 ) ); int absVal = Math.abs( -92 ); } } data types ©cs160 2006 Hello World Numbers: Bridging from Theory to Practice  Is Java int equivalent to Z from mathematics?  We can convert binary to decimal and back again, but what about representing  negative numbers?  double? data types ©cs160 2006 Hello World 2’s complement numbers data types ©cs160 2006 Hello World Hardware number representation  Unsigned integers, we know them  0000, 0001, 0010, 0011,…, 1111 represent 0 to 15  8 bits: 0 to 28- 1, 32 bits: 0 to 232- 1  Signed integers: there are options  1’s complement  2’s complement  Signed magnitude  You will learn about these in CS270, we will only discuss 2’s complement data types ©cs160 2006 Hello World 2’s complement numbers  Lets work with 4 bit numbers  Positive numbers  are same as unsigned but range from 0 (0000) to 7 (0111)  The first 0 in the number represents that the # is positive  Negative numbers  flip the bits and add 1  Examples -1 start w/ 1: 0001, flip bits: 1110, add 1: 1111 -(-1) start w/ -1: 1111, flip bits: 0000, add 1: 0001 data types ©cs160 2006 Hello World 2’s complement cont’ positive flip add number bits 1 -1 0001 1110 1111 -2 0010 1101 1110 -3 0011 1100 1101 -4 0100 1011 1100 -5 0101 1010 1011 -6 0110 1001 1010 -7 0111 1000 1001 -8 1000 0111 1000 Notice: the range of 4 bit 2’s complement numbers: -8 .. 7 the range of 8 bit 2’s complement numbers: -27 .. 27-1 data types ©cs160 2006 Hello World Mixing Numeric Data Types  Widening conversion Java will automatically convert int expressions to double values without loss of information  int i = 5; double x = i + 10.5;  double y = i;  Narrowing conversion To convert double expressions to int requires a typecasting operation and truncation will occur i = (int) (10.3 * 2)  To round-up instead of truncating add 0.5 i = (int) (10.3 * x + 0.5) Arithmetic promotion of i to largest data type double assignment promotion of i i = 20 : the .6 is truncated data types ©cs160 2006 Hello World Characters  Any key you type on the keyboard generates a character which may or may not be displayed on the screen (e.g., nonprinting characters)  Characters are a primitive type in Java and are not equivalent to strings  Examples char vitamin = ’A’, chromosome = ’y’, middleInitial = ’N’; data types ©cs160 2006 Hello World Important Literal Characters Single Right Quote’\’’ Backslash’\\’ Tab’\t’ New line’\n’ Blank’ ’ Punctuation Marks’.’, ’,’, ’!’,’”’,etc. Digits’0’, … , ’9’ Lowercase letters’a’, … ,’z’ Uppercase letters’A’, … ,’Z’ data types ©cs160 2006 Hello World Characters as Integers  It is legal to assign a char to an int variable int i = ’a’; // assigns 97 to i  It is legal to assign an int to a char variable char c = 97; // assigns ’a’ to c  It is possible (kinda) to perform arithmetic on char variables char ch = ’a’; ch = (char)((int)ch + 1); // ch is ’b’ data types ©cs160 2006 Hello World Object Data Types Example: Strings data types ©cs160 2006 Hello World Strings  String is a class defined in the java.lang package  *The java.lang package is automatically included in all programs, so you do not need to import it.  String literals are defined in double-quotes “string”  Can add two strings together  concatenates them  Number + string  String (concatenation)  String + number  String (concatenation)  Number + number  number  Examples String prompt = “Enter an integer:”; String t1 = “To be ”, t2 = “or not to be”; System.out.print(t1 + t2); System.out.print(“Mass is ” + x * 2.2 + “ Kg”); data types ©cs160 2006 Hello World String Methods Returns the character at the index, which must be between 0 and length of string - 1 char charAt(int index) Converts all characters of the string to uppercase String toLowerCase() Converts all characters of the string to uppercase String toUpperCase() Returns the substring beginning at index beginx and ending at index endx-1 String substring (int beginx, int endx) Returns the index within the string of the first occurrence of the string s. int indexOf(String s) Returns the length of this stringint length() DescriptionName data types ©cs160 2006 Hello World String Method Examples public class StringEx { public static void main( String[ ] args ) { String s1 = "Here is a test string"; System.out.println(s1.indexOf("s")); System.out.println(s1.indexOf("x")); System.out.println(s1.length()); System.out.println(s1.substring(8,14)); } } data types ©cs160 2006 Hello World Methods versus Operations  Primitive data types use operations that specify variables or literals as arguments  E.g.,  5 + 6  Math.min(x,3);  Objects, such as String, invoke methods on themselves and use arguments to include other variables or literals  E.g.,  String s1 = “Strings are fun Stuffs!”; s1.indexOf(“s”); data types ©cs160 2006 Hello World Objects vs Primitives The Data Type War data types ©cs160 2006 Hello World Different Data Types  Primitives:  Doesn’t use new to allocate space  Requires a fixed known amount of memory  Uses operations, not methods  Building blocks for classes  Can hold only one value  Objects:  Objects use new to allocate space  Variables reference objects elsewhere in memory  Can have multiple data values associated with them  Can have methods that can be called on to affect the data values data types ©cs160 2006 Hello World Java Data Types  8 Primitive Data Types:  Integer types: byte, short, int, long  Floating-pt type: double, float  char  boolean  Objects:  Everything else data types ©cs160 2006 Hello World Aside: print parameters  Methods can sometimes take different types as parameters!  Java methods are defined by:  Their names  The number of parameters  The types of the parameters  Examples  System.out.println( ) and System.out.println( number )  System.out.println( 5 ); System.out.println( ); System.out.print( -2.993 ); System.out.print( “Cookie Monster likes Java” ); data types ©cs160 2006 Hello World Formatting Decimal Values  Use DecimalFormat class  Leading zeros (e.g. money: $0.25)  “0.##”  Trailing zeros (e.g. money: $5.30)  “#.00”  Truncate to 3 decimal values  “#.###”  Add comma for thousands  “#,###” data types ©cs160 2006 Hello World Formatting Decimal Values  Import package import java.text.*;  Create the object DecimalFormat fmt = new DecimalFormat( “#.##” );  Specify which numbers to format when printing by calling format method System.out.println( fmt.format( 45.6789 ) ); data types ©cs160 2006 Hello World Formatting Decimal Values Examples  DecimalFormat fmt = new DecimalFormat( “#.##” ); System.out.println( fmt.format( 45.6789 ) ); System.out.println( fmt.format( 345.6 ) ); System.out.println( fmt.format( 67.0 ) );  DecimalFormat fmt = new DecimalFormat( “000.00” ); System.out.println( fmt2.format( 45.6789 ) ); System.out.println( fmt2.format( 5.6 ) );  DecimalFormat fmt6 = new DecimalFormat( "#,###" ); System.out.println( fmt6.format( 12345 ) ); data types ©cs160 2006 Hello World Common Debugging Problems  Misleading compiler error messages  Syntax errors indicated on one-line may actually reflect an error made on an earlier line  Capitalization errors  Java is case sensitive, identifier names must use the same capitalization rules each time  Logic Errors  Program appears to run correctly, but on closer inspection the wrong output is displayed data types ©cs160 2006 Hello World Debugging Hints  Let Eclipse help you!  Gives suggestions on methods to use  Provides warning and error messages as you type… even provides suggestions of how to fix the problem.  Print out debug statements in the console to check that computation is proceeding correctly -- System.out.println(…); data types ©cs160 2006 Hello World Summary  Primitives  Objects  Strings  Input/Output in Java
Docsity logo



Copyright © 2024 Ladybird Srl - Via Leonardo da Vinci 16, 10126, Torino, Italy - VAT 10816460017 - All rights reserved