Java Syntax - PowerPoint PPT Presentation

1 / 61
About This Presentation
Title:

Java Syntax

Description:

So we need to start out by building 'toy' programs ... 'Greetings'); Exiting a Program ... JOptionPane.showInputDialog('Greetings'); NumberFormat formatter ... – PowerPoint PPT presentation

Number of Views:61
Avg rating:3.0/5.0
Slides: 62
Provided by: coba1
Category:
Tags: java | syntax

less

Transcript and Presenter's Notes

Title: Java Syntax


1
Java Syntax
2
Introduction
  • As mentioned in the chapter, we need a bit of
    'machinery' to display windows and build a GUI
  • So we need to start out by building 'toy'
    programs
  • Today we discuss the basics of the Java language
  • I'll cover this chapter in the precise order that
    the topics are presented
  • The authors have really done a great job here

3
Comments
  • / and / are comment markers
  • Comments do not nest
  • Comments may span multiple lines
  • // is the single line comment marker
  • / This is a comment appearing on
  • two lines. /
  • // And this is a comment on one line.

4
A Word about Packages
  • Classes are organized into packages
  • Packages are the same as .NET namespaces
  • Use the import statement as in
  • import java.lang.String.

5
Statement Format
  • A semicolon terminates a statement
  • A physical line means nothing
  • Statements can span multiple lines
  • There exists no continuation character as in VB
    .NET.

6
Variables (Types)
  • Java is strongly typed
  • EVERY variable must be declared with a type
  • There are 8 primitive data types
  • Whole numbers
  • byte, short, int, long
  • Floating point numbers
  • float, double
  • Character
  • char - Note that this is not a string
  • Boolean
  • true and false

7
Whole Number Types
  • byte (1 bytes)
  • short (2 bytes)
  • int (4 bytes)
  • long (8 bytes)
  • Value has a suffix of "L" for long
  • All of these are signed types Java does not
    support unsigned types

8
Floating Point Types
  • float (4 bytes)
  • 6-7 digits of precision
  • Suffix constant values with "F"
  • double (8 bytes)
  • 15 digits of precision
  • Suffix constant values with "D"
  • These types are not acceptable for financial
    calculations because of rounding errors
  • Use the BigDecimal class instead

9
Numeric Overflow
  • Division by 0 evaluates to constant value
    Double.POSITIVE_INFINITY
  • Square root of a negative number produces NaN
    (Not a Number)
  • Use double.isNaN(x) to check

10
The Character Type (1)
  • The data type is char
  • This is not the same as a String String is a
    class
  • Surround literal values with a single quote
    character
  • Java uses Unicode encoding rather than ASCII
    encoding

11
The Character Type (2)
  • Use C-like escape sequences for non-printable
    characters
  • \b - backspace
  • \t - tab
  • \n - linefeed
  • \r - carriage return
  • \" - double quote
  • \' - single quote
  • \\ - backslash

12
The Boolean Type
  • Represents the values true and false
  • Note that these are reserved words
  • Unlike in C, integers are not converted to
    boolean values
  • Internally, 0 is false
  • All other values are true

13
Variable Naming
  • Variables must begin with a letter and not
    contain special characters
  • Underscore ( _ ) character is legal
  • CASE SENSITIVE
  • All variables must be declared with an explicit
    type
  • Suggest using camel-case for variable names
  • First word is all lower case
  • Capitalize the first character of subsequent
    words

14
Declaring Variables
  • Note that variables MUST be initialized before
    they are used
  • Variable declarations can appear anywhere
  • They need not appear at the beginning of a module
  • type varname ,varname
  • int counter
  • float radius 3.8
  • boolean isValid true
  • char firstLetter a
  • int counter1, counter2

15
Constants
  • The final keyword denotes a constant
  • A value can be assigned to a constant only once
  • Constant names typically appear in upper case
  • Example
  • final double PI 3.14

16
Operators (Arithmetic)
  • (Addition)
  • Subtraction
  • (Multiplication)
  • / (Division)
  • If both operands are integers then integer
    division is performed
  • Integer division by 0 throws an exception
  • Otherwise floating point division is performed
  • (Integer remainder)
  • Same as Mod function in VB

17
Increment and Decrement Operators
  • Increment ()
  • x // adds 1 to x
  • Decrement (--)
  • x-- // subtracts 1 from x
  • Prefix vs. postfix
  • y 2 x
  • x is incremented before the multiplication
  • y 2 x
  • x is incremented after the multiplication

18
Operators ( Relational)
  • Relational operators return true or false
  • (Equality)
  • ! (Inequality)
  • gt (Greater than)
  • lt (Less than)
  • gt (Greater than or equal to)
  • lt (Less than or equal to)

19
Operators (Logical)
  • (And)
  • (Or)
  • Logical operators support short circuiting
  • Evaluates from left to right
  • Once a sub-expression is deemed to be False,
    evaluation of subsequent sub-expressions is
    terminated
  • See table 3-4 on page 49 for operator precedence
    and operator associatively

