370 likes | 497 Views
JAVA Programcılığı 1.1.2. Ali R+ SARAL. Ders Planı 1.1.2. Storing characters Harfleri Depolamak Bitwise Operations Bit İşlemleri Enumeration Boolean variables Bool Değişkenleri Arithmetic Calculations Aritmetik Hesaplamaları.
E N D
JAVA Programcılığı 1.1.2 Ali R+ SARAL
Ders Planı 1.1.2 • Storing characters Harfleri Depolamak • Bitwise Operations Bit İşlemleri • Enumeration • Boolean variables Bool Değişkenleri • Arithmetic CalculationsAritmetik Hesaplamaları
Fixing the Value of a VariableKayan Nokta Değişkenini Sabitleyiş • Sometimes you will declare and initialize a variable with a value that should never change. For example: • final int FEET_PER_YARD = 3; // Constant values • final double MM_PER_INCH = 25.4; // that cannot be changed
Arithmetic CalculationsAritmetik Hesaplamaları • numFruit = numApples + numOranges; • numApples = numApples + 1; • a = b = c = 777; • With simple assignments of a constant value to a variable of type short or byte, the constant will be stored as the type of the variable on the left of the =, rather than type int. For example: • short value = 0; • value = 10;
Arithmetic CalculationsAritmetik Hesaplamaları • 20 – 3 * 3 – 9 / 3 • will produce the value 8, since it is equivalent to 20 – 9 – 3. • (20 – 3) * (3 – 9) / 3 • is equivalent to 17 * (-6) / 3, which results in -34.
Arithmetic CalculationsAritmetik Hesaplamaları • EXAMPLE: Apples and Oranges – FRUIT FRUIT 01.TotalFruit • public class Fruit { public static void main(String[] args) { // Declare and initialize three variables int numOranges = 5; // Count of oranges int numApples = 10; // Count of apples int numFruit = 0; // Count of fruit numFruit = numOranges + numApples; // Calculate the total fruit count // Display the result System.out.println(“A totally fruity program”); System.out.println(“Total fruit is “ + numFruit); } }
FruitWait 02_DelayedEnding • import java.io.IOException; // For code that delays ending the program • public class FruitWait { • public static void main(String[] args) { // Declare and initialize three variables int numOranges = 5; // Count of oranges int numApples = 10; // Count of apples int numFruit = 0; // Count of fruit numFruit = numOranges + numApples; // Calculate the total fruit count // Display the result System.out.println(“A totally fruity program”); System.out.println(“Total fruit is “ + numFruit); // Code to delay ending the program System.out.println(“(press Enter to exit)”); try { System.in.read(); // Read some input from the keyboard } catch (IOException e) { // Catch the input exception return; // and just return } } }
Arithmetic Calculations 04_IncrementOrangesAritmetik Hesaplamaları • EXAMPLE – AverageFruit01_Average • public class Fruit { • public static void main(String[] args) { // Declare and initialize three variables int numOranges = 5; int numApples = 10; int numFruit = 0; // Increment oranges and calculate the total fruit numFruit = ++numOranges + numApples; System.out.println(“A totally fruity program”); // Display the result System.out.println(“Value of oranges is “ + numOranges); System.out.println(“Total fruit is “ + numFruit); } }
Integer Division and RemaindersInteger Bölme ve Kalan • int numFruitEach = 0; // Num fruit for each child • numFruitEach = numFruit/4; • int remainder = 0; • remainder = numFruit%4; // Calculate the remainder after division by 4
Increment and Decrement Operators Arttır ve Azalt İşlemleri • int count = 10; • ++count; // Add 1 to count • --count; // Subtract 1 from count • Computation with shorter Integer types • short numOranges = 5; • short numApples = 10; • short numFruit = 0;
Integer calculationsInteger Hesaplamaları • You will find that the program will no longer compile. The problem is with the statement: • numFruit = numOranges + numApples; • Since the expression numOranges + numApples produces a 32-bit result, • the compiler cannot store this value in numFruit, as the variable numFruit is only 16 bits long.
Integer calculationsInteger Hesaplamaları • To make the code acceptable to the compiler, you must modify the assignment statement so that the 32-bit result of the addition is converted back to a 16-bit number. • You do this by changing the statement to: • numFruit = (short)(numOranges + numApples);
Errors in integer arithmeticInteger Aritmetiğinde Hatalar • If you divide an integer value by zero, no sensible result can be produced so an exception will be • thrown,
Floating Point calculationsKayan Nokta Hesaplamaları • EXAMPLE-AVERAGE FRUIT • Other Floating Point arithmetic Operators • You can apply the modulus operator, %, to floating-point values, too. For an operation of the form: • floatOperand1 % floatOperand2 • Error conditions in Floating Point Arithmetic • Mixed Arithmetic expressions
Floating Point calculationsKayan Nokta Hesaplamaları • EXAMPLE – AverageFruit01_Average • public class AverageFruit { • public static void main(String[] args) { // Declare and initialize three variables double numOranges = 50.0E-1; // Initial value is 5.0 double numApples = 1.0E1; // Initial value is 10.0 double averageFruit = 0.0; averageFruit = (numOranges + numApples)/2.0; System.out.println(“A totally fruity program”); System.out.println(“Average fruit is “ + averageFruit); } }
Automatic type conversions in Assignments Atamalarda Otomatik Tip Değişimleri • Automatic type conversions in Assignments • For example, suppose you have defined a double variable result; and two variables, three and two, of type int with the values 3 and 2, respectively.
Automatic type conversions in Assignments Atamalarda Otomatik Tip Değişimleri If you compute the value of result with the statement • result = 1.5 + three/two; • the value stored will be 2.5, • since three/two will be executed as an integer operation • and will produce the result 1.
Automatic type conversions in Assignments Atamalarda Otomatik Tip Değişimleri • You may have wanted the term three/two to produce the value 1.5 so the overall result would be 3.0. You could do this using an explicit cast: • result = 1.5 + (double)three/two; • The op= operators • count += 5; • This has the same effect as the statement: • count = count + 5;
Matematik Fonksiyonları ve Sabitleri • EXAMPLE- the Math Class –PondRadiusMathCalc.java • public class PondRadius { public static void main(String[] args) { // Calculate the radius of a pond // which can hold 20 fish averaging 10 inches long int fishCount = 20; // Number of fish in pond int fishLength = 10; // Average fish length int lengthPerSqFt = 2; // Fish length per square foot of surface double radius = 0.0; // Pond radius in feet int feet = 0; // Pond radius - whole feet int inches = 0; // - and whole inches double pondArea = (double)(fishCount*fishLength)/lengthPerSqFt; radius = Math.sqrt(pondArea/Math.PI); feet = (int)Math.floor(radius); // Get the whole feet and nothing but the feet inches = (int)Math.round(12.0*(radius – feet)); // Get the inches System.out.println(“To hold “ + fishCount + “ fish averaging “ + fishLength + “ inches long you need a pond with an area of \n” + pondArea + “ square ft.”); System.out.println(“The radius of a pond with area “ + pondArea + “ square feet is\n “ + feet + “ feet “ + inches + “ inches”); } }
Matematik Fonksiyonları ve Sabitleri • radius = Math.sqrt(pondArea/Math.PI); • The result is in feet as a value of type double. • To get the number of whole feet you use the floor() method: • feet = (int)Math.floor(radius); //
Importing the MathClass Methods • import static java.lang.Math.*; // Import static class members • import static java.lang.Math.floor; // Import floor • import static java.lang.Math.sqrt; // Import sqrt • import static java.lang.Math.round; // Import round • import static java.lang.Math.PI; // Import PI
Storing charactersHarfleri Depolamak • Variables of type char store a single character code. • char myCharacter = ‘X’; • Character Escape Sequences • char myCharacter = ‘\u0058’; • System.out.println(“\”It\’s freezing in here\”, he said coldly.”); • \b Backspace • \f Form feed • \n New line • \r Carriage return • \t Tab
Character Arithmetic Harf aritmetiği • Character arithmetic • myCharacter += 1; // Increment to next character • ++myCharacter; // Increment to next character • char aChar = 0; • char bChar = ‘\u0028’; • aChar = (char)(2*bChar + 8); • Here are the hexadecimal codes for the letters: • A: 41 B: 42 C: 43
Storing charactersHarfleri Depolamak • EXAMPLE- Arithmetic with Character Codes – CHARCODECALCS • public class CharCodeCalcs { • public static void main(String[] args){ char letter1 = ‘A’; // letter1 is ‘A’ char letter2 = (char)(letter1+1); // letter2 is ‘B’ char letter3 = letter2; // letter3 is also ‘B’ System.out.println(“Here\’s a sequence of letters: “+ letter1 + letter2 + (++letter3)); // letter3 is now ‘C’ System.out.println(“Here are the decimal codes for the letters:\n”+ letter1 + “: “ + (int)letter1 + “ “ + letter2 + “: “ + (int)letter2 + “ “ + letter3 + “: “ + (int)letter3); } } • import static java.lang.Integer.toHexString;
Bitwise OperationsBit İşlemleri • & AND , | OR • ^ Exclusive OR if both bits are the same the result is 0; otherwise, the result is 1. • ~ Complement it inverts all the bits, so that each 1 bit becomes 0, and each 0 bit becomes 1 • Using the AND OR Operators • thirdBit = indicators & 0x4; // Select the 3rd bit
Bitwise OperationsBit İşlemleri • EXAMPLE- Bitwise AND and OR operations-BITWISEOPS • import static java.lang.Integer.toBinaryString; • public class BitwiseOps { • public static void main(String[] args) { int indicators = 0xFF07; int selectBit3 = 0x4; // Mask to select the 3rd bit // Try the bitwise AND to select the third bit in indicators System.out.println(“indicators = “ + toBinaryString(indicators)); System.out.println(“selectBit3 = “ + toBinaryString(selectBit3)); indicators &= selectBit3; System.out.println(“indicators & selectBit3 = “ + toBinaryString(indicators)); // Try the bitwise OR to switch the third bit on indicators = 0xFF09; System.out.println(“\nindicators = “+ toBinaryString(indicators)); System.out.println(“selectBit3 = “+ toBinaryString(selectBit3)); indicators |= selectBit3; System.out.println(“indicators | selectBit3 = “ + toBinaryString(indicators)); // Now switch the third bit off again indicators &= ~selectBit3; System.out.println(“\nThe third bit in the previous value of indicators” + “ has been switched off”); System.out.println(“indicators & ~selectBit3 = “ + toBinaryString(indicators)); } }
Bitwise OperationsBit İşlemleri • Using the Exclusive OR operator • a ^= b; • byte allBitsOne = 0xFF; // Wrong!! • byte allBitsOne = 0xFFFFFFFF; // Correct – well done!! • Shift Operations • << Shift left, filling with zeros from the right. • >> Shift right, propagating the sign bit from the left. • >>> Shift right, filling with zeros from the left.
Bitwise OperationsBit İşlemleri • EXAMPLE-Using shift Operations-PACKING CHARACTERS • import static java.lang.Long.toHexString; • public class PackingCharacters { • public static void main(String[] args) { • char letterA = ‘A’; • char letterB = ‘B’; • char letterC = ‘C’; • char letterD = ‘D’; • long packed = 0L; • packed = letterD; // Store D • packed = (packed << 16) | letterC; // Shift and add the next letter - C • packed = (packed << 16) | letterB; // Shift and add the next letter - B • packed = (packed << 16) | letterA; // Shift and add the next letter - A • System.out.println(“packed now contains 0x” + toHexString(packed)); • // Now unpack the letters and output them • long mask = 0xFFFF; // Rightmost 16 bits as 1 • char letter = (char)(packed & mask); // Extract the rightmost letter • System.out.println(“From right to left the letters in packed are:”); • System.out.println(“ “ + letter + “ 0x” + toHexString(letter)); • packed >>= 16; // Shift out the rightmost letter • letter = (char)(packed & mask); // Extract the new rightmost letter • System.out.println(“ “ + letter + “ 0x” + toHexString(letter)); • packed >>= 16; // Shift out the rightmost letter • letter = (char)(packed & mask); // Extract the new rightmost letter • System.out.println(“ “ + letter + “ 0x” + toHexString(letter)); • packed >>= 16; // Shift out the rightmost letter • letter = (char)(packed & mask); // Extract the new rightmost letter • System.out.println(“ “ + letter + “ 0x” + toHexString(letter)); • } • }
Bitwise OperationsBit İşlemleri • Methods for Bitwise operations • bitCount(arg) • highestOneBit(arg) • lowestOneBit(arg) • numberOfLeadingZeros(arg) • int data = 0x0F00; • // data is: 0000 0000 0000 0000 0000 1111 0000 0000 • int bits = Integer.bitCount(data); // Result is 4
Bitwise Operations • EXAMPLE- Methods for Bitwise operations-TRYBITMETHODS • import static java.lang.Long.*; • public class TryBitMethods { • public static void main(String[] args) { • long number = 0xF00000000000000FL; • System.out.println(“number:\n” + toBinaryString(number)); • long result = rotateLeft(number,2); • System.out.println(“number rotated left 2 bits:\n” + toBinaryString(result)); • result = rotateRight(number, 3); • System.out.println(“number rotated right 3 bits:\n” + toBinaryString(result)); • result = reverse(result); • System.out.println(“Previous result reversed:\n” + toBinaryString(result)); • System.out.println(“Bit count in number:\n” + bitCount(number)); • } • } • 76
enumeration • Variables with a fixed set of integer values • You will often need variables that can have values only from a predefined fixed set. • enum Day {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday } • Day weekday = Day.Tuesday;
enumeration • Variables with a fixed set of integer values • enum Month { January, February, March , April , May , June, July , August , September, October, November, December } • Month current = Month.September; // Initialize to September • current = Month.October;
enumeration • EXAMPLE-Using enumeration- TRYENUMERATION • public class TryEnumeration { // Define an enumeration type for days of the week enum Day {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday } public static void main(String[] args) { // Define three variables of type Day Day yesterday = Day.Thursday; Day today = Day.Friday; Day tomorrow = Day.Saturday; // Output the values of the Day variables System.out.println(“Today is “ + today); System.out.println(“Tomorrow will be “ + tomorrow); System.out.println(“Yesterday was “ + yesterday); } }
Boolean variablesBool Değişkenleri • Variables of type boolean can have only one of two values, true or false. The values true and false are boolean literals • boolean state = true; • state = false;
Operator precedenceİşlem Önceliği • a = b + c + 10; • a = (b + c) + 10; • (), [], postfix ++, postfix -- • unary +, unary -, prefix ++, prefix --, ~, ! • (type), new • *, /, % • +, - • <<, >>, >>> • < ,<= , >, >=, instanceof • ==, != • & • ^ • | • && • || • =, +=, -=, *=, /=, %=, <<=, >>=, >>>=, &=, |=, ^=
comments Yorumlar • Program comments • /*************************************** • * This is a long explanation of * • * some particularly important * • * aspect of program operation. * • ***************************************/ • Documentation Comments • /** • This is a documentation comment. • */ • //single line comment