금요일, 3월 29
Shadow

#001 OPERATOR

<<  op1 << op2  Shifts bits of op1 left by distance op2; fills with 0 bits on the right side
>>  op1 >> op2  Shifts bits of op1 right by distance op2; fills with highest (sign) bit on the left side
>>>  op1 >>> op2  Shifts bits of op1 right by distance op2; fills with 0 bits on the left side

&  op1 & op2  Bitwise AND if both operands are numbers;
conditional AND if both operands are boolean
|  op1 | op2  Bitwise OR if both operands are numbers;
conditional OR if both operands are boolean
^  op1 ^ op2  Bitwise exclusive OR (XOR)
~  ~op  Bitwise complement
AND
0 0 0
0 1 0
1 0 0
1 1 1

OR
0 0 0
0 1 1
1 0 1
1 1 1

XOR
0 0 0
0 1 1
1 0 1
1 1 0

static final int VISIBLE = 1;
static final int DRAGGABLE = 2;
static final int SELECTABLE = 4;
static final int EDITABLE = 8;

int flags = 0;

flags = flags | VISIBLE;
if ((flags & VISIBLE) == VISIBLE) {

}

public class BitwiseDemo {

static final int VISIBLE = 1;
static final int DRAGGABLE = 2;
static final int SELECTABLE = 4;
static final int EDITABLE = 8;

public static void main(String[] args) {
int flags = 0;

flags = flags | VISIBLE;
flags = flags | DRAGGABLE;

if ((flags & VISIBLE) == VISIBLE) {
if ((flags & DRAGGABLE) == DRAGGABLE) {
System.out.println(“Flags are Visible ”
+ “and Draggable.”);
}
}

flags = flags | EDITABLE;

if ((flags & EDITABLE) == EDITABLE) {
System.out.println(“Flags are now also Editable.”);
}
}
}