20
Operators (Bitwise)
  • Bitwise operators operate on whole number types
    (We don't do much bit fiddling in business
    applications)
  • (And)
  • (Or)
  • (XOr)
  • (Not)
  • gtgt (Shift right)
  • ltlt (Shift left)

21
Mathematical Functions
  • Provided by the Math class
  • Note that these methods are static methods (more
    about this later)
  • Math.sin, Math.cos, Math.tan, etcMath.PI,
    Math.E are constants
  • Note that Java has no exponent () operator
  • Use the pow method of the Math class
  • double y pow(x, a)

22
Type Conversion (1)
  • When evaluating an expression, Java converts
    operands to a common type before evaluating the
    expression
  • Conversion is to the least restrictive type

23
Type Conversion (2)
  • Implicit type conversion is only performed from a
    more restrictive type to a less restrictive type
  • See Table 3-1 on page 49
  • Use a cast to perform explicit type
    conversionOut of bounds casts will produce
    incorrect results
  • Same as CType function in .NET
  • Example to convert a double to an int
  • Fractional value is truncated rather than
    roundeddouble x 3.1415int nx (int)x

24
Operator Precedence
  • Refer to Table 3-4 on page 49
  • All operators have an order of precedence
  • Note that operators have associativity

25
Strings Introduction (1)
  • String is not a type in Java Its a built-in
    class
  • Strings are immutable
  • We will talk about string pools and why immutable
    strings are good later
  • Character positions are 0-based
  • Java performs automatic garbage collection on
    strings
  • This is true of all other class instances

26
Strings Introduction (2)
  • A string is a sequence of characters
  • Unlike C, you need not suffix a string with a
    null byte
  • () is the string concatenation operator unlike
    () in VB .NET
  • Note that the () operator is overloaded in this
    context.
  • When concatenation is performed, non-string
    variables are implicitly converted to strings
  • Java (like .NET) can convert any type to a string
  • Refer to the list on page 53 for additional
    functions

27
String Methods (1)
  • See list on page 53
  • substring extracts a sub string from a string
  • First argument contains starting character
    position (0-based)
  • Second argument contains the number of characters
  • String myName "Michael Ekedahl"
  • String s myName.substring(0, 7)

28
String Methods (2)
  • equals method compares two strings for value
    equality
  • equalsIgnoreCase compares for value equality but
    comparison is case insensitive
  • Do not use as it tests only for reference
    equality rather than value equality
  • Example
  • String s1 "Name"
  • String s2 "Name"
  • Boolean b
  • b s1.equals(s2)

29
String Methods (3)
  • charAt gets the character as a position
  • Returns a Char data type
  • Position is 0 based
  • length gets the length of a string
  • The value is 1-based
  • Length returns an int
  • compareTo compares two strings for equality or
    inequality

30
String Examples
  • Declare an empty string
  • String s
  • Declare an initialized string
  • String s Hello
  • Concatenate a string
  • s s World

31
Getting Input
  • Writing to standard output is easy. Reading from
    standard input is not
  • To get by, we show how to create an input dialog
  • Import the javax.swing. package
  • Display the input dialog as in
  • String input JOptionPane.showInputDialog(
    "Greetings")

32
Exiting a Program
  • By default, Java does not return an exit code to
    the operating system.
  • java.lang.System package contains an exit method
    to return a value from a Java program
  • System.Exit(3)

33
Output Formatting
  • java.text package has three method that return a
    standard formatter
  • NumberFormat.getNumberInstance()
  • To format numbers
  • NumberFormat.getCurrencyInstance()
  • To format currency values
  • NumberFormat.getPercentInstance()
  • To format percentage values
  • Call the format method to actually perform the
    formatting

34
Output Formatting Example
  • Format a number as currency
  • String input
  • JOptionPane.showInputDialog("Greetings")
  • NumberFormat formatter
  • NumberFormat.getCurrencyInstance()
  • double dblInput Double.parseDouble(input)
  • System.out.println(
  • formatter.format(dblInput))

35
Numeric Precision
  • Primitive types don't work well for financial
    calculations because of rounding errors
  • The java.math package contains two classes to fix
    the problem
  • BigInteger works with Integer values
  • BigDecimal works with floating point values
  • Cannot use arithmetic operators with these types.
    Use methods such as Add, Subtract, Multiply, and
    Divide

36
BigDecimal Example
  • BigDecimal bd1 BigDecimal.valueOf(1)
  • BigDecimal bd2 BigDecimal.valueOf(2)
  • BigDecimal result
  • result bd1.divide(bd2,
  • BigDecimal.ROUND_HALF_UP)
  • System.out.println(result)

37
Block Scope
  • A block contains one or more statements
    surrounded by braces
  • Variables declared in a block have a scope of the
    block containing the declaration
  • A variable cannot be redefined in an inner block

