370 likes | 499 Vues
This guide covers key concepts in Java programming including primitive data types, strings, variables, and constants. Learn how strings function as objects defined by the String class, and how to print strings using the print and println methods. Understand the concept of string concatenation, and explore escape sequences for special characters. Discover primitive data types and their sizes, variable declaration and initialization rules, and effective practices for using variables. Ideal for beginners wanting to grasp the fundamental building blocks of Java programming.
E N D
CSci 142 Data and Expressions
Data and Expressions • Topics • Strings • Primitive data types • Variables and constants • Expressions and operator precedence • Data conversions
Character Strings • A String consists of zero or more characters • Represent a String literal with double quotes "This is a string literal." "123 Main Street" "X" "" this is called an empty String • Every string is an object in Java, defined by the String class
method name Printing Strings println ("Whatever you are, be a good one."); print ("Whatever you are, "); print ("be a good one."); information provided to the method (argument) • The ConsoleProgram class has two methods for printing: • print - no line break • println - inserts a line break • Both accept String arguments
String Concatenation • Concatenation is appending one string to the end of another • "Peanut butter " + "and jelly" • Concatentation can be used to break up a long line • println ("It was many and many a year ago, " +"in a kingdom by the sea, that a maiden there lived…");
The + Operator • Used for concatenation if either or both operandsare Strings • println(“Good ” + 4 + “U”); • Used for addition if both operands are numeric • println(3+6); • Evaluated left to right, but parenthesescan be used to force the order • println(“Hi ” + 2 + 3); • println(“Hi ” + (2 + 3));
Escape Sequences • How would we print the quote (") character? println ("I said "Hi" to you."); • An escape sequence is a series of characters that represents a special character • Begins with a backslash (\) println ("I said \"Hi\" to you.");
Type byte short int long float double Storage 8 bits 16 bits 32 bits 64 bits 32 bits 64 bits Min Value -128 -32,768 -2,147,483,648 < -9 x 1018 +/- 3.4 x 1038 with 7 significant digits +/- 1.7 x 10308 with 15 significant digits Max Value 127 32,767 2,147,483,647 > 9 x 1018 Numeric Primitive Data • The difference between the various numeric primitive types is their size
char • A char variable stores a single character • Characters are delimited by single quotes: 'a' 'X' '7' '$' ',' '\n' • Example declarations: char topGrade = 'A'; char terminator = ';', separator = ' '; Note that a character variable can hold only one character, while a String can hold zero or more characters.
boolean • Abooleanvalue represents true or false • The reserved wordstrue andfalse are the only valid values for a boolean type boolean done = false;
Practice • What data type would you use to store: • A tax rate? • The current year? • Whether or not a customer should receive a discount? • Height?
data type variable name Variables • A variable is a named memory location • A variable must be declared by specifying the variable's name and the type of information that it will hold int count, temp, result; int total; Multiple variables can be declared in one statement
Variable names • May contain letters or numbers, but may not start with a number • you2 - valid • 2you - not valid • May not contain a space or any special characters, except the underscore (_) • why_not - valid • why not? - not valid • Should use camel case • gpa, numCredits, totalClassCount
Variable Initialization Declare the variable Initialize the variable Use the variable • A variable must be initialized before it can be used • intval; • val = 10; • println(val);
Variable Initialization Declare and initialize the variable Use the variable • A variable can be declared and initialized in one statement • intval = 10; • println(val);
Variable Assignment • An assignment statement changes the value of a variable • Read “=” as gets • The value that was in total is overwritten • Most current value of a variable is used • Values assigned to a variable must be consistent with the variable's declared type total = 55; int base = 32; println(base); base = 45; println(base);
String Variables Declare the variable Initialize the variable Use the variable • Strings can be stored in variables just like primitive data types • String name; • name = "Jose"; • println(name);
String Variables Declare and initialize the variable Use the variable • A variable can be declared and initialized in one statement • String name = "Jose"; • println(name);
Practice • Declare a variable to hold a total price • double price; • In two lines, declare and initialize a variable to hold your age • int age; • age = 21; • Declare and initialize a variable to hold your favorite pet • String pet = "alpaca"; • Declare and initialize a character variable to hold your middle initial • char initial = "J"; • Declare and initialize a boolean variable isMarriedto hold your marital status • booleanisMarried = true;
Constants • A constant is similar to a variable except that its value cannot change during program execution • As the name implies, it is constant, not variable • The compiler will issue an error if you try to changethe value of a constant public static final int MIN_HEIGHT = 62;
Why Constants are Cool • Give meaningto otherwise unclear literal values • MAX_LOAD means more than the literal 250 • They facilitate program maintenance • If a constant is used in multiple places, its value need only be updated once • They formally establish that a value should not change, avoiding inadvertent errors
Expressions • Arithmetic expressions use arithmetic operators: Addition + Subtraction - Multiplication * Division / Remainder % • If either or both operandsused by an arithmetic operator are floating point (decimal), then the result is a floating point
Operator Precedence • Operators can be combined into complex expressions result = total + count / max - offset; • Operations have a well-defined precedence • Parentheses • Multiplication (*), division (/), and remainder (%) • Addition and string concatenation (+), subtraction(-) • Assignment (=) • Arithmetic operators with the same precedence are evaluatedfrom left to right
Example answer = sum / 4 + MAX * lowest; 4 1 3 2 The expression is evaluated and the result is stored in the variable on the left hand side
Practice int a=3, b=5, c=2; int answer; • answer = a * b - c; • answer = b + a * c; • answer = b / a; • answer = a / b; • answer = b % a; • answer = a % b; • answer = b - a * b - c; • answer = b - a / c; • answer = (b - a) / c; • answer = a * (b + c);
Increment and Decrement • The increment operator (++) adds one to its operand • The decrement operator (--) subtracts one from its operand • The statement count++;is equivalent tocount = count + 1;
Assignment Operators • Often we perform an operation on a variable, and then store the result back into that variable • Example: • num = num + count; • This can be written using an assignment operator: • num += count;
Operator += -= *= /= %= Example x += y x -= y x *= y x /= y x %= y Equivalent To x = x + y x = x - y x = x * y x = x / y x = x % y Assignment Operators • There are many assignment operators in Java, including the following:
Data Conversion • Sometimes it is convenient to convert data from one type to another • These conversions do not change the type of a variable or the value that's stored in it • They only convert a value as part of a computation • Conversions must be handled carefully to avoid losinginformation
Practice int a=3, b=5, c=2; int answer; • answer = a += b; • answer = b -= c; • answer = a *= c; • answer = a++;
Data Conversion • widening conversions • Go from a small data type to a larger one • Example: short to an int • Safe • narrowing conversions • Go from a large data type to a smaller one • Example: int to a short • Can lose information • Types of conversion • Assignment conversion • Data conversion • Casting byte short int long float double narrowing conversions widening conversions
Assignment Conversion • Assignment conversion occurs when a value of one type is assigned to a variable of another double money; int dollars = 5; money = dollars; • Only widening conversions can happen via assignment • The value and type of dollars did not change converts the value in dollars to a float
Data Conversion • Promotion happens automatically in certain expressions • Example double sum = 5.0; int count = 3; double result = sum / count; countis Temporarilyconverted to a double
Casting • Casting is the most powerful, and dangerous, technique for conversion • May be used for both widening and narrowing conversions • To cast, the type is put in parentheses in front of the value being converted int total=3, count=2; double result = (double)total / count;
iResult = num1 / num4; dResult = num1 / num4; iResult = num3 / num4; dResult = num3 / num4; dResult = val1 / num4; Practice • Given the following declarations, what result is stored in each of the statements? intiResult, num1=25, num2=40, num3=17, num4=5; double dResult, val1=17.0, val2=12.78; • dResult = (double)num1 / num2; • dResult = num1 / (double)num2; • iResult = (int)(val1 / num4); • dResult = (int)((double)num1/num2); • iResult = num3%num4;