Upload
others
View
7
Download
0
Embed Size (px)
Citation preview
Expressions, Data Types, Formatted Printing, ScanningCSC 123Fall 2018
Howard Rosenthal
Lesson Goals
� Review the basic constructs of a Java Program� Review simple Java data types and the operations on those types� Review the concept of casting� Review formatted printing� Understand how to declare and use variables in Java Programs� Review how to formulate assignment statements� Review how to read in data from a terminal
� Using the Scanner object for interactive input
� Compatibility and casting� Note: This is meant to be a quick review, not a complete
“reteaching”. Please ask questions if there is something you don’t recognize or remember.
2
Key Terms and Program Structures
3
public class Hello{
public static void main ( String[] args ){
System.out.println("Hello World!");}
} •Above is a source program (source file) for a Java program. The purpose of this program is to type the characters Hello World! on the monitor.
•The file must be named Hello.java to match the name of the class. The upper and lower case characters of the file name are important.
•Each class is created in it’s own file•A program may consist of multiple classes
•On all computers, upper and lower case inside the program are important. –Java is very case sensitive
•The first line class Hello says that this source program defines a class called Hello.
• A class is a section of a program. Small programs often consist of just one class. Most programs use multiple classes to create objects
•Some classes are are imported while other are created by the programmer
•Every class is contained within a set of braces
Key Terms and Definitions
4
Key Terms and Definitions (2)• When the program is compiled, the compiler will make a file of bytecodes called Hello.class. - This is the file that the JVM uses.
• If the file is named hello.java with a small h it will compile but hello.class won’t exist if the code declares the class with a capital H
• It will create a class Hello.class that will work – but keep it simple and follow the capitalization exactly
• Methods are built out of statements. The statements in a method are placed between braces { and } as in this example.
• A method is a section of a class that performs a specific task• All programs start executing from the main method• Each method is contained within a set of braces
� Braces� For every left brace { there is a right brace } that matches.
� Usually there will be sets of matching braces inside other sets of matching braces. The first brace in a class (a left brace) will match the last brace in that class (a right brace). A brace can match just one other brace.
� Use indenting to show how the braces match (and thereby show the logic of the program). Look at the example. � Increase the indenting by three spaces for statements inside a left and right brace. If another pair of
braces is nested within those braces, increase the indenting for the statements they contain by another three spaces. Line up the braces vertically. � With Notepad++ the indent levels for both braces and parentheses are color coded� After a left brace an indent will be created for you automatically� Make sure that you step back to align your left and right braces� You can also indent when necessary by using the tab key
5
• Most classes contain many more lines than this one. Everything that makes up a class is placed between the first brace { and its matching last brace } .
• The name of the class (and therefore the name of the file) is up to you.• By convention the first letter of a class is typically upper case. If the
class has a compound name each word in the name starts with a uppercase letter i.e. NumberAdder
• A source file always end with .java in lower case. • Therefore the file name is ClassName.java
• In programming, the name for something like a class, a method or a variable is called an identifier. • An identifier consists of alphabetical characters and digits, plus the
two characters '_' and '$' - underscore and dollar sign• The first character must be alphabetical, the remaining characters
can be mixed alphabetic characters and digits or _ or $. • No spaces are allowed inside the name.
• An expression is a sequence of symbols (identifiers, operators, constants, etc.) that denote a value3*(2*x+y)-6*z
Key Terms and Definitions (3)
6
• A reserved word is a word like class that has a special meaning to the system. For example, class means that a definition of a class immediately follows. You must use reserved words only for their intended purpose. (For example, you can't use the word class for any other purpose than defining a class.) Page 25 0f the text lists reserved words
• A statement in a programming language is a command for the computer to do something. It is like a sentence of the language.
• A statement in Java is always followed by a semicolon. • A group of statements within a set of braces is called a block
• We will learn that each block level defines a scope for the variables defined within that scope
• The part "Hello World!" is called a String. A String is a sequence of characters within double quotes. This program writes a String to the monitor and then stops.
Key Terms and Definitions (4)
7
Reserved Keywords In Java
8
abstract assert boolean break byte case
catch char class const* continue default
double do else enum extends false
final finally float for goto* if
implements import instanceof int interface long
native new null package private protected
public return short static strictfp super
switch synchronized this throw throws transient
true try void volatile while
The table below lists all the words that are reserved Java.Notice that all the reserved words are lower case
*Even though goto and const are no longer used in the Java programming language, they still cannot be used as variable names.
Comments
� A single line comment begins with //� This // can come at the beginning of the line or after a
statement on the line :System.out.println("On a withered branch" ); // Write first line of the poem
� Multiline comments begin/* and end *//* Program 1 Write out three lines of a poem. The poem describes a single moment in time, using 17 syllables. */
� It is a good idea to fully comment your program� This includes describing the logic, and defining your
variables� Using descriptive variable names makes this much easier
9
10
Data Types and Operators� A data type is a set of values together with an associated set
of operators for manipulating those values.� Who can think of some basic data types in the numerical
world? The logical world?� When an identifier is used as a variable it always has a
defined data type
� The meaning of the 0’s and 1’s in the computer depends on the data type being represented
� We will begin by defining the eight primitive data types � byte, short, int, long, float, double, char and boolean– all
lower case
11
Data Types and Operators (2)� All data in Java falls into one of two categories: primitive data
types, and reference data types which refer to objects that are created from classes. � There are only eight primitive data types - byte, short, int, long,
float, double, char, and boolean. � Reference data types are memory addresses that refer to objects
� Java has many different classes, and you can invent as many others as you need.
� Much more will be said about objects in future chapters (since Java is a object oriented programming language). The following is all you need to know, for now: � A primitive data value uses a small, fixed number of bytes.� There are only eight primitive data types.� A programmer cannot create new primitive data types.
12
Some Notes on Objects� An object is a big block of data. An object may use many bytes of memory.� An object usually consists of many internal pieces. � The data type of an object is called its class.� Many classes are already defined in Java.� A programmer can invent new classes to meet the particular needs of a
program.� We create classes and access the methods of those classes
� Some classes have static methods that are accessed without creating new objects
� We will see the differences as we move ahead� In CSC 123 we learn how to create separate classes and how to instantiate
objects from those classes
13
There Are Eight Primitive Data Types In Java
14
Primitive Numeric Data Types (1)� Numbers are so important in Java that 6 of the 8
primitive data types are numeric types. � There are both integer and floating point primitive
types. � There are 4 integer data types
� byte – a single byte used for small integers� short – two bytes� int – 4 bytes – all integers are assumed to be of type int � long – 8 bytes – use for very large number
15
Primitive Numeric Data Types (2)� There are two data types that are used for floating point numbers
� float - 4 bytes� double - 8 bytes – this is the default for all floating constants and is used in
almost all cases for floating point arithmetic � Floating point numbers, unlike integers, are not always precise.
� If you compare floating point numbers you can get errors or unexpected results when executing due to the way that they are represented in the computer
� Due to this lack of perfect precision we usually prefer to use double over float for real numbers that aren’t integers, since the precision is greater, although still not perfect.� As we will see shortly, there are casting issues when you mix numbers, especially
with floating point numbers� Java has advanced methods using objects to calculate numbers even more
precisely� This class called BigDecimal is used for very precise monetary and scientific
calculations� In the tables, E means "ten to the power of". So 3.5E38 means 3.5 x 1038
16
Primitive Numeric Data Types (3)� There is a fundamental difference between the the
representations of integers and floating point numbers in the computer. � Integer types have no fractional part; floating point
types have a fractional part. � On paper, integers have no decimal point, and floating
point types do. But in main memory, there are no decimal points: even floating point values are represented with bit patterns.
17
Summary of Primitive Numeric Data TypesInteger Primitive Data TypesType Size Rangebyte 1 byte (8 bits) -128 to +127short 2 bytes (16 bits) -32,768 to +32,767
int 4 bytes (32 bits) -2 billion to +2 billion (approximately)
long 8 bytes (64 bits) -9E18 to +9E18 (approximately)
Floating Point Primitive Data TypesType Size Rangefloat 4 bytes (32 bits) -3.4E38 to +3.4E38double 8 bytes (64 bits) -1.7E308 to 1.7E308
Remember: Integer data types reserve the leftmost bit to indicate positive (0) or negative (1) in two’s complement format
18
In the tables, E means "ten to the power of". So 3.5E38 means 3.5 x 1038
Numeric Operators (1)
Operator Meaning Precedence
- unary minus highest
+ unary plus highest
* multiplication middle
/ division middle
% remainder /modulus middle
+ addition low
- subtraction low
19
Precedence of operators can take the place of parentheses, but just as in algebra, you should use parentheses for clarity.Where there are no parentheses and equal precedence evaluation is from left to right
Numeric Operators (2)� All of these operators can be used on floating point
numbers and on integer numbers. � The % operator is rarely used on floating point. (we won’t be
using it, but the remainder concept would be similar)� When mixing floating point numbers and integer numbers,
floating point takes precedence – this is called casting� An integer operation is always done with 32 bits or more. If
one or both operand is 64 bits (data type long) then the operation is done with 64 bits. Otherwise the operation is done with 32 bits, even if both operands are of a lesser data type than 32 bits. � For example, with 16 bit short variables, the arithmetic is
done using 32 bits:
20
Exponents� There is no exponent operator in java� You can use Math.pow(x,y) to obtain the value of xy
� There is also a special method Math.sqrt(x) to obtain the square of x� Math.sqrt(x) is equivalent to Math.pow(x, .5)
� Math.pow and Math.sqrt both are of type double
21
Arithmetic, Casting, etc.
22
Integer Arithmetic� In integer arithmetic you always truncate
� 7/2 = 3� 11/4 = 2
� The modulus operator gives you the remainder� 7%4 = 3� 9%2 = ?� Any ideas on where the % can be helpful?� Note: In Java the sign of the result of a%b is always the
sign of a (the dividend).
23
Casting� Java is a highly type sensitive language� When evaluating any expression with operands of different types
Java first promotes or casts the operand of the “smaller” data type� By smaller we mean the range� byte is smaller than short which is smaller than int which is smaller
than long which is smaller than float which is smaller than double� boolean expressions are never cast� char automatically casts up to int, not to short
� You can only cast downwards explicitly, otherwise you may create an error
� Example :int a =10; short b =5;a = b; This is casting upwards – it is implicit and automatic b = (short)(a); This is casting downwards – must be explicit
24
Mixing Numeric Data Types (1)� If both operands are integers, then the operation is an
integer operation. If any operand is double, then the operation is double. 7.1+7.4 = 14.5� 7.0+7.4 = 14.4� 7+7.4 = 14.4� (15/2) +7.4 = ?� (15%2) + 7.4 = ?
� The numbers are “casted” upwards� This becomes more important in the next chapter when we
learn about typing variables� Note: Unless otherwise declared all decimals are assumed to be
of type double
25
Mixing Numeric Data Types (2)� Remember that without parentheses you follow the hierarchy
� Mixed integer/decimal addition is cast to decimal when the mixing occurs(10.0+5) = 15.0
10/4*(18.0) = 36.0
(5/9) *(212.0 -32.0) = 0.0
� Note: Integers can be of type byte, short, int, long, but default to int
However you can directly assign an int to a short or byte variable (if it fits with the range) short b =5; works
� Floating point numbers can be of type double or float, but default to double
Example:
float z;
z = 2.0+3.0; this creates an error – Why? Java doesn’t allow the double to cast down because of precision issues
z = (float)(2.0+3.0); - This is correct – we explicitly cast down.
26
Relational Operators
27
Type boolean� Type boolean identifiers can have only one of two values – true or
false. (1 or 0)� A boolean value takes up a single byte.
� There are three operators� && - means and – both operands must be true for the value of
the expression to be true� || - means or – one of the operands must be true for the value of
the expression to be true� ! - means not
p q p&&q (and) p||q (or) !p (not)true true true true falsetrue false false true falsefalse true false true truefalse false false false true
28
Type boolean – Short Circuiting� There are also boolean operators & and |� What’s the difference?
� When you use && or || the compiler is more efficient, it can short-circuit when necessary
� This means that once it determines if a statement is true or false it stops evaluating i.e.:
(true || false) || false – it is evaluated true after the first || is evaluated(true && false) && true – same idea, but evaluates as false after first &&
� So when is there a problem:� If you try to assign a logical value (allowed) this might not take place
if there is short circuiting:� (true || false) || (a= true) – a doesn’t get assigned the value true (a=
true) is allowed as the expression evaluates as true� (true | false) | (a= true) – a does get assigned the value true
� Don’t use these types of assignment statements inside of boolean statements – it will inevitably lead to errors
29
Relational OperatorsOperator Description Example (with A=2, B=5
==Checks if the value of two operands are equal or not, if yes then condition becomes true.
(A == B) is not true.
!=Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. (A != B) is true.
>Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.
(A > B) is not true.
<Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. (A < B) is true.
>=Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.
(A >= B) is not true.
<=Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.
(A <= B) is true.
� The result of applying a relational operator is a true or false value
30
Operator HierarchyPriority Operators Operation Associativity
1[ ] array index
left() method call. member access
2
++ pre- or postfix increment
right
-- pre- or postfix decrement+ - unary plus, minus~ bitwise NOT! boolean (logical) NOT(type) type castnew object creation
3 * / % multiplication, division, remainder left
4+ - addition, subtraction
left+ String concatenation
5<< signed bit shift left
left>> signed bit shift right>>> unsigned bit shift right
6< <= less than, less than or equal to
left> >= greater than, greater than or equal toinstanceof reference test
7 == equal to left!= not equal to
8& bitwise AND
left& boolean (logical) AND
9 ^ bitwise XOR left^ boolean (logical) XOR
10| bitwise OR
left| boolean (logical) OR11 && boolean (logical) AND left12 || boolean (logical) OR left13 ? : conditional right
14
= assignment
right
*= /= += -= %= <<= >>= >>>= &= ^= |=
combinated assignment
• The hierarchy is very similar to what you know from algebra
• When there is an equivalent hierarchy level and no parentheses you evaluate from left to right
• When in doubt use parentheses
31
Some Extra Examples� 5>4 – true� 4>5 – false� (5>4) || (4>5) - ?� (5>4) && (4>5) - ?
32
Another ExampleEvaluate as true or falsetrue || false && 3 < 4 || !(5==7)(true || (false && (3 < 4))) || !(5==7) – putting in the parentheses correctly always helps(true || (false && true)) || !false(true || false)|| truetrue || truetrue
33
34
Type char� Type char is the set of all characters found on the standard keyboard, and
thousands of other characters as well. � char is a primitive data type� Type char is denoted using single quotes� ‘A’ , ‘5’� Java uses Unicode – 2 byte representations that increases the number of
characters that can be represented from 127 to 32,767� unique characters –in actuality only 7 bits are used for ASCII characters and 15
bits are used for two byte Unicode, the leftmost bit is always zero.� Note: Keyboard letters in ASCII Code and Unicode have the same value – i.e. ‘A’ = 65
i.e. 01000001 in ASCII or 0000000001000001 in Unicode
� You can add and subtract type char – they are actually treated like integers when adding� i.e. ‘A’ +1 = 66 0r 0000000001000010 - char would automatically cast up to int
� You could cast back down to char by saying (char)(66) which yields ‘B’� They are added as type int – 4bytes – to accommodate all Unicode characters
� The most common characters and their Unicode values are found in Appendix B� You can also compare type char values – they compare based on their ASCII value
� (‘A’ < ‘B’) would evaluate as true
35
String� String is a class in Java with lots of different methods that allows you to
manipulate them� An individual String is an object, not a basic data type.� A String is a sequence of characters enclosed in double quotes
� Java provides a String class and we can create String objects� Why does String have a capital S while primitive data types have lower
case first letters – String is the name of a class� Strings can be concatenated
� “I am” + “ a man” would evaluate as “I am a man”� Strings and values
� Everything depends on the order� “The sum of two numbers is ” + (5*2) prints as The sum of two numbers is 10Why? You always work from inside the parentheses outwards� However (“The sum of two numbers is 5”) + 2 prints asThe sum of two numbers is 52
� In Chapter 9 we do a lot more with String objects
36
Casting With Strings and Characters‘A’ + ‘B’ = 131 (integer)‘A’ + “B” = AB (String)“A” + “B” = AB (String)“” + ‘A’ + ‘B’ = AB (String) – ‘A’ gets cast to String‘A’ + ‘B’ + “” = 131 (String)3 + 4 + “” = 7 (String)“” + 3 + 4 = 34 (String)
Key is that without parentheses we are reading left to right
37
38
Printing and Special Characters� The System.out object is a predefined instance of a class called PrintStream,
and is included with the basic java.lang and therefore is always available for use. � It is called the standard output object, and prints to the terminal� We will learn how to print to other File objects later in this term
� We will be using several basic static methods from this class� System.out.println(“abc”) // prints the String and a character return � System.out.print (“abc”) // prints a String without a character return
� Escape sequences inside the String can be used to control printing
Escape Sequence Character
\n newline
\t tab
\b backspace
\f form feed
\r return
\" " (double quote)
\' ' (single quote)
\\ \ (back slash)
\uDDDD character from the Unicode character set (DDDD is four hex digits) – used when the character isn’t available during input
39
Printing Examplepublic class PrintAPoem
{
public static void main (String[] args)
{
System.out.println (“He wrote his code”);
System.out.print(“\tHe indented well\n”);
System.out.println(“\tTill he was done”);
System.out.print(“\nThe Author\n”);
}
}
He wrote his code
He indented well
Till he was done
The Author
40
System.out.println(concatenated String) – prints and goes to the next lineSystem.out.print(concatenated String) – prints and stays on the same line
Printing Example – Concatenation in Print Statements� When you write expressions in a System.out.println() statement
the expression may or may not be calculated first, depending on if and where you put the parentheses� The rules are exactly the same as used when concatenating String(s)� Ultimately the println method will output a single String
public class PrintingNumbers //Class name{
public static void main ( String[] args ) {
System.out.println("The sum of 5 + 6 is " + (5+6));System.out.println("The sum of 5 + 6 is " + 5+6);System.out.println("The sum of " +5 +" + " +6 + " is " +(5 + 6));
} }
41
Formatted Printing with printf (1)
� For simple formatted outputs, each format parameter aligns to the subsequent variable or constant after the String
� It is possible to more clearly format your output with the printf method� Width, precision, leading blanks, signs, etc. can all be controlled
� The printf method has a String followed by a number of primitive or object variables to be printed� You can also specify formatting a geographic area, but we’ll ignore
that for now
� Please use printf as opposed to println and print in this class to the greatest extent possible
� Nice referencehttp://www.java2s.com/Tutorial/Java/0120__Development/UsingJavasprintfMethod.htm
42
Formatted Printing with printf (2)System.out.printf(“ characters %format1 characters %format2 characters %format3”, varorconst1, varorconst2, varorconst3);
� The first parameter is a String (in double quotes) that lays out the sentence and format for each variable, and includes special control characters
� There is a one to one mapping of format to variable� The variable must match the format type� Example� System.out.printf(“The average of %,d students taking %d exams is %3.2f\n”, 1250, 4,
78.655); // prints out as:
The average of 1,250 students taking 4 exams is 78.66
� Each format specification begins with % and ends with the format specifier type (see next page)
43
Some Key Conversion Character Specifiers For Formatted OutputSpecifier Name Example%b or %B boolean false or FALSE%c or %C character f or F%d decimal integer 189%e exponential floating 1.59e+01%f Floating point number 15.9%s or %S String if “Java” Java or JAVA%x or %X Hexadecimal integer 1f2a or 1F2A%% The percent symbol %
44
• We will also learn several other important elements• Flags – for left justified, etc.• Width - specifies the field width for outputting the argument and represents the minimum number of
characters to be written to the output• Precision - used to restrict the output depending on the conversion and specifies the number of digits
of precision when outputting floating-point values.
Important Control Characters
Control Character
Name
\n new line\t tab\\ Prints \
45
• Always placed inside the String
Controlling Integer Output With printf� The %wd means reserve a minimum of w spaces, right
justified� The – in %-wd means left justified� The 0 in %0d means left fill with 0’s� The + in %+d means add a positive sign for positive
numbers� A ( encloses a negative number in parentheses� A , is used as a group separator (may work differently
outside of U.S.)
See Printf1.java46
Simple Formatted Output With Decimals� For simple formatted outputs, each format parameter aligns to the subsequent variable or
constant after the String
public class Printf2{public static void main(String[] args) {double x = 27.5, y = 33.75;System.out.printf("x = %f y = %f\n", x, y);
}}
Output: x = 27.500000 y = 33.750000
47
Controlling Formatted Outputs With Decimals� Uses the same formatting structures as integers
� Adds the ability to specify the number of decimal places to the right of the decimal point, as opposed to printing a minimum of a default 6
� %w.nf has a minimum width of w and n decimal places
� %#w.nf – the # guarantees a decimal point
� Variable associated with f must be of type double or float - it won’t cast up any type of integer
� Note: On some machines it may not do a perfect job in rounding as it uses bankers rounding� Bankers Rounding is an algorithm for rounding quantities to integers ,
in which numbers which are equidistant from the two nearest integers are rounded to the nearest even integer.
� Thus, 0.5 rounds down to 0; 1.5 rounds up to 2.
� It has been extended to be used at any level of precision� 1.685 would print to two places as 1.68 while 1.675 would also round to two places
as 1.68
�See See Printf3.java48
Controlling Other Formatted Outputs (1)� Strings with %-ws
� - will left justify� w specifies width� s is for a String� If s is capitalized then the entire String prints capitalized� We will learn how to use String variables later this semester
� Same rules apply for c (char) and b (boolean)
�See Printf4.java
49
Formatted Printing With printf – Putting It All Together (1)
See Printf5.java
50
51
•A variable (either primitive or a reference) is a named memory location capable of storing data of a specified type• Variables indicate logical, not physical addresses – Those are taken care of in
the JVM and the OS•Variables in Java always have a specific data type•Variables must always be declared before they can be used• Remember that a data type is a scheme for using bit patterns to represent a
value or a reference. Think of a variable as a little box made of one or more bytes that can hold a value using a particular data type.
What is a Variable
52
double Cost_of_Home
128,695.22
• A declaration of a variable is made if a program requires a named variable of a
particular type
• Three things happen• The variable is named with an identifier
• The amount of space required for the variable is defined• How the bits in that space are interpreted is defined
• The value of a variable is always its last declared or assigned value in a program
public class Example1_CH3
{ public static void main ( String [] args )
{
long payAmount; //the declaration of the variable payAmount = 123; // variable assignment
System.out.println("The variable payAmount contains: " + payAmount); payAmount = -8976; // variable reassignment
System.out.printf("The variable payAmount contains: %d\n”,payAmount);
} }
What is a Variable (2)
53
Declaring Variables� Variables must be declared before they are used
� Basic syntax:
Type name1, name2, name3 …;� Example:
double dinner_Bill, creditBalance, moneyInBank;//three variables of type
double
� Variables can be explicitly initialized when they are declared
short rent = 75;
double milkPrice_Half = 1.99;
boolean testimony = true;
� Can’t do multiple assignments at once when declaring variablesint x=y=z=0; // Incorrect syntax
int x,y,z=60; // only z is initialized, but good syntax
int x=60, y=60, z=60; //all three are initialized, good syntax
� Don’t try to assign a value that that is illegal
short big_number = 250000;
� This gives an error – why?
54
Naming Variables (1)� Use only the characters 'a' through 'z', 'A' through 'Z', '0' through '9', character
'_', and character '$'. � Just like any other identifier
� A variable name cannot contain the space character.
� Do not start with a digit� A variable can be any number of characters
� Java is case sensitive. Upper and lower case count as different characters SUM and Sum are different identifiers
� A variable name cannot be a reserved word
� Don’t use the same name twice, even as different types – it will generate an error during compilation
� Programmers should follow the good practice of creating meaningful identifier names that self-describe an item's purpose� Meaningful names make programs easier to maintain
� userAge, houseSquareFeet, and numItemsOnShelves
� Good practice minimizes use of abbreviations in identifiers except for well-known ones like num in numPassengers
� Abbreviations make programs harder to read and can also lead to confusion, such as if a chiropractor application involves number of messages and number of massages, and one is abbreviated numMsgs (which is it?)
55
Naming Variables (2)� There are certain conventions used by java
programmers� Variables and methods start with a lower case letter with
the exception of final variables (slide 59)� i.e. var1, interest
� Multiword variables capitalize the first letter of subsequent words� i.e. interestRate, milesPerHour
� Names of classes by convention begin with a capital letter� i.e. Calculator, MyProgram
56
Assigning Variables� Assignment statements look like this:
variableName = expression ; //The equal sign = is the assignment operator
� variableName is the name of a variable that has been declared previously in the program.
� Remember: An expression is a combination of literals, operators, variable names, and parentheses used to calculate a value – must be syntactically correct
� Assignment is accomplished in two steps:
� Evaluate the expression
� Store the value in the variable which appears to the left of the = sign
� Examples :
int total;
double price, tax;
total = 3 + 5; // total =8
price = 34.56; tax = price*0.05; //tax = 1.728
� While you can’t do a multiple assignment in a declaration statement , you can do multiple assignments once the variables have been declared:
int x,y,z; //declaration of the variables
x=y=z=0; // works as an assignment statement provided the variables have been declared previously –these work right to left
int x=y=z=3; // This will generate a syntax error because you are first declaring the variables here
These two statements also work:
int x,y,z;
x=y=z=14+5; // First calculate the value of the expression, then do the assignments
Only rightmost part in multi-assignment can be an expression, all the rest must be variables
57
Assigning Variables (2)� Primitive variables must be initialized before they are
used� They aren’t given a default value� They are typically initialized by reading in a value� You can also explicitly initialize in the code
int value; value = value + 10; // this gives an error as value wasn’t
initialized
58
final Variables� final variables are really constants
� They are assigned a value that doesn’t change
final double PI = 3.14159;
final int PERFECT = 100;
� final variables are by convention written with all capitals
� It is legal to defer initialization of a final variable, provided that
it is initialized exactly once before it is used for the first time
boolean leapYear =true;
final int DAYS_IN_FEBRUARY;
if (leapYear)
DAYS_IN_FEBRUARY= 29;
else
DAYS_IN_FEBRUARY= 28;
59
An Example of a Simple Program (1)� The Fibonacci sequence is 1,1,2,3,5,8,13,21,34,55….
� The next number is the sum of the previous two numbers.
Pseudocode for printing Fibonacci series up to 50
Set the low number =1
Set the high number equal to 1
Print the lowStart of Loop – check that high is less than 50
Print the high
Set the high equal to the low+high
Set the low equal to the high -low
Repeat loop
60
An Example of a Simple Program (2)public class Fibonacci { // Print out the Fibonacci sequence for values < 50
public static void main(String[] args) {
int lo = 1; int hi = 1; System.out.printf(“%d\n”,lo); while (hi < 50) {
System.out.println(hi); hi = lo + hi; // new hi lo = hi - lo; /* new lo is (sum - old lo) i.e., the old hi */
}}
}
61
Note: also look at Fibonacci2.java
62
Obtaining Input Data Using Scanner� Scanner is a class.� You must include the following statement to use the class to create a Scanner
object:import java.util.Scanner; or import java.util.*;� You are importing a class with all it’s methods that can then be used to create
objects� Declare a Scanner object variable and create an object:Scanner scannerName = new Scanner (System.in);
� new means you are creating a new object – new is a reserved word� System.in is a variable that tell the Java program that this input stream is
coming from the keyboard� You can now access seven types of primitive input: byte, short, int, long,
double, float and boolean using predefined methods associated with the Scanner class� A Scanner object doesn’t read characters
� We will learn a way around this when we study the String object� The scannerName is just another variable name
� It contains an address which refers to the Scanner object you have created
63
There are 7 Input Methods Available For Primitive Data TypesScannerName.nextByte()ScannerName.nextShort()
ScannerName.nextInt()
ScannerName.nextLong()
ScannerName.nextDouble()
ScannerName.nextFloat()
ScannerName.nextBoolean()
Note: the type names are capitalized in these methods
Note: There is no way to directly input a char with a Scanner object
What you are looking at above is the standard way objects access methods:
objectname.method(par1, par2, …)
- There are no parameters required for the Scanner methods
64
Each Scanner Object Is Created From The Scanner Class
65
Name0f input file(System.in)
Constructor –used to create objectMethodsnextByte()nextShort()nextInt()nextLong()nextFloat()nextDouble()nextBoolean()next()nextLine()hasNext()
o00
keyboard
An Example Showing Scanner Usageimport java.util.Scanner;
public class ScannerUsage
{
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in); // Creates a new Scanner called keyboard
System.out.println("Enter an integer of type int");
int n1 = keyboard.nextInt();
System.out.printf("Enter an integer of type byte\n");
byte b1 = keyboard.nextByte();
float f1;
double d1;
long l1;
short s1;
boolean bn1;
System.out.println("Enter a floating point of type float");
f1 = keyboard.nextFloat();
System.out.printf("Enter a floating point of type double and Enter an integer of type long\n");
d1 = keyboard.nextDouble();
l1 = keyboard.nextLong();
System.out.printf("Enter an integer of short int and Enter boolean value\n");
s1 = keyboard.nextShort();
bn1 = keyboard.nextBoolean();
System.out.println("n1 = " + n1 +"\nb1 = " + b1 + "\nf1 = " + f1 + "\nd1 = " + d1);
System.out.printf("l1 = %d\ns1 = %d\nbn1 = %b\n”, l1, s1, bn1);
}
}66
A Practical Example Using Scannerimport java.util.Scanner; // Make the Scanner class available.public class Interest2WithScanner {
public static void main(String[] args) {
Scanner keyboard = new Scanner( System.in ); // Create the Scanner. double principal; // The value of the investment. double rate; // The annual interest rate. double interest; // The interest earned during the year. System.out.printf("Enter the initial investment: "); //always ask for an input with a questionprincipal = keyboard.nextDouble(); System.out.printf("Enter the annual interest rate as a percent"); rate = keyboard.nextDouble(); rate = rate/100;interest = principal * rate; // Compute this year's interest. principal = principal + interest; // Add it to principal. System.out.printf("The value of the investment after one year is $ %.2f\n”, principal);
} } // end of class Interest2withScanner
67
68
Casting (1)� The value of a smaller numerical type may be assigned to a higher numerical data type
automatically� Do you know the order?
� Casting down must be done explicitlyExample:int natural, bigger;double odds, otherNumber; odds = 20.3;natural = 5;
otherNumber = (int)(odds)*natural;bigger = (int)otherNumber;System.out.printf(“%.1f\n”,otherNumber); //prints 100.0System.out.println(bigger); //prints 100
otherNumber = odds*natural;bigger = (int)otherNumber; System.out.printf(“%.1f\n”,otherNumber); //prints 101.5System.out.println(bigger); //prints 101
69
Casting (2)
� Remember that float is a special case that always requires casting if you are assigning a floating point number to a float variablefloat x = 15.0; //This creates an errorfloat y = (float)15.0; //This is proper explicit castingfloat z = 15; //Implicit casting
70
Casting (3)� Character data may be assigned to any of the types short,
int, long, double or float� When this happens the ASCII/Unicode value is assigned to
the numerical valuedouble x = ‘A’;System.out.printf(“%.1f”, x);The output is 65.0 – Why?
However,char chm =‘A’;System.out.printf(“%c”, chm);The output is A
71
Shortcuts
Operator Shortcut For
+= x+=10 x=x+10
-= x-=10 x=x-10
*= x*=10 x=x*10
/= x/=10 x=x/10
%= x%=10 x=x%10
72
Prefix and Postfix for Incrementing and Decrementing (1)
� There are two mechanisms for adding or subtracting 1 from a variable� ++number; //prefix form for adding 1 to number� --number; //prefix form for subtracting 1 from number� number++; //postfix form for adding 1 to number� number--; //postfix form for subtracting 1 from number
� What’s the difference?� In assignment statements prefix action takes effect before the
assignment� In assignment statements postfix action takes effect after the
assignment
73
Prefix and Postfix for Incrementing and Decrementing (2)
Prefix Incrementing Postfix Incrementing
int number =5,result;
result = 3*(++number);
System.out.printf(“%d\n”, result);
18
System.out.println(number);6
int number =5,result;
result = 3*(number++);
System.out.printf(“%d\n”, result);
15
System.out.println(number);6
74
Use postscript incrementing carefully, it can be confusingHowever, it is very useful when dealing with loops
Prefix and Postfix for Incrementing and Decrementing (3)
� Here is what happens in a postfix in prior exampleresult = 3*(number++);a. temp = number; // a hidden temp is created by the
compilerb. number = number +1;c. result = 3*temp;What is the value printed in the following example;int number =10;number = number++; System.out.printf(“%d\n”, number);
75
76
Programming Exercise 1Exercise 6. Triangle1StarsWrite a program that prints the triangle:
*********************
Use this framework:
public class Pname //Class name{
public static void main ( String[] args ) //main method header{
Code goes here //Body}
}
Compile with javac Pname.javaExecute with java Pname once you compile successfully
77
Programming Exercise 2Exercise 2. Uptime
The uptime command of the UNIX operating system displays the number of days, hours and minutes since the operating system was started. For example the UNIX command uptime might return the string
Up 53 days 12:39. Write a program that converts the 53 days, 12 hours and 39 minutes to the number of seconds that have elapsed since the operating since was last started.
78
Programming Exercise 3
CharSum� Write a program that that prints out your initials and the
prints out the sum of the ASCII values for the following character sets:
N T CA FG� The output will look as follows:HGRNTC 229AF 135G 71
79
Programming Exercise 4AreaWrite a program that prompts a user for the dimensions (double) of a room in feet (length,
width, height) and calculates and prints out the total area of the floor, ceiling and walls.
80