38
Conditional Statements (1)
  • Note that the condition MUST be surrounded by
    parenthesis
  • Note the if and else are all lower case
  • Unlike VB, marks the block of the if
    statement
  • if (condition)
  • Statements
  • else
  • Statements

39
Conditional Statements (2)
  • The else if version has a similar syntax
  • if (condition)
  • Statements
  • else if (condition )
  • Statements
  • else
  • Statements

40
Conditional Statements (Example)
  • A simple If statement
  • if (value gt Math.PI)
  • System.out.println(Greater than or )
  • else
  • System.out.println(Less than)

41
Multiple Selection
  • The switch statement is a limited form of the if
    statement
  • Syntax is the same as in C
  • Similar to a VB Select Case statement
  • Condition is tested once for multiple alternatives

42
Switch Statement Syntax
  • switch (expression)
  • case value1
  • statements
  • break
  • case value2
  • statements
  • break
  • default
  • statements
  • break

43
Indeterminate Loops
  • Use an indeterminate loop when you dont know in
    advance how many times the loops statements will
    execute
  • Java supports two forms
  • A while loop executes statements while a
    condition is true
  • Statements in the loop body may never execute
  • A do loop executes statements first and then
    tests the condition
  • Statements in the loop body will execute at least
    once

44
Indeterminate Loops (while)
  • Condition evaluates to a boolean value
  • Statements only execute while the condition is
    true
  • mark the block of statements
  • while (condition)
  • statements

45
Indeterminate Loops (do)
  • Executes statement body before testing the
    condition
  • do
  • statements
  • while (condition)

46
Determinate Loops
  • Determinate loops are used when the iteration
    count is known in advance
  • Commonly used to iterate through the elements of
    an array
  • Use whole numbers as floating point errors will
    cause serious problems
  • Any for loop can be written as a while loop but
    not the other way around

47
Determinate Loops (for)
  • Syntax
  • for (statement1 expression1 expression2)
  • statements
  • Statement1 initializes the counter
  • Expression1 supplies the terminal condition
  • Expression2 updates the counter
  • A semicolon separates each segment

48
For Loop example
  • Print the counting numbers from 1 to 10
  • int i
  • for (i 1 i lt 10 i)
  • System.out.println(i)

49
Arrays
  • Arrays contain multiple elements of the same type
  • Arrays are 0-based
  • Unlike C arrays, you cannot perform pointer
    arithmetic
  • Java arrays perform bounds checking
  • No need to worry about walking over memory
  • Compared to VB, use instead of ( )

50
Declaring Arrays
  • Declare an array variable (note that the
    following does not initialize the array)
  • int Alist

51
Array Initializers
  • Arrays are initialized with the new keyword
  • New as the same meaning as it does in .NET
  • Note the following initializes the array with 100
    elements having subscripts from 0 to 99
  • int AList new int100

52
Array Initializers
  • Arrays can be initialized using C-like syntax
  • Note that new keyword is omitted using this
    syntax
  • int Alist 1, 2, 3, 4, 5
  • Or
  • Alist new int 1, 2, 3, 4, 5
  • The preceding syntax can be used to reinitialize
    an existing array

53
Copying Arrays (1)
  • Again, this works the same way in .NET
  • Assignment of an array does not copy the data
    Rather the two variables point to the same array
    (memory)
  • int AList 1 ,2 ,3 ,4 , 5
  • int BList AList
  • AList and BList both reference the same array
    memory

54
Copying Arrays (2)
  • Call System.arrayCopy to copy array data thereby
    allocating new memory
  • System.arraycopy(from, fromIndex, to toIndex,
    count)

55
Arrays and Command Line Parameters
  • Main accepts an array of string as an argument
  • Note that Java does not store the program name as
    the first argument as we would in C
  • Print the first command line argument
  • Public static void main(String args)
  • System.out.println(args0)

56
Sorting Arrays
  • Call the Sort method of the Arrays class
  • Note Java uses a version of the QuickSort
    algorithm
  • int Alist 32, 24, 33, 18, 12
  • Arrays.Sort(Alist)

57
MultiDimensional Arrays
  • Add additional subscripts for each dimension
  • Declare 2-dimensional array
  • int TableArray
  • Declare and initialize the array. Note the use of
    nested
  • int TableArray 1,2 , 3, 4

58
Static Variables
  • static keyword declares a variable that is shared
    across classes
  • public static final single PI 3.14

59
Block Scope
  • Braces form a block
  • Variables declared in a block have block scope
  • Variables can be declared in nested blocks
  • Variables in an outer block cannot be redefined
    in an inner block
  • C does allow this but .NET does not
  • VB 6 did not have block scope at all

60
The Help System
  • http//java.sun.com/j2se/1.4.2/docs/api/index.html

61
For next time
  • Read chapter 4
Write a Comment
User Comments (0)
About PowerShow.com