+=  op1 += op2  Equivalent to op1 = op1 + op2
-=  op1 -= op2  Equivalent to op1 = op1 – op2
*=  op1 *= op2  Equivalent to op1 = op1 * op2
/=  op1 /= op2  Equivalent to op1 = op1 / op2
%=  op1 %= op2  Equivalent to op1 = op1 % op2
&=  op1 &= op2  Equivalent to op1 = op1 & op2
|=  op1 |= op2  Equivalent to op1 = op1 | op2
^=  op1 ^= op2  Equivalent to op1 = op1 ^ op2
<<=  op1 <<= op2  Equivalent to op1 = op1 << op2
>>=  op1 >>= op2  Equivalent to op1 = op1 >> op2
>>>=  op1 >>>= op2  Equivalent to op1 = op1 >>> op2
?:  op1 ? op2 : op3  If op1 is true, returns op2; otherwise, returns op3
[]  See Creating and Using Arrays  Used to declare arrays, to create arrays, and to access array elements
.  See Using Objects Used to form long names
(params)  See Defining Methods Delimits a comma-separated list of parameters
(type)  (type) op  Casts (converts) op to the specified type; an exception is thrown if the type of op is incompatible with type
new  See Using Objects and Creating and Using Arrays Creates a new object or array
instanceof  op1 instanceof op2  Returns true if op1 is an instance of op2
Summary
+  +op  Promotes op to int if it’s a byte, short, or char
–  -op  Arithmetically negates op
+ op1 + op2  Adds op1 and op2; also used to concatenate strings
– op1 – op2  Subtracts op2 from op1
* op1 * op2  Multiplies op1 by op2
/ op1 / op2  Divides op1 by op2
% op1 % op2  Computes the remainder of dividing op1 by op2
++  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
>  op1 > op2  Returns true if op1 is greater than op2
>=  op1 >= op2  Returns true if op1 is greater than or equal to op2
<  op1 < op2  Returns true if op1 is less than op2
<=  op1 <= op2  Returns true if op1 is less than or equal to op2
==  op1 == op2  Returns true if op1 and op2 are equal
!=  op1 != op2  Returns true if op1 and op2 are not equal
&&  op1 && op2  Returns true if op1 and op2 are both true; conditionally evaluates op2
||  op1 || op2  Returns true if either op1 or op2 is true; conditionally evaluates op2
!  !op  Returns true if op is false
&  op1 & op2  Returns true if op1 and op2 are both boolean and both true; always evaluates op1 and op2; if both operands are numbers, performs bitwise AND operation
|  op1 | op2  Returns true if both op1 and op2 are boolean and either op1 or op2 is true; always evaluates op1 and op2; if both operands are numbers, performs bitwise inclusive OR operation
^  op1 ^ op2  Returns true if op1 and op2 are different ? that is, if one or the other of the operands, but not both, is true
<<  op1 << op2  Shifts bits of op1 left by distance op2; fills with 0 bits on the right side
>>  op1 >> op2  Shifts bits of op1 right by distance op2; fills with highest (sign) bit on the left side
>>>  op1 >>> op2  Shifts bits of op1 right by distance op2; fills with 0 bits on the left side
&  op1 & op2  Bitwise AND if both operands are numbers;
conditional AND if both operands are boolean
|  op1 | op2  Bitwise OR if both operands are numbers;
conditional OR if both operands are boolean
^  op1 ^ op2  Bitwise exclusive OR (XOR)
~  ~op  Bitwise complement
=  op1 = op2  Assigns the value of op2 to op1
+=  op1 += op2  Equivalent to op1 = op1 + op2
-=  op1 -= op2  Equivalent to op1 = op1 – op2
*=  op1 *= op2  Equivalent to op1 = op1 * op2
/=  op1 /= op2  Equivalent to op1 = op1 / op2
%=  op1 %= op2  Equivalent to op1 = op1 % op2
&=  op1 &= op2  Equivalent to op1 = op1 & op2
|=  op1 |= op2  Equivalent to op1 = op1 | op2
^=  op1 ^= op2  Equivalent to op1 = op1 ^ op2
<<=  op1 <<= op2  Equivalent to op1 = op1 << op2
>>=  op1 >>= op2  Equivalent to op1 = op1 >> op2
>>>=  op1 >>>= op2  Equivalent to op1 = op1 >>> op2
?:  op1 ? op2 : op3  If op1 is true, returns op2; otherwise, returns op3
[]  See Creating and Using Arrays  Used to declare arrays, to create arrays, and to access array elements
.  See Using Objects Used to form long names
(params)  See Defining Methods Delimits a comma-separated list of parameters
(type)  (type) op  Casts (converts) op to the specified type; an exception is thrown if the type of op is incompatible with type
new  See Using Objects and Creating and Using Arrays Creates a new object or array
instanceof  op1 instanceof op2  Returns true if op1 is an instance of op2

import java.text.DecimalFormat;

//DecimalFormat is discussed in
//http://java.sun.com/docs/books/tutorial/java/data/decimalFormat.html

