Chapter 2 Notes

advertisement
Day #2 Basic Java
2. 2 Writing Simple Programs: Area of a circle
public class ComputeArea
{
public static void main(String[] args)
{
double radius;
double area;
radius = 20;
area = radius * radius * 3.14159;
System.out.println ("Area: " + area);
}
}
Assignment statements
Assignment statements in Java are similar to assignment statements in other languages.
Syntax:
<variable> = <expression>
Output
Output to the console uses the System.out object and print, println, or printf methods. The
argument to print/println must be a single string. It is not necessary to change numbers to
strings like it is in C#. Java does it for you.
2.3 Reading Input from the Console
The monitor is System.out in Java. The keyboard is System.in.
We can use the Scanner class to create an object that can read from the System.in device
(the keyboard). To create a Scanner object:
Scanner input = new Scanner (System.in);
Some useful methods of the Scanner class:
nextInt();
nextDouble();
nextLine();
character
//reads an int
//reads a double
//reads a string that is terminated by a newline
Example (listing 2.2)
package computeareawithconsoleinput;
import java.util.Scanner;
public class ComputeAreaWithConsoleInput
{
public static void main(String[] args)
{
Document1
1 of 9
3/21/2016
Scanner input = new Scanner (System.in);
System.out.print ("Enter a number for radius:");
double radius = input.nextDouble();
double area = radius * radius * 3.14159;
System.out.println ("Area: " + area);
}
}
Example (listing 2.3)
package computeaverage;
import java.util.Scanner;
public class ComputeAverage
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print ("Enter 3 numbers:");
double number1 = input.nextDouble();
double number2 = input.nextDouble();
double number3 = input.nextDouble();
double average = (number1 + number2 + number3) / 3;
System.out.println ("Average is: " + average);
}
}
Document1
2 of 9
3/21/2016
3.16 Formatting Console Output
To get formatted output, use the System.out.printf method. The "f" stands for "formatted".
The syntax is:
System.out.printf(formatString, item1, item2, …);
The formatString consists of a string that has format specifiers embedded in it. A format
specifier begins with a percent symbol (%). Some common format specifiers:
%b
a boolean
%c
a character
%d
a decimal integer
%f
a floating point number
%s
a string
Examples
int count = 5;
int amount = 45.56;
System.out.printf("Count is %d and amount is %f", count, amount);
The output is:
Count is 5 and amount is 45.560000
You can also use printf to control the number of decimal places that are displayed:
double x = 2.0 / 3;
System.out.printf("x is %4.2f \n", x);
The 4 is the field width (including the decimal point) and the 2 is the number of decimal
places. The "\n" moves the cursor to the beginning of the next line before the "BUILD
SUCCESSFUL" message is displayed in the output window. The output is:
x is 0.67
To print a percent sign, do this:
double rate = 0.205; // 20.5%
System.out.printf("Rate is %6.2f%%\n", rate*100);
2.4 Identifiers (see above)
2.5 Variables (see above)
2.6 Assignment Statements and Assignment Expressions
The assignment statement syntax:
<variable> = <expression>;
Java is strongly typed. The data type of the expression on the right must match the data
type of the variable on the left. Expressions will be covered below.
Document1
3 of 9
3/21/2016
2.7 Named Constants
Named constants in Java are, by convention, named using upper-case letters, with
underscores separating the words. To declare a constant in Java, use the reserved words
static and final in the declaration, AND declare it outside of any method.
static means that there is only one instance per class.
final means that it cannot be changed.
public static final double TAX_RATE = 0.05;
putlic static final double PI = 3.14159;
Convention: Use upper-case letters for constant names. Use underscores to separate words.
2.8 Naming Conventions
1. Use lower-case letters to begin names of variables and methods.
2. Use an upper-case letter to begin the name of a class.
3. Use all caps for constants.
2.9 Numeric Data Types and Operations
Integer types:
 byte
 short
 int
 long
Floating point types:
 float
 double
We will always use int and double unless there is a good reason for doing otherwise.
See what happens when you enter numbers that are outside the range of an integer data
type:
byte b = (byte) 255;
b++;
b++;
System.out.println(b);
double d = 1.0e300;
d = d * d;
System.out.println(d);
Numeric operators
Operators are: + - * / %
If both operands are integer types when doing division, the result will be an integer, not a
double!
Try this (in sample program RoundOffErrors):
System.out.println (1.0 - 0.1 - 0.1 - 0.1 - 0.1 - 0.1);
System.out.println (1.0 - 0.9);
Document1
4 of 9
3/21/2016
The first println gives 0.5000000000000001!
The second one gives 0.09999999999999998!
Why does this happen? The decimal value one-tenth is computed in binary like this: 1/1010,
which gives:
.00011001100110011
with the 0011 repeating forever. Many numbers that are terminating decimals in base 10
are not terminating in base 2.
2.10 Numeric literals
Integer literals
Numbers without a decimal point are considered to be of type int. Therefore, this is illegal:
byte b = 255; // converting int to byte!
You have to explicitly convert to a byte:
byte b = (byte) 255;
And you can't do this(!):
long m = 3333333333; //bigger than max int!
You have to make the 3333333333 into a long like this:
long m = 3333333333L;
You can also use hexadecimal constants if you prefix them with 0x:
System.out.println (0xFFFF);
Floating Point literals
Floating point constants are assumed to be of type double. Therefore this is illegal:
float f = 1.5;
You have to explicitly make the constant a float:
float f = 1.5f;
Or use type casting:
float f = (float) 1.5;
2.11 Evaluating Expressions and Operator Precedence
Java binary arithmetic operators:
 Addition: +
 Subtraction:  Multiplication: *
 Division: /
 Mod: %
Precedence
The precedence rules are pretty much what you would expect, but when doubt, use
parentheses!
Document1
5 of 9
3/21/2016
Note about the mod operator
In some languages, the mod operator only works on integers. In Java, it works on floating
point types as well, and it simply does the division and gives you the remainder.
Example:
12.5
12.5
13.5
13.5
13.6
%
%
%
%
%
2 gives .5
2.5 gives 0
2 gives 1.5
2.5 gives 1
2.5 gives 1.0999999999999996!!!
2.12 Displaying the current time (see book)
2.13 Arithmetic/Assignment shorthand operators
Operator
Use
Description
+=
a += 10;
a = a + 10;
-=
a -= 10;
a = a – 10;
*=
a *= 10;
a = a * 10;
/=
a /= 10;
a = a / 10;
%=
a %= 10;
a = a % 10;
2.14 Increment and Decrement operators:
 ++ (both pre- and post-)
 -- (both pre- and post-)
I recommend that you do not use the increment or decrement operators in anything other
than a stand-alone increment or decrement, like this:
count++;
But do not do this:
x = y++;
Operator Use
Description
++
op++
Increments op by 1; evaluates to the value of op before it was
incremented
++
++op
Increments op by 1; evaluates to the value of op after it was
incremented
--
op--
Decrements op by 1; evaluates to the value of op before it was
decremented
--
--op
Decrements op by 1; evaluates to the value of op after it was
decremented
Document1
6 of 9
3/21/2016
Shift and Logical Operators
Each shift operator shifts the bits of the left-hand operand over by the number of positions
indicated by the right-hand operand. The shift occurs in the direction indicated by the
operator itself.
Operator
Use
Operation
>>
op1 >> op2
Returns the bits of op1 right-shifted by distance op2
<<
op1 << op2
Returns the bits of op1 left-shifted by distance op2
>>>
op1 >>>
op2
Returns the bits of op1 right-shifted by distance op2
(unsigned)
These operators perform logical functions on their operands.
Operator
Use
Operation
&
op1 & op2 bitwise and
|
op1 | op2
^
op1 ^ op2 bitwise xor
~
~op2
bitwise or
bitwise complement
2.15 Numeric Type Conversions
Type casting is the same as in C#.
2.16 Software Development Process: Computing Loan Payments (see book)
2.17 Character Data Type and Operations
Java stores characters as Unicode characters: 16 bits per character. The ASCII code is a 7
(or 8) bit subset of Unicode. Character constants are enclosed in single apostrophes: 'a'.
Java allows you to increment characters:
char ch = 'a';
ch++;
System.out.println (ch); // b
You can also do arithmetic, but must use type casting to convert from int back to char.
char c = 'x';
c = (char)(c + 2);
System.out.println (c); // z
Document1
7 of 9
3/21/2016
Escape Sequences
An escape sequence is a special sequence of characters that begins with the backslash
character (\).
To insert a special character in a string, use an "escape" sequence:
\"
double quotes (to embed in a string)
\u0022
\'
single quotes (to embed in a char)
\b
backspace
\u0008
\\
backslash
\u005C
\n
linefeed
\u000A
\r
carriage return
\u000D
\t
tab
\u0009
\f
formfeed
\u000C
2.17.4 Problem: Counting Monetary Units (see text)
2.18 The String Type
Syntax:
String firstName = "George";
The characters in a string are numbered beginning with 0.
The concatenation operator: +
To read a string using a Scanner object:
Scanner input = new Scanner(System.in);
System.out.println ("Enter a string: ");
String s = input.nextLine();
System.out.println ("Your string is: " + s);
If you add the above lines to a program that has done previous input with nextInt or
a similar method, you will find that it just gives you an empty string!
The reason is that the statement:
String s = input.nextLine();
is reading the line newline character from the last integer that you typed in! So you
need to add the following before you try to read the string. It will consume the
newlien that has already been typed:
input.nextLine();
Document1
8 of 9
3/21/2016
Some useful String methods (assumes that firstName = "George"):
Method
Example
Return value
length()
firstName.length()
// returns 6
indexOf("pattern")
firstName.indexOf("or")
// returns 2
(counting begins
with 0, not 1!)
charAt(psn)
firstName.charAt(3)
// returns "r"
toLowerCase()
firstName.toLowerCase()
// returns "george"
toUpperCase()
firstName.toUpperCase()
// returns "GEORGE"
trim()
firstName.trim()
//returns "George"
with leading and
trailing blanks
removed
compareTo
(otherString)
firstName.compareTo("Bob")
equals
(otherString)
firstName.equals("Bob")
Document1
//returns negative integer if less than, 0 if
equal, positive number if greater than, so this
will return a negative number
9 of 9
//returns false
3/21/2016
Download