1 / 37

JAVA Programciligi 1.1.2

Ders Plani 1.1.2. Storing characters Harfleri DepolamakBitwise Operations Bit IslemleriEnumerationBoolean variables Bool DegiskenleriArithmetic Calculations Aritmetik Hesaplamalari. Fixing the Value of a Variable Kayan Nokta Degiskenini Sabitleyis . Sometimes you will declare and initialize a

valterra
Télécharger la présentation

JAVA Programciligi 1.1.2

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


    1. JAVA Programciligi 1.1.2 Ali R+ SARAL

    2. Ders Plani 1.1.2 Storing characters Harfleri Depolamak Bitwise Operations Bit Islemleri Enumeration Boolean variables Bool Degiskenleri Arithmetic Calculations Aritmetik Hesaplamalari

    3. Fixing the Value of a Variable Kayan Nokta Degiskenini Sabitleyis 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

    4. Arithmetic Calculations Aritmetik Hesaplamalari 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;

    5. Arithmetic Calculations Aritmetik Hesaplamalari 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.

    6. Arithmetic Calculations Aritmetik Hesaplamalari 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); } }

    7. 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 } } }

    8. FruitWait

    9. Arithmetic Calculations 04_IncrementOranges Aritmetik Hesaplamalari EXAMPLE AverageFruit 01_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); } }

    10. Integer Division and Remainders Integer Blme 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

    11. Increment and Decrement Operators Arttir ve Azalt Islemleri 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;

    12. Integer calculations Integer Hesaplamalari 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.

    13. Integer calculations Integer Hesaplamalari 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);

    14. Errors in integer arithmetic Integer Aritmetiginde Hatalar If you divide an integer value by zero, no sensible result can be produced so an exception will be thrown,

    15. Floating Point calculations Kayan Nokta Hesaplamalari 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

    16. Floating Point calculations Kayan Nokta Hesaplamalari EXAMPLE AverageFruit 01_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); } }

    17. Automatic type conversions in Assignments Atamalarda Otomatik Tip Degisimleri 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.

    18. Automatic type conversions in Assignments Atamalarda Otomatik Tip Degisimleri 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.

    19. Automatic type conversions in Assignments Atamalarda Otomatik Tip Degisimleri 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;

    20. Matematik Fonksiyonlari ve Sabitleri EXAMPLE- the Math Class PondRadius MathCalc.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); } }

    21. Matematik Fonksiyonlari 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); //

    22. 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

    23. Storing characters Harfleri 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

    24. Character Arithmetic Harf aritmetigi 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

    25. Storing characters Harfleri 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;

    26. Bitwise Operations Bit Islemleri & 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

    27. Bitwise Operations Bit Islemleri 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)); } }

    28. Bitwise Operations Bit Islemleri 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.

    29. Bitwise Operations Bit Islemleri 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)); } }

    30. Bitwise Operations Bit Islemleri 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

    31. 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

    32. 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;

    33. 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;

    34. 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); } }

    35. Boolean variables Bool Degiskenleri 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;

    36. Operator precedence Islem nceligi a = b + c + 10; a = (b + c) + 10; (), [], postfix ++, postfix -- unary +, unary -, prefix ++, prefix --, ~, ! (type), new *, /, % +, - <<, >>, >>> < ,<= , >, >=, instanceof ==, != & ^ | && || =, +=, -=, *=, /=, %=, <<=, >>=, >>>=, &=, |=, ^=

    37. 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

More Related