Introductory Java Language Features
2021년 8월 30일 월요일 오후 1:22
Introductory Java Language
-Packages and classes
-Types and identifies
-Operators
-Input/Output
-Control structures
-Errors and exceptions
Types and Identifiers
Identifier: A number of for a variable, parameter, constant,user-defined method, or user defined class.
Build-in Types
int: An integer, 2, -26, 3000
boolean: true or false
Double
One type can be cast to another compatible type if appropriate
int total n;
double average;
…
average = (double) total / n; //total cast to double to ensure
//real division is used
Alternatively
average = total / (double) n;
Assigning an int to a double automatically casts the int to double.
int num = 5;
double realNum = num; //num is cast to double
Assigning a double to an int without a cast, however, causes a complie-time error
double x = 6.79;
int intNum = x; //error
Note that casting a floating-point(real) number to an integer simply truncates the number
double cast = 10.95;
int numDollars = (int) cast; //sets num Dollars to 10
If your intent was to round cost to the nearest dollar, you needed to write
int numDollars = (int) (cost + 0.5);
To round a negative number to the nearest integer
double negAmount = -4.8;
int roundNeg = (int) (negAmount - 0.5); //-5
Storage of Numbers
-Differences between types int and double
Integers
-stored exactly, as a string of bits
-0 for positive, 1 for negative
-one type (eights bits) of storage
01111111
0 represents the largest positive integer than can be stored using type byte: 2^7-1
One bype: 8bits
Ex)32bits
-four bype
2^31-1. Integer. MAX_VALUE
-2^31. integer.MIN_VALUE
Final variables
final (value will not change)
final double TAX_RATW - 0.08;
final int CLASS_SIZW = 35;
Note
1. Constant identifies are, by convention, capitalized.
2. A final variable can be declared without initializing it immediately.
final double TAX_RATW;
if(<some condition>)
TAX_RATE = 0.08;
else
TAX_RATE = 0.0;
//TAX_RATW can be given a value just once; its value is final
3. A common use for a constant is an array bound.
final int MAXSTUDENTS = 25;
AP 페이지 1
final int MAXSTUDENTS = 25;
int [] classList = new int [MAXSTUDENTS];
4. Easier to revise code
Operators
Arithmetic Operators
+
-
*
/
% (remainder)
(int) 3.0 / 4 = 0
(double) 3/4 = 0.75
Be careful
(double) (3/4) = 0.0 // 3/4 is first
Relational Operators
== equal to if (x == 100)
!= not equal to if (x != 21)
> greater than if (salary > 3000)
< less than if (salary < 65)
>= greater than or equal to if (age >= 16)
<= less than or equal to if (height <= 16)
Note
1. Relational operators are used in boolean expressions that evaluate ot true or false
boolean x = (a != b); //initializes x to true if a != b,
//false otherwise
return p == q; //returns true if p equals q, false otherwise
2. If the operands are an int and a double, the int is promoted to a double as for arithmetic operators
Optional topic (Comparing Floating-Point Numbers)
|x - y| / max(|x|, |y| <= e
To avoid problems with dividing by zero, code this as
|x - y| < Σ(|x|, |y|)
Logial Operators
A logical operator (boolean operators) is one that returns a boolean result that is based on the boolean
result of one or two other boolean expressions.
! Not if (!found)
&& And if (x < 3 && x >4)
|| Or if (age < 2 || height < 4)
Assignment Operators
= x=2 x=2
+= x += 4 x=x+4
-= x -= 6 x=x-6
*= x *= 5 x=x*5
/= x /= 10 x = x / 10
%= x %= 10 x = x % 10
1. All these operators, with the exception of simple assignment are called compound assignment
operators
2. Changing of assignment statements is allowed, with evluation from right to left
int next, prev, sum;
next = prev = sum = 0; //initializes sum to 0, then prev to 0
//then next to 0
Increment and Decrement Operators
++ i++ or ++i i is incremented by 1
-- k-- or --k k is decremented by 1
Operators Precedence
first to last
!, ++, --
*, /, %
+, -
<, >, <=, >=
==, !=
&&
AP 페이지 2
&&
||
=, +=, -=, *=. /=, %=
Input / Output
input
double x = call to method that reads a floating-point number
or
double x = …, // read user input
Note
The scanner calls simplifies boht console and file input. It will not, howeverm be tested on the AP exam.
output
restricted to [Link] and [Link]
The println method outputs an item and then goes to a new line.
The print method outputs an item without going to a new line afterward.
Escape Sequences
\n new line
\" double quote
\\ backslash
[Link] ("Welcome to \na new line") ;
prints
Welcome to
a new line
[Link] ("He is known as \"Hothead Harry\" . ") ;
prints
He is know as "Hothead Harry" .
[Link] ("The file path is d: \\myFlies\\..") ;
prints
The file path is d: \myflies\..
Control Structures
-the method by which you make the statements of a program run in a nonsequenttial order
-decision - making
-iteration (반복)
Decision-Making Control Structures
-if, if...else, switch
The if statement
if (boolean expression)
{
statements
}
The if...else statement
if (boolean expression)
{
statements
}
else
{
statements
}
Nested (중첩) if statement
If the statement in an if statement is itself an if statement, the result is a nested if statement.
Ex1)
if (boolean expr1)
if (boolean expr2)
statement;
This is equivalentto
if (boolean expr1 && boolean expr2)
statement;
Ex2) Beware the dangling else! Suppose you want to read in an integer and print it it it's positive and
AP 페이지 3
Ex2) Beware the dangling else! Suppose you want to read in an integer and print it it it's positive and
even.
int n = …;
if (n > 0)
if (n % 2 == 0)
[Link](n);
else
[Link](n + " is not positive");
A user enters 7 and is surprised to see the output.
7 is not positive
There are two ways to fix the preceding code. The first is to use {} delimiters to group the satements
correctly.
int n = …; //read user input
if (n > 0)
{
if (n % 2 == 0)
[Link](n);
}
else
[Link](n + " is not positive");
The second way of fixing the code is to rearrange the statements
int n = …; //read user input
if (n <= 0)
[Link] (n + " is not positive");
else
if (n % 2 ==0)
[Link](n);
Extend if statement
Ex)
String grade = …; //read user input
if ( [Link]("A"))
[Link]("Excellent");
else if ([Link]("B"))
[Link]("Good");
else if ([Link]("C") || [Link]("D"))
[Link]("Poor");
else if([Link]("E"))
[Link]("Egregious");
else
[Link]("Invalid grade")
Iteration
-for loop, while loop
Loop: repetition of statements
The for loop
The general form of the for loop is
for (initialization; termination condition; update statement)
{
statements //body of loop
}
The termination condition is tested at the top of the loop; the update statement is performed at the bottom.
Ex1)
//outputs 1 2 3 4
for (i = 1; i < 5; i++)
[Link] (i + " ");
Ex2)
//outputs 2 4 6 8 10
for (j = 2; j <= 10; j += 2)
[Link](j + " ");
Ex3)
//outputs 20 19 18 17 16
for(k = 20; k <= 16; k --)
[Link](k + " ");
Note
1. The loop variable should not have its value changed inside the loop body.
2. The initizaling and update statements can use an valid constants variables, or expressions.
3. The scopes (the segment of the program where a variable can be used and is valid) of the loop variable
can be restricted to the loop body by combining the loop variable declaration with the initialization.
For example,
for (int i = 0; i < 3; i++)
{
…
AP 페이지 4
…
}
4. The following loop is syntactically (문법적으로) valid:
for (int i = 1; i <= 0; i++)
{
…
}
The loop body will not be executed at all, since the exiting codition is true before the first execution.
Enhanced for loop (For-each-loop)
This is used to iterate over an array or collection. The general form of the loop is
for (SomeType element : collection)
{
ststements
}
(Read the top lines as "For each element of type someType in collection…")
Ex)
//Outputs all elements of arr, one per line.
for (int element : arr)
[Link](element);
Note
1. The enhanced for loop should be used for accessing elements in the data structure, not for replacing or
removing elements as you traverse.
2. The loop hides the index variable that is used with arrays.
The while loop
The general form of the while loop is
while (boolean test)
{
statements //loop body
}
There are standard algorithms to:
-Identify if an integer is or is not evenly divisible by another integer
-Identify the individual digits in an integer
-Determine the frequency with which a specific criterion is met
Ex1)
int i = 1, mult3 = 3;
while (mult3 < 20)
{
[Link](mult3 + " ");
i++;
mult3 *= i;
} //outpus 3 6 18
Note
1. It is possible for the body of a while loop never to be executed. This is will happen if the test evaluates
to false the first time.
2. Don’t forget to change the loop variable in the body of the loop in a way that leads to termination.
Ex2)
int power2 = 1;
while (power2 !=20)
{
[Link](power2);
power2 *= 2;
}
Since power2 will never exactly equal 20, the loop will grind merrily along eventually causing an integer
overflow.
Ex3)
/* Screen out bad data/
* The loop won't allow execution to continue until a valid
* integer is entered.
*/
[Link]("Enter a positive integer from 1 to 100");
int num = …; //read user input
while (num < 1 || num > 100)
{
[Link]("Number must be from 1 to 100.");
[Link]("Please reenter");
num = …;
}
Ex4)
/* Uses a sentinel (a special input value that tests the condition within the while loop) to terminate data
entered at the keyboard.
AP 페이지 5
entered at the keyboard.
* The Te sentinel is a valuve that cannot be part of the data.
* It signals the end of the list.
*/
final int SENTINEL = -999;
[Link]("Enter list of positive integers, " + " end list with " + SENTINEL);
int value = …; //read user input
while (value != SENTINEL)
{
process the valuse
value = …; //read anothre values
}
Collegeboard example)
pubic static void main(String[] args)
{
int value = 1;
while (value <= 5)
{
[Link](value);
value++;
}
[Link]("Finished!"):
}
1
2
3
4
5
Finished!
public static void main(String[] args)
{
int number = 5;
while (number < 100)
{
[Link](number + " ");
number += 5;
}
[Link]();
}
5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95
Infinity loop
public static void main(String[] args)
{
while (true)
{
[Link]("AP CSA") ;
}
}
=infinite Loop
Sum the individual Digits of an Integer
-Given a multidigit integer, sum the individual digits
5384 -> 5 + 3 + 8 + 4 = 20
Mod (%) (Any integer) % 10 -> last digit
Integer Divison (Any integer) % 10 -> eliminates last digit
while loop Allows us to repeat a task mulitiple times
Algorithm
-Given an integer called number
-Create a variable for the sum
-Use modd(%10) to isolate the last digit of our number
-Add the last digit to the sum
-Use integer division (/10) to eliminate the last digit from the number
Ex)
public static void main(String[] args)
{
int number = 5384;
int sum = 0;
while (number > 0)
{
int lastDigit = number % 10
AP 페이지 6
int lastDigit = number % 10
sum += lastDigit;
number = number / 10;
}
[Link]("The sume of the digits is " +sum);
The sum of the digits is 20
Note
New number value will goes to first step for new lastDigit, and repeat this step unitl of these values goes
to zero
Can you write a code segment that sums the first 100 positive multiples of 4 and prints the results?
/*
Sums up first 10 multiples of 4
*/
public class Sum4mutliples
{
public static void main(String[] args)
{
int counter = 1;
int sum = 0;
while (counter <=10)
{
sum = sum +(counter *4);
counter==;
}
[Link]("The sum is " + sum);
}
}
The sum is 220
If you have $200 in a bank account that earns 10% interest per year, how much would you have after
saving that money for 50 years?
public class Interest
{
public static void main(String[] args)
{
int numYear = 50;
double total = 200;
for (int year = 1; num <= numYear; year++)
{
total = total + (total*.10);
}
[Link]("After 50 years, my $200 would be worth $" + total);
}
}
화면 캡처: 2022-03-26 오전 9:42
Nested loops
you create a nested loop when a loop is a statement in the body of another loop.
Ex1)
for (int k = 1; k <= 3; k++)
{
for (int i = 1; i <= 4; i++)
AP 페이지 7
for (int i = 1; i <= 4; i++)
[Link]("*");
[Link]();
Output:
****
****
****
Ex2) This example has two loops nested in an outer loop.
for (int i = 1; i <= 6; i++)
{
for (int j = 1; j <= j; j++)
[Link]("+");
for (int j = 1; j <= 6 - i; j++)
[Link]("*");
[Link]();
}
Output:
+*****
++****
+++***
++++**
+++++*
++++++
public class NestedLoops {
public static void main(String[] args)
{
for(int outer = 1; outer < 5; outer++)
{
for(int inner = 1; inner < 3; inner++)
{
[Link](inner + " ")'
}
[Link]();
}
}
}
12 (outer 1일때 inner 1일때와 2일때)
12 (outer 2일때 inner 1일때와 2일때)
12 (outer 3일때 inner 1일때와 2일때)
12 (outer 4일때 inner 1일때와 2일때)
Errors and Exceptions
Exception
ArithmeticException
NullPointerException
ArrayIndexOutOfBoundException
IndexOutOfBoundsException
IllegalArgumentException
ConcurrentModificationException
Off by one (when the iteration statement loops one time too many or one time too few)
Ex1)
if (numScores == 0)
throw new ArithmeticException ("Cannot divide by zero");
else
findAverageScore ();
Ex2)
public void setRadius (int newRadius)
{
if (newRadius < 0)
throw new IllegalArgumentException
("Radius cannot be negative");
else
radius = newRadius;
}
Note
1. throw and new are both reservd words.
2. The error message is optional: The line in Example 1 could have read throw new ArithmeticException
();
AP 페이지 8
();
AP 페이지 9