public class CurrencyExchange {
static double EUROS_PER_DOLLAR = 0.781162;

public static void main(String[] args) {
DecimalFormat formatter = new DecimalFormat(“###,###.00″);
double numEuros = 10000000.0;
double numDollars = numEuros/EUROS_PER_DOLLAR;

System.out.println(formatter.format(numEuros)
+ ” euros is equal to $”
+ formatter.format(numDollars)
+ “.”);
}
}
grouping statements together with braces, { and }, you create blocks of code.

/**
* MaxVariablesDemo.java is an application that compiles and runs
* under J2SE 5.0. It requires no other files.
*/

public class MaxVariablesDemo {
public static void main(String args[]) {

//integers
byte largestByte = Byte.MAX_VALUE;
short largestShort = Short.MAX_VALUE;
int largestInteger = Integer.MAX_VALUE;
long largestLong = Long.MAX_VALUE;

//real numbers
float largestFloat = Float.MAX_VALUE;
double largestDouble = Double.MAX_VALUE;

//other primitive types
char aChar = ‘S’;
boolean aBoolean = true;

//Display them all.
System.out.println(“The largest byte value is ”
+ largestByte + “.”);
System.out.println(“The largest short value is ”
+ largestShort + “.”);
System.out.println(“The largest integer value is ”
+ largestInteger + “.”);
System.out.println(“The largest long value is ”
+ largestLong + “.”);

System.out.println(“The largest float value is ”
+ largestFloat + “.”);
System.out.println(“The largest double value is ”
+ largestDouble + “.”);

if (Character.isUpperCase(aChar)) {
System.out.println(“The character ” + aChar
+ ” is uppercase.”);
} else {
System.out.println(“The character ” + aChar
+ ” is lowercase.”);
}
System.out.println(“The value of aBoolean is ”
+ aBoolean + “.”);
}
}

aChar = ‘S’ Assigns the character S to the character variable aChar The value of aChar after the assignment (‘S’)
“The largest byte value is ” + largestByte Concatenates the string “The largest byte value is ” and the value of largestByte converted to a string The resulting string: The largest byte value is 127
Character.isUpperCase(aChar) Invokes the method isUpperCase The return value of the method: true
postfix expr++ expr–
unary ++expr –expr +expr -expr ~ !
multiplicative * / %
additive + –
shift << >> >>>
relational < > <= >= instanceof
equality == !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||
conditional ? :
assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=
aValue = 8933.234;                      //assignment statement
aValue++;                               //increment         ”
System.out.println(aValue);             //method invocation ”
Integer integerObject = new Integer(4); //object creation   ”

block is a group of zero or more statements between balanced braces and can be used anywhere a single statement is allowed
group zero or more statements together into a block with braces: { and }.
i > 0            [boolean]
i = 0            [int]
i++              [int]
(float)i         [float]
i == 0           [boolean]
“aString” + i    [String]

i–%5>0—>(i– % 5) > 0 :false

String copyFromMe = “Copy this string until you ” +
“encounter the letter ‘g’.”;//로컬변수
StringBuffer copyToMe = new StringBuffer();  //생성자

int i = 0;
char c = copyFromMe.charAt(i); //

while (c != ‘r’) {
copyToMe.append(c);
c = copyFromMe.charAt(++i);
}
System.out.println(copyToMe);

String copyFromMe = “Copy this string until you ” +
“encounter the lettea ‘g’.”;
StringBuffer copyToMe = new StringBuffer();

int i = 0;
char c = copyFromMe.charAt(i);

do {
copyToMe.append(c);
c = copyFromMe.charAt(++i);
} while (c != ‘a’);
System.out.println(copyToMe);

 

//charAt(index num) –Returns the char value at the specified index. An index ranges from zero to length() – 1
//append
Appendable append(CharSequence csq)
throws IOExceptionAppends the specified character sequence to this Appendable.
Parameters:
csq – The character sequence to append. If csq is null, then the four characters “null” are appended to this Appendable.
Returns:
A reference to this Appendable
Throws:
IOException – If an I/O error occurs

append(CharSequence csq,
int start,
int end)
throws IOException
out.append(csq.subSequence(start, end))

Parameters:
csq – The character sequence from which a subsequence will be appended. If csq is null, then characters will be appended as if csq contained the four characters “null”.
start – The index of the first character in the subsequence
end – The index of the character following the last character in the subsequence
Returns:
A reference to this Appendable
for (initialization; termination; increment) {
statement(s)
}

for ( ; ; ) {    //infinite loop

}

public class ForDemo {
public static void main(String[] args) {
int[] arrayOfInts = { 32, 87, 3, 589, 12,
1076, 2000, 8, 622, 127 };

for (int i = 0; i < arrayOfInts.length; i++) {
System.out.print(arrayOfInts[i] + ” “);
}
System.out.println();
}
}

public class ForEachDemo {
public static void main(String[] args) {
int[] arrayOfInts = { 32, 87, 3, 589, 12,
1076, 2000, 8, 622, 127 };

for (int element : arrayOfInts) {
System.out.print(element + ” “);
}
System.out.println();
}
}

void cancelAll(Collection<TimerTask> c) {
for (Iterator<TimerTask> i = c.iterator(); i.hasNext(); )
i.next().cancel();
}

Don’t worry about the strange <TimerTask> bit of code for now. You’ll learn about it and about collections in the Generics section and the Collections chapter, respectively. The point is you can avoid it in the for loop by using the enhanced for statement.
//This is much prettier.
void cancelAll(Collection<TimerTask> c) {
for (TimerTask t : c)
t.cancel();
}

When you nest iterators, the enhanced for statement is even nicer because you can avoid more unnecessary code; here’s an example.
for (Suit suit : suits) {
for (Rank rank : ranks)
sortedDeck.add(new Card(suit, rank));
}

if (DEBUG) {
System.out.println(“DEBUG: x = ” + x);
}
//this is noting 0, all of ture

if (expression) {
statement(s)
}

System.out.println(“The character ” + aChar + ” is ” +
(Character.isUpperCase(aChar) ? “upper” : “lower”) + “case.”);

—————aChar is uppercase or lowercase?

aChar = ‘S’;

public class SwitchDemo2 {
public static void main(String[] args) {

int month = 2;
int year = 2000;
int numDays = 0;

switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
numDays = 31;
break;
case 4:
case 6:
case 9:
case 11:
numDays = 30;
break;
case 2:
if ( ((year % 4 == 0) && !(year % 100 == 0))
|| (year % 400 == 0) )
numDays = 29;
else
numDays = 28;
break;
default:
numDays = 0;
break;
}
System.out.println(“Number of Days = ” + numDays);
}
}

public class SwitchEnumDemo {
public enum Month { JANUARY, FEBRUARY, MARCH, APRIL,
MAY, JUNE, JULY, AUGUST, SEPTEMBER,
OCTOBER, NOVEMBER, DECEMBER }

public static void main(String[] args) {
Month month = Month.FEBRUARY;
int year = 2000;
int numDays = 0;

switch (month) {
case JANUARY:
case MARCH:
case MAY:
case JULY:
case AUGUST:
case OCTOBER:
case DECEMBER:
numDays = 31;
break;
case APRIL:
case JUNE:
case SEPTEMBER:
case NOVEMBER:
numDays = 30;
break;
case FEBRUARY:
if ( ((year % 4 == 0) && !(year % 100 == 0))
|| (year % 400 == 0) )
numDays = 29;
else
numDays = 28;
break;
default:
numDays=0;
break;
}
System.out.println(“Number of Days = ” + numDays);
}
}

try {
statement(s)
} catch (exceptiontype name) {
statement(s)
} finally {
statement(s)
}

The try statement identifies a block of statements within which an exception might be thrown
The catch statement must be associated with a try statement and identifies a block of statements that can handle a particular type of exception. The statements are executed if an exception of a particular type occurs within the try block.
The finally statement must be associated with a try statement and identifies a block of statements that are executed regardless of whether or not an error occurs within the try block.
public class BreakDemo {
public static void main(String[] args) {

int[] arrayOfInts = { 32, 87, 3, 589, 12, 1076,
2000, 8, 622, 127 };
int searchfor = 12;

int i = 0;
boolean foundIt = false;

for ( ; i < arrayOfInts.length; i++) {
if (arrayOfInts[i] == searchfor) {
foundIt = true;
break;
}
}

if (foundIt) {
System.out.println(“Found ” + searchfor
+ ” at index ” + i);
} else {
System.out.println(searchfor
+ “not in the array”);
}
}
}

public class BreakWithLabelDemo {
public static void main(String[] args) {

int[][] arrayOfInts = { { 32, 87, 3, 589 },
{ 12, 1076, 2000, 8 },
{ 622, 127, 77, 955 }
};
int searchfor = 12;

int i = 0;
int j = 0;
boolean foundIt = false;

search:
for ( ; i < arrayOfInts.length; i++) {
for (j = 0; j < arrayOfInts[i].length; j++) {
if (arrayOfInts[i][j] == searchfor) {
foundIt = true;
break search;
}
}
}

if (foundIt) {
System.out.println(“Found ” + searchfor +
” at ” + i + “, ” + j);
} else {
System.out.println(searchfor
+ “not in the array”);
}

}
}

public class ContinueDemo {
public static void main(String[] args) {

StringBuffer searchMe = new StringBuffer(
“peter piper picked a peck of pickled peppers”);
int max = searchMe.length();
int numPs = 0;

for (int i = 0; i < max; i++) {
//interested only in p’s
if (searchMe.charAt(i) != ‘p’)
continue;

//process p’s
numPs++;
searchMe.setCharAt(i, ‘P’);
}
System.out.println(“Found ” + numPs
+ ” p’s in the string.”);
System.out.println(searchMe);
}
}

//setCharAt(i,’ ‘) is same VB instr()
Peter PiPer Picked a Peck of Pickled PePPers

public class ContinueWithLabelDemo {
public static void main(String[] args) {

String searchMe = “Look for a substring in me”;
String substring = “sub”;
boolean foundIt = false;

int max = searchMe.length() – substring.length();

test:
for (int i = 0; i <= max; i++) {
int n = substring.length();
int j = i;
int k = 0;
while (n– != 0) {
if (searchMe.charAt(j++)
!= substring.charAt(k++)) {
continue test;
}
}
foundIt = true;
break test;
}
System.out.println(foundIt ? “Found it” :
“Didn’t find it”);
}
}

Found it

return ++count;

The data type of the value returned by return must match the type of the method’s declared return value. When a method is declared void, use the form of return that doesn’t return a value.
return;

Looping Statements
Use the while statement to loop over a block of statements while a boolean expression remains true. The expression is evaluated at the top of the loop.
while (boolean expression) {
statement(s)
}

Use the do-while statement to loop over a block of statements while a boolean expression remains true. The expression is evaluated at the bottom of the loop, so the statements within the do-while block execute at least once.

do {
statement(s)
} while (expression);

The for statement loops over a block of statements and includes an initialization expression, a termination condition expression, and an increment expression.

for (initialization; termination; increment) {
statement(s)
}

Decision-Making Statements
The Java programming language has two decision-making statements: if-else and switch. The more general-purpose statement is if; use switch to make multiple-choice decisions based on a single integer value.
The following is the most basic if statement, the single statement block of which is executed if the boolean expression is true.

if (boolean expression) {
statement(s)
}

Here’s an if statement with a companion else statement. The if statement executes the first block if the boolean expression is true; otherwise, it executes the second block.
if (boolean expression) {
statement(s)
} else {
statement(s)
}

You can use else if to construct compound if statements.
if (boolean expression) {
statement(s)
} else if (boolean expression) {
statement(s)
} else if (boolean expression) {
statement(s)
} else {
statement(s)
}

The switch statement evaluates an integer or enumerated type expression and executes the appropriate case statement.
switch (integer expression) {
case integer expression:
statement(s)
break;

default:
statement(s)
break;
}

switch (expression of enum type) {
case enum constant:
statement(s)
break;

default:
statement(s)
break;
}

Exception-Handling Statements
Use the try, catch, and finally statements to handle exceptions.
try {
statement(s)
} catch (exceptiontype name) {
statement(s)
} catch (exceptiontype name) {
statement(s)
} finally {
statement(s)
}
catch(ArithmeticException e) : 산술 계산으로 예외적 조건이 발생했을 경우(제로계산)
catch (ArrayIndexOutOfBoundsException e) :인덱스가 배열의 사이즈 이상일경우
catch(Exception e) : 어떤 예외든 발생하면 무조건 해당
Exception handling is covered in detail in the chapter Handling Errors Using Exceptions.
Branching Statements
Some branching statements change the flow of control in a program to a labeled statement. Label a statement by placing a legal identifier (the label) followed by a colon (:) before the statement.
statementName: someJavaStatement;

Use the unlabeled form of the break statement to terminate the innermost switch, for, while, or do-while statement.
break;

Use the labeled form of the break statement to terminate an outer switch, for, while, or do-while statement with the given label.
break label;

A continue statement terminates the current iteration of the innermost loop and evaluates the boolean expression that controls the loop.
continue;

The labeled form of the continue statement skips the current iteration of the loop with the given label.
continue label;

Use return to terminate the current method.
return;

You can return a value to the method’s caller by using the form of return that takes a value.
return value;

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다

이 사이트는 스팸을 줄이는 아키스밋을 사용합니다. 댓글이 어떻게 처리되는지 알아보십시오.