1 / 30

TCU CoSc 10403 Programming with Java

TCU CoSc 10403 Programming with Java. Data Types and Operators. Java Identifiers. Identifiers are the words a programmer uses to identify particular items in a program. They may be used to name a variable (e.g. studentName), a class (e.g., HelloWorld), or a method (e.g., paint).

tlofton
Download Presentation

TCU CoSc 10403 Programming with Java

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. TCU CoSc 10403 Programming with Java Data Types and Operators

  2. Java Identifiers • Identifiers are the words a programmer uses to identify particular items in a program. • They may be used to name a variable (e.g. studentName), a class (e.g., HelloWorld), or a method (e.g., paint). • Most identifiers have no predefined meaning except as specified by the programmer. • Rules: • MUST begin with a letter (“A” … “Z”, or “a”… “z”) • contains letters, digits and underscores (and ‘$’ but you are discouraged from using it) • Naming Conventions • Classes begin with a capital letter (ex., HelloWorld) • Identifiers (variables & methods) do NOT start with a capital letter • Constants (called “final variables”) are ALL caps (ex., PI) • word separation: getMax, calcAvgGrade ***Note: Java is case sensitive. The identifier xyz is not the same as XYZ.

  3. Identifiers and Reserved Words • There are three categories of identifiers: • Words that we make up (e.g., HelloWorld and Lab0) 2. Words that another programmer chose (String, System, out, println, and main). • Often these are words that were chosen by a programmer for code that became part of a Java library; • Now available for use by all Java programmers. 3. Words that are reserved for special purposes in the language (class, public, static, extends, and void). • The designers of the Java language chose these words.

  4. Choosing Identifier Names Identifier names should be descriptive. • Avoid meaningless names such as a or x. • Unless the name is actually descriptive, such as using x and yto represent (x,y) coordinates. • Avoid using unnecessarily long names (unless they promote better readability - example: yearToDateSalary). • A “name” in Java is a series of identifiers separate by the dot (period) character. • The name System.out is the ‘name’ of an object through which we invoke the println method. (println is a method inside the object.)

  5. Variables - names • Descriptive of the data it represents • Using the alphabet is not acceptable: a, b, c, d, e; nor is a1, a2, a3, a4 • Lists of images in something like a slideshow can be namedimg1, img2, img3, etc. • No spaces allowed within a variable name • Convention is to begin variable names with a lower case letter and separate each word in the variable name by capitalizing subsequent words: - firstName, lastName, midtermGrade, labGrade • Abbreviations are good, but be consistent: - tempFreq, hitFreq, qtyCount, qtyOfShirts • Cannot use a Java keyword for a variable name No spaces in names!

  6. Variables • Instance variables • Declared at the top of a class • Data available to the entire class • Local variables • Declared within a method • Data only available within the method • Includes method parameters

  7. Instance vs. Local Variables import java.awt.*; import javax.swing.*; public class instanceVars extends JApplet { public void init( ) { // local variables JLabel name; JButton go; setLayout( new FlowLayout( ) ); name = new JLabel( "Cookie Monster"); go = new JButton( "GO!" ); add( name ); add( go ); } } import java.awt.*; import javax.swing.*; public class instanceVars extends JApplet { // instance variables JLabel name; JButton go; public void init( ) { setLayout( new FlowLayout( ) ); name = new JLabel( "Cookie Monster" ); go = new JButton( "GO!" ); add( name ); add( go ); } } Declared outside any methods Declared inside a method

  8. Scope of variables • Scope • Check out the enclosing braces ({}) • You cannot declare two variables of the same name at the same scope level • Any variable declared strictly within the scope of another with the same name will shadow the outer named variable

  9. Instance Variables • Most variables are declared at the top of the class – called instance variables public class Fun extends JApplet { // instance variables JButton b_submit ; JTextField tf_state; // methods public void init( ) { b_submit = new JButton( "Submit" ); ... } }

  10. Instance Variables • We do this so we can reference them throughout the program – called scope public class Fun extends JApplet implements ActionListener { // instance variables JButton b_submit; JTextField tf_state; // methods public void init( ) { b_submit = new JButton( "Submit" ); tf_state = new JTextField( "great", 10 ); doLeftSide( ); } public void doLeftSide( ) { JPanel p = new JPanel( new FlowLayout( ) ); p.add( b_submit ); p.add( tf_state ); } }

  11. Instance Variables • A problematic example follows: What's wrong and what happens? public class Fun extends JApplet implements ActionListener { // methods public void init( ) { JButton b_submit = new JButton( "Submit" ); JTextField tf_state = new JTextField( "great", 10 ); doLeftSide( ); } public void doLeftSide( ) { JPanel p = new JPanel( new FlowLayout( ) ); p.add( b_submit ); p.add( tf_state ); add( p ); } }

  12. Java Reserved Words * indicates a keyword that is not currently used ** indicates a keyword that was added for Java 2

  13. Operator Precedence in Java Operator precedence defines the order in which operators are evaluated. As an example, let's say we have the following line of Java code: int x = 4 + 3 * 5; The variable x gets the value of evaluating the expression 4 + 3 * 5. There are a couple of ways to evaluate the expression, though: We can either perform the addition first or perform the multiplication first. By choosing which operation to perform first, we are actually choosing between two different expressions: 1. (4 + 3) * 5 == 35 2. 4 + (3 * 5) == 19 In the absence of parentheses, which choice is appropriate? Programming languages answer this question by defining precedence levels for each operator, indicating which is to be performed first. In the case of Java, multiplication takes precedence over addition; therefore, x will get the value 19. For arithmetic expressions, multiplication and division are evaluated before addition and subtraction, just like in mathematics. Of course, you can always parenthesize Java expressions to indicate which are to be evaluated first. Sensible use of parentheses will make your programs easier to read even if your expressions all use the standard evaluation order.

  14. Data Types • There are 8 primitive data types provided in Java. • Note: below are the primitive data types; we also use a lot of objects as well. • The most commonly used ones are: int, float, double, char and boolean • Examples of objects are: buttons, strings, textfields, panels, fonts, etc

  15. Arithmetic Operators • Math operators work as you would expect, with two that may be new to you: • In Java, addition also works on strings by concatenating them together. - String fullname = "Elizabeth" + "Boese"; fullname is equal to “ElizabethBoese” - String result = "Version" + 2.0; result is equal to “Version2.0”

  16. Java arithmetic • Integer division • Throw away the remainder! • 9 / 4 = • Modulus • 9 % 4 = • How would you test to see if the int variable named val is even? • Widening conversions • 9.0 / 4 =

  17. Math class • Can use the constants and methods from the Math class • Math.PI • Math.pow( double x, double y ) • Math.round( double d ) • Math.sqrt( double d )

  18. Relational Operators • Relational operators return either true or false based on the operands • Note that the greater-than-or-equal-to operator has the = AFTER the >and the less-than-or-equal-to operator has the = AFTER the <This is Java, so on an exam do not try to put  or  as our keyboards don't have these symbols!!! You have been warned. • Note the difference between the two equal signs here and the assignment statement that contains only one equal sign. • Examples:

  19. Logical Operators Trials: when x = -3, when x = 5, when x = 6

  20. Careful testing Equality!! • Two primitive values (except floating point data types) are the same under == if their values are the same • For two class-type variables, == is true ONLY if the variables REFER TO THE SAME OBJECT!

  21. Conditional Operators • Conditional operators return either true or false based on boolean operands • Examples

  22. Truth Tables

  23. The wonderful instanceof Operator • Test whether a variable is a particular class type by using the instanceof operator • Variable instanceof class-type B instanceof JButton B instanceof MyOwnButton Mb instanceof JFrame • Can not check if something is an instance of a primitive data type!

  24. Expressions • Precedence “order of operations” • Parenthesis first • unary operators (pos/neg, ++ -- if before variable, !) • *, /, % • +, - • < <= > >= instanceof • == != • && • || • = • 3 * ( 2 + ( 3 – 4 * 2 + (5-1 ) ) ) =

  25. Characters • Data type: char • Enclose with single quotes (Strings use double quotes (")) char grade= ‘A’; char code = ‘!’; • Escape sequences char singleQuote = ‘\’’; Char newLine = ‘\n’;

  26. String to numbers • Call methods on the class (Integer, Double, Character, etc.) Class:Method Integer parseInt( String ) Double parseDouble( String ) • Examples int value = Integer.parseInt( string ); double value = Double.parseDouble( string ); int numShirts = Integer.parseInt( textfieldNumShirts.getText( ) );

  27. Strings • Not a primitive data type • A class – the String class – but acts like a primitive. • Examples: String title = “COSC 10403”; String semester = “Fall”; • Instantiated as a new instance (object) of a class: String school = new String(“TCU”);

  28. Numbers to String • Call method from the String class: String.valueOf( number ) • Examples To set the text inside a JTextField, we have to send it a String (not an int or double). So we can convert a number to a String with String.valueOf( number ) tfcartTotal.setText( String.valueOf( totalCost ) ); • What's another 'hack' way to convert a number to a String? append the number to an empty String (2 dbl-quotes)  String tfcartTotal.setText( “” + totalCost );

  29. Summary • Conversions • String to number • Number to String • Variables • Names • Java keywords • Data types • Scope • Instance vs. local variables • Math • Arithmetic • Relational operators • Logical • Equality • Conditional • Order of precedence

  30. Boolean • One of two values • true • false boolean isSenior = false; boolean livesOnCampus = true;

More Related