1 / 57

Elementary Programming

Elementary Programming. Terminology. Primitive Data Type – a category of data. A description of how the computer will treat bits found in memory. Variable – a named location in memory, treated as a particular data type, whose contents can be changed.

jackie
Download Presentation

Elementary Programming

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. Elementary Programming

  2. Terminology • Primitive Data Type – a category of data. A description of how the computer will treat bits found in memory. • Variable – a named location in memory, treated as a particular data type, whose contents can be changed. • Constant – a named location in memory, treated as a particular type, whose contents cannot be changed. • Declaration – the act of creating a variable or constant and specifying its type. • Literal – a hard-coded piece of data, part of the statement and not based on a variable or constant declaration. • Operator – a symbol that describe how to manipulate data and variables in memory • Expression – a combination of operators, variables, constants and/or literals that produces a resulting piece of data • Assignment – copying the results of an expression into a variable. • Statement – a program instruction telling the CPU what to do. (All statements end with semicolon).

  3. Java Primitive Data types • int -- 32-bit signed integer • long -- 64-bit signed integer • float -- 32-bit floating point number • double -- 64-bit floating point nbr • boolean -- true/false • char -- Unicode character (good for internationalization) • byte -- 8-bit signed integer • short --16-bit signed integer

  4. Identifiers • Identifier = the name of a variable, constant, class, or method • Rules for using identifiers: • An identifier must start with a letter, an underscore, or a dollar sign. • An identifier cannot contain operators, such as+, -, and so on. • An identifier cannot be a reserved word. • An identifier cannot betrue, false, ornull. • An identifier can be of any length.

  5. Declaring Variables int x; // declares x to be an // integer variable; double radius; // declares radius to // be a double variable; char a; // declares a to be a // character variable; Declaring multiple variables of the same type: datatype identifier1, identifier2, identifier3; General format: datatype identifier;

  6. These expressions are all just Literals! Note: the = sign is an assignment operator. It is NOT a test for equality. Assignment Statements x = 1; // Assign 1 to x; radius = 1.0; // Assign 1.0 to radius; a = 'A'; // Assign 'A' to a; General format: Variable Identifier = expression;

  7. declaration assignment NOTE: by default floating point literals are assumed to be doubles. If you want to assign a floating point literal to a float variable, you must append the “f” to the end of the number. Note: character literals are enclosed in single quotes Declaring and Initializingin One Step • int x = 1; • double d = 1.4; • float f = 1.4f; • char a = ‘a’;

  8. Abstraction Identifier (name) int a = 45; Address Identifies how we will conceptualize variables. Value

  9. The final modifier indicates that the identifier refers to a constant, not a variable. Constants must be initialized when declared. Constants final datatype CONSTANTNAME = VALUE; final double PI = 3.14159; final int SIZE = 3;

  10. Numeric Literals • int i = 34; • long l = 1000000; • float f = 100.2f; orfloat f = 100.2F; • double d = 100.2d ordouble d = 100.2D;

  11. Common Types of Operators • Assignment = • Arithmetic + - * / % • Comparison == < > <= >= != • Logical && || ! ^ modulus equals not equals Exclusive OR AND NOT OR

  12. Modulus (remainder) Operator Modulus is very useful in programming. For example, an even number % 2 is always 0 and an odd number % 2 is always 1. So you can use this property to determine whether a number is even or odd. Suppose you know January 1, 2005 is Saturday, you can find that the day for February 1, 2005 is Tuesday using the following expression:

  13. Common Types of Expressions • Arithmetic • Combine numeric data with arithmetic operators • Return a number • Conditional • Combine boolean values with logical operators • Boolean values can be derived from comparison operators or boolean data values • Returns boolean value

  14. Arithmetic Expressions • 1 + 1 • x * y • 5 / 2 • 5 % 2 • radius*radius*3.14159

  15. Sample Statements with Arithmetic Expressions //Compute the first area radius = 1.0; area = radius*radius*3.14159; //Compute the second area radius = 2.0; area = radius*radius*3.14;

  16. Arithmetic Expressions is translated to (3+4*x)/5 – 10*(y-5)*(a+b+c)/x + 9*(4/x + (9+x)/y)

  17. Shortcut Operators Operator Example Equivalent +=i+=8i = i+8 -=f-=8.0f = f-8.0 *=i*=8i = i*8 /=i/=8i = i/8 %=i%=8i = i%8

  18. Increment andDecrement Operators • x = 1; • x++; ++x; • x--; --x; • y = 2 + x++; • y = 2 + ++x; • y = 2 + x--; • y = 2 + --x; Add 1 to x Subtract 1 from x X is incremented after adding to 2 X is incremented before adding to 2 X is decremented after adding to 2 X is decremented before adding to 2

  19. Increment andDecrement Operators, cont.

  20. Integer vs. Floating Point Division • When performing operations involving two operands of different types, Java automatically converts the operand of a smaller range to the data type of the larger range. Example: 1/2 this will give 0 because both operands are integer 1.0/2 or 1/2.0  this will give 0.5 because the floating point literal is a double, so the integer literal (long) will be converted to a double; thus floating point division will take place.

  21. Unicode representation Character Data Type • char letter = 'A'; • char letter = '\u00041'; • char numChar = '4'; Java uses Unicode instead of ASCII for character data representation

  22. Character Escape Sequences Backspace \b Tab \t Linefeed \n Carriage return \r Backslash \\ Single quote \' Double quote \"

  23. Here, the + is used to concatenate strings together The + symbol as concatenation operator System.out.println("The area is " + area + " for radius " + radius); String literals are enclosed in double quotes

  24. Example public class Welcome2  • {     public static void main( String args[] )    { int y = 6 % 5; • System.out.println("\n\nHeyEverbody:\tThis is so much " • + "Fun"+"\n\n!" + y++); • System.out.println(++y);     }   }

  25. comparison expressions The boolean Data Type • boolean lightsOn = true; • boolean lightsOn = false; • boolean test = 1==1; • Returns true • boolean test = 1==2; • Returns false

  26. Boolean Operators Revisited OperatorName ! not && and || or ^ exclusive or

  27. Example for Operator ! !(1 > 2) is true, because (1 > 2) is false !(1 > 0) is false, because (1 > 0) is true

  28. Truth Table for Operator &&

  29. Truth Table for Operator ||

  30. Truth Table for Operator ^

  31. Numeric Type Conversion Consider the following statements: byte i = 100; long k = i * 3 + 4; double d = i * 3.1 + k / 2;

  32. Conversion Rules When performing a binary operation involving two operands of different types, Java automatically converts the operand based on the following rules: 1.    If one of the operands is double, the other is converted into double. 2.    Otherwise, if one of the operands is float, the other is converted into float. 3.    Otherwise, if one of the operands is long, the other is converted into long. 4.    Otherwise, both operands are converted into int.

  33. Operator Precedence

  34. Examples int x = 7 * 8 - 9 + 4 / 4 % 2;System.out.println(x); //prints ?? to the screenint y = 7 * (8 - 9) + (4 / 4) % 2;System.out.println(y); //prints ?? to the screen

  35. Programming Style and Documentation • Comments • Comments are very important. You should comment your code in order to provide explanations of what the program is doing • Indentation and Spacing • Proper indenting makes the code reflect the actual logic of the program. • Block Styles • Placement of the { and } braces • BE CONSISTENT! • Naming conventions • Use descriptive names for classes, methods, and variables • By convention, class names begin with uppercase, method and variable names begin with lowercase, and constants are all uppercase.

  36. Comments • // for single line • /* */ for multiple lines • Comment at top of source file to identify the author and the purpose of the program • Comment to describe classes, methods, and sections of code (steps of the algorithm) Comments help readers understand the program code!

  37. Indentation and Spacing • Statements within blocks should be indented • Statements that are executed within control structures should be indented • If a statement continues from one line to the next, the subsequent line(s) should be indented. • Once logic seems to change a bit, a nice space between subsequent lines of code works well

  38. Block Styles • Choices: • Next-line: void myMethod() { --------- } • End-of-line: void myMethod(){ --------- } I like the first!

  39. Naming Conventions • Variables and method names: • Use lowercase • For example, the variables radiusand area • If the name consists of several words, concatenate all in one, use lowercase for the first word, and capitalize the first letter of each subsequent word in the name • For example, the method computeArea

  40. Naming Conventions, cont. • Class names: • Capitalize the first letter of each word in the name • For example, the class name TestComputeArea • Constants: • Capitalize all letters in constants • For example, the constant PI

  41. Putting it all together: Listing 2.1(available from Liang Code Samples)

  42. Variable declarations Assignment of literal value into variable Arithmetic expression and assignment Output with concatenated data values. Putting it all together: Listing 2.1

  43. The System class…this contains static member variable (out). PrintStream has a non-static (instance-specific) method called println The name (identifier) of the member variable The arguments passed to the println method A method Call The member variable (out) is an instance of another class (called PrintStream) System.out.println("The area for the circle of radius " + radius + " is " + area); This method does not return a value no assignment

  44. About the System Class • Part of the Java Class Library • Useful for standard input (keyboard) and output (screen) in console-based applications • More details from Oracle’s Java documentation site: • http://docs.oracle.com/javase/7/docs/api/

  45. Putting it all together: Listing 2.1 • A package is a collection of classes. In practice, a package is equivalent to a directory (folder). To indicate that a class is in a package, you must: • Place the .java file in the appropriate folder, and • Write a package statement with the appropriate package name as the first line of code in the .java file.

  46. Listing 2.11 ComputeLoanUsingInputDialog

  47. Listing 2.11 ComputeLoanUsingInputDialog If you are using a class that is not in your own package, or in the package java.lang, you must import that class.

  48. Listing 2.11 ComputeLoanUsingInputDialog Input from user and convert to appropriate data type.

  49. User Input via JOptionPane Object • JOptionPane is a class in the Java class library that can display an input dialog for obtaining user input or show message dialogs for display to the user. • Two methods: • showInputDialog – for user input • showMessageDialog – for displaying a message to the user

  50. The JOptionPane class…this contains static methods for displaying various types of dialogs The JOptionPane class’s ShowInputDialog method displays a dialog with parameters controlling the look. String annualInterestRateString = JOptionPane.showInputDialog( "Enter yearly interest rate, for example 8.25:");

More Related