Chapter 2 introduction to java applications
This presentation is the property of its rightful owner.
Sponsored Links
1 / 107

Chapter 2 - Introduction to Java Applications PowerPoint PPT Presentation


  • 33 Views
  • Uploaded on
  • Presentation posted in: General

Chapter 2 - Introduction to Java Applications.

Download Presentation

Chapter 2 - Introduction to Java Applications

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.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript


Chapter 2 introduction to java applications

Chapter 2 - Introduction to Java Applications

Outline2.1Introduction2.2A First Program in Java: Printing a Line of Text 2.3Modifying Our First Java Program 2.4Displaying Text in a Dialog Box2.5 Another Java Application: Adding Integers2.6Memory Concepts2.7Arithmetic2.8Decision Making: Equality and Relational Operators


2 1 introduction

2.1Introduction

  • In this chapter

    • Introduce examples to illustrate features of Java

    • Simple java programs

      • displaying messages

      • geting information from the user

      • performing aritmetic and logical opperations

      • primitive types in java

      • illiustrate decision making


2 2 a first program in java printing a line of text

2.2A First Program in Java: Printing a Line of Text

  • Application

    • Program that executes using the java interpreter

  • Sample program

    • Show program, then analyze each line


Welcome1 java program output

1 // Fig. 2.1: Welcome1.java

2 // Text-printing program.

3

4 public class Welcome1 {

5

6 // main method begins execution of Java application

7 public static void main( String args[] )

8 {

9 System.out.println( "Welcome to Java Programming!" );

10

11 } // end method main

12

13 } // end class Welcome1

Welcome1.javaProgram Output

Welcome to Java Programming!


2 2 a first program in java printing a line of text1

1 // Fig. 2.1: Welcome1.java

2 // Text-printing program.

2.2 A First Program in Java: Printing a Line of Text

  • Comments start with: // end of line comment

    • Comments ignored during program execution

    • Document and describe code

    • Provides code readability

  • Traditional comments: /* ... */

    /* This is a traditional comment. It can be split over many lines */

  • Another line of comments

  • Note: line numbers not part of program, added for reference


2 2 a first program in java printing a line of text2

2.2 A First Program in Java: Printing a Line of Text

  • javadoc comments

    • delimited by /** end */

    • all text between the delimiter is ignored as in treditional comments

    • the javadoc utility program

      • reads javadoc comments and prepare a documentation in HTML format

      • eee Appendix K


2 2 a simple program printing a line of text

3

4 public class Welcome1 {

2.2A Simple Program: Printing a Line of Text

  • Blank line

    • Makes program more readable

    • Blank lines, spaces, and tabs are white-space characters

      • Ignored by compiler

  • Begins class declaration for class Welcome1

    • Every Java program has at least one user-defined class

    • Keyword: words reserved for use by Java

      • class keyword followed by class name

    • Naming classes: capitalize every word

      • SampleClassName


2 2 a simple program printing a line of text1

4 public class Welcome1 {

2.2A Simple Program: Printing a Line of Text

  • Name of class called identifier

    • Series of characters consisting of letters, digits, underscores ( _ ) and dollar signs ( $ )

    • Does not begin with a digit, has no spaces

    • Examples: Welcome1, $value, _value, button7

      • 7button, first line are invalid

    • Java is case sensitive (capitalization matters)

      • a1 and A1 are different

  • For chapters 2 to 7, use public keyword

    • Certain details not important now

    • Mimic certain features, discussions later


2 2 a simple program printing a line of text2

4 public class Welcome1 {

7 public static void main( String args[] )

2.2A Simple Program: Printing a Line of Text

  • Saving files

    • File name must be class name with .java extension

    • Welcome1.java

  • Left brace {

    • Begins body of every class decleration

    • Right brace ends declarations (line 13)

  • Part of every Java application

    • Applications begin executing at main

      • Parenthesis indicate main is a method (ch. 6)

      • Java applications contain one or more methods


2 2 a simple program printing a line of text3

7 public static void main( String args[] )

8 {

2.2A Simple Program: Printing a Line of Text

  • Exactly one method must be called main

  • Methods can perform tasks and return information

    • void means main returns no information

    • For now, mimic main's first line

  • Left brace begins body of method declaration

    • Ended by right brace } (line 11)


  • 2 2 a simple program printing a line of text4

    9 System.out.println( "Welcome to Java Programming!" );

    2.2A Simple Program: Printing a Line of Text

    • Instructs computer to perform an action

      • Prints string of characters

        • String - series characters inside double quotes

      • White-spaces in strings are not ignored by compiler

    • System.out

      • Standard output object

      • Print to command window (i.e., MS-DOS prompt)

    • Method System.out.println

      • Displays line of text

      • Argument inside parenthesis

      • compleating printing, position the cursor to tbe begiining of next line

    • This line known as a statement

      • Statements must end with semicolon ;


    2 2 a simple program printing a line of text5

    11 } // end method main

    13 } // end class Welcome1

    2.2A Simple Program: Printing a Line of Text

    • Ends method declaration

    • Ends class declaration

    • Can add comments to keep track of ending braces

    • Lines 8 and 9 could be rewritten as:

    • Remember, compiler ignores comments

    • Comments can start on same line after code


    2 2 a simple program printing a line of text6

    2.2A Simple Program: Printing a Line of Text

    • Compiling a program

      • Open a command prompt window, go to directory where program is stored

      • Type javacWelcome1.java

      • If no errors, Welcome1.class created

        • Has bytecodes that represent application

        • Bytecodes passed to Java interpreter


    2 2 a simple program printing a line of text7

    2.2A Simple Program: Printing a Line of Text

    • Executing a program

      • TypejavaWelcome1

        • Interpreter loads .class file for class Welcome1

        • .class extension omitted from command

      • Interpreter calls method main

    Fig. 2.2Executing Welcome1 in a Microsoft Windows 2000 Command Prompt.


    2 3 modifying our first java program

    2.3Modifying Our First Java Program

    • Modify example in Fig. 2.1 to print same contents using different code


    2 3 modifying our first java program1

    9 System.out.print( "Welcome to " );

    10 System.out.println( "Java Programming!" );

    2.3Modifying Our First Java Program

    • Displaying single line of text with multiple statemetns

      • Welcome2.java (Fig. 2.3) produces same output as Welcome1.java (Fig. 2.1)

      • Using different code

      • Line 9 displays “Welcome to ” with cursor remaining on printed line

      • Line 10 displays “Java Programming! ” on same line with cursor on next line


    Chapter 2 introduction to java applications

    System.out.print keeps the cursor on the same line, so System.out.printlncontinues on the same line.

    1 // Fig. 2.3: Welcome2.java

    2 // Printing a line of text with multiple statements.

    3

    4 public class Welcome2 {

    5

    6 // main method begins execution of Java application

    7 public static void main( String args[] )

    8 {

    9 System.out.print( "Welcome to " );

    10 System.out.println( "Java Programming!" );

    11

    12 } // end method main

    13

    14 } // end class Welcome2

    Welcome2.java1. Comments2. Blank line3. Begin class Welcome23.1 Method main4. Method System.out.print4.1 Method System.out.println5. end main,Welcome2Program Output

    Welcome to Java Programming!


    2 3 modifying our first java program2

    9 System.out.println( "Welcome\nto\nJava\nProgramming!" );

    2.3Modifying Our First Java Program

    • Displaying multiple lines of text with single statement

    • Newline characters (\n)

      • Interpreted as “special characters” by methods System.out.print and System.out.println

      • Indicates cursor should be on next line

      • Welcome3.java (Fig. 2.4)

      • Line breaks at \n

    • Usage

      • Can use in System.out.println or System.out.print to create new lines

        • System.out.println("Welcome\nto\nJava\nProgramming!" );


    Welcome3 java 1 main 2 system out println uses n for new line program output

    Notice how a new line is output for each \n escape sequence.

    1 // Fig. 2.4: Welcome3.java

    2 // Printing multiple lines of text with a single statement.

    3

    4 public class Welcome3 {

    5

    6 // main method begins execution of Java application

    7 public static void main( String args[] )

    8 {

    9 System.out.println( "Welcome\nto\nJava\nProgramming!" );

    10

    11 } // end method main

    12

    13 } // end class Welcome3

    Welcome3.java1. main2. System.out.println (uses \n for new line)Program Output

    Welcome

    to

    Java

    Programming!


    2 3 modifying our first java program3

    2.3Modifying Our First Java Program

    Escape characters

    • Backslash ( \ )

    • Indicates special characters be output


    2 4 displaying text with printf

    2.4Displaying Text with printf

    • System.out.printf method

      • displaying formated data in Java SE 5.0

      • same output in figure 2çwith printf

        System.out.printf(“%s\n%s\n”,

        “Welcome to”,”Java programming”);

      • Line 9 displays “Welcome to ” with cursor remaining on printed line

      • Line 10 displays “Java Programming! ” on same line with cursor on next line

    • The method has three arguments

      • comma seperated list


    2 4 displaying text with printf1

    2.4Displaying Text with printf

    • Line 9-10 one statement

      • can be split into more then one line

      • ends with ;

      • can not be splitted

        • identifiers or

        • strings

    • first argumet:

      • format string

        • fixed text

        • format specifiers

    • format specifiers

      • begins with a % followed by a character

        • s for stringsf: float

        • d for integerslf:double


    Chapter 2 introduction to java applications

    1 // Fig. 2.6: Welcome4.java

    2 // Printing multiple lines with printf.

    3

    4 public class Welcome4 {

    5

    6 // main method begins execution of Java application

    7 public static void main( String args[] )

    8 {

    9 System.out.printf( “%s\n%s\n “,

    10 “Welcome to”,"Java Programming!" );

    11

    12 } // end method main

    13

    14 } // end class Welcome4

    output of program

    Welcome to

    Java Programming!


    3 9 displaying text in a dialog box

    3.9Displaying Text in a Dialog Box

    • Display

      • Most Java applications use windows or a dialog box

        • We have used command window

      • Class JOptionPane allows us to use dialog boxes

    • Packages

      • Set of predefined classes for us to use

      • Groups of related classes called packages

        • Group of all packages known as Java class library or Java applications programming interface (Java API)

      • JOptionPane is in the javax.swing package

        • Package has classes for using Graphical User Interfaces (GUIs)


    3 9 displaying text in a dialog box1

    3.9Displaying Text in a Dialog Box

    • Upcoming program

      • Application that uses dialog boxes

      • Explanation will come afterwards

      • Demonstrate another way to display output

      • Packages, methods and GUI


    Chapter 2 introduction to java applications

    1// Fig. 2.6: Welcome4.java

    2// Printing multiple lines in a dialog box

    3import javax.swing.JOptionPane; // import class JOptionPane

    4

    5public class Welcome4 {

    6 public static void main( String args] )

    7 {

    8 JOptionPane.showMessageDialog(

    9 null, "Welcome\nto\nJava\nProgramming!" );

    10

    11 System.exit( 0 ); // terminate the program

    12 }

    1 // Fig. 2.6: Welcome4.java

    2 // Printing multiple lines in a dialog box.

    3

    4 // Java packages

    5 import javax.swing.JOptionPane; // program uses JOptionPane

    6

    7 public class Welcome4 {

    8

    9 // main method begins execution of Java application

    10 public static void main( String args[] )

    11 {

    12 JOptionPane.showMessageDialog(

    13 null, "Welcome\nto\nJava\nProgramming!" );

    14

    15

    16

    17 } // end method main

    18

    19 } // end class Welcome4

    Welcome4.java1. import declaration2. Class Welcome42.1main2.2showMessageDialog2.3 System.exitProgram Output


    Chapter 2 introduction to java applications

    1 // Fig. 3.17 Dialog1.java

    2 // Printing multiple lines in a dialog box.

    3

    4 // Java packages

    5 import javax.swing.JOptionPane; // program uses JOptionPane

    6

    7 public classDialog1 {

    8

    9 // main method begins execution of Java application

    10 public static void main( String args[] )

    11 {

    12 JOptionPane.showMessageDialog(

    13 null, "Welcome\nto\nJava\nProgramming!" );

    14

    15 } // end method main

    16

    17} // end class Dialog1


    3 9 displaying text in a dialog box2

    4 // Java packages

    5 import javax.swing.JOptionPane; // program uses OptionPane

    3.9 Displaying Text in a Dialog Box

    • Lines 1-2: comments as before

    • Two groups of packages in Java API

    • Core packages

      • Begin with java

      • Included with Java 2 Software Development Kit

    • Extension packages

      • Begin with javax

      • New Java packages

    • import declarations

      • Used by compiler to identify and locate classes used in Java programs

      • Tells compiler to load class JOptionPane from javax.swing package


    3 9 displaying text in a dialog box3

    12 JOptionPane.showMessageDialog(

    13 null, "Welcome\nto\nJava\nProgramming!" );

    3.9 Displaying Text in a Dialog Box

    • Lines 6-11: Blank line, begin class Welcome4 and main

    • Call method showMessageDialog of class JOptionPane

      • Requires two arguments

      • Multiple arguments separated by commas (,)

      • For now, first argument always null

      • Second argument is string to display

    • showMessageDialog is a static method of class JOptionPane

      • static methods called using class name, dot (.) then method name


    3 9 displaying text in a dialog box4

    3.9 Displaying Text in a Dialog Box

    • All statements end with ;

      • A single statement can span multiple lines

      • Cannot split statement in middle of identifier or string

    • Executing lines 12 and 13 displays the dialog box

      • Automatically includes an OK button

        • Hides or dismisses dialog box

      • Title bar has string Message


    3 9 displaying text in a dialog box5

    3.9 Displaying Text in a Dialog Box

    • Class System part of package java.lang

      • No import declaration needed

      • java.lang automatically imported in every Java program

    • Lines 17-19: Braces to end Welcome4 and main


    2 5 another java application adding integers

    2.5Another Java Application: Adding Integers

    • Upcoming program

      • Use input dialogs to input two values from user

      • Use message dialog to display sum of the two values


    Chapter 2 introduction to java applications

    Declare variables: name and type.

    Input first integer as a String, assign to firstNumber.

    Convert strings to integers.

    Add, place result in sum.

    1 // Fig. 2.9: Addition.java

    2 // Addition program that displays the sum of two numbers.

    3

    4 // Java packages

    5 import javax.swing.JOptionPane; // program uses JOptionPane

    6

    7 public class Addition {

    8

    9 // main method begins execution of Java application

    10 public static void main( String args[] )

    11 {

    12 String firstNumber; // first string entered by user

    13 String secondNumber; // second string entered by user

    14

    15 int number1; // first number to add

    16 int number2; // second number to add

    17 int sum; // sum of number1 and number2

    18

    19 // read in first number from user as a String

    20 firstNumber = JOptionPane.showInputDialog( "Enter first integer" );

    21

    22 // read in second number from user as a String

    23 secondNumber =

    24 JOptionPane.showInputDialog( "Enter second integer" );

    25

    26 // convert numbers from type String to type int

    27 number1 = Integer.parseInt( firstNumber );

    28 number2 = Integer.parseInt( secondNumber );

    29

    30 // add numbers

    31 sum = number1 + number2;

    32

    Addition.java1. import2. class Addition2.1 Declare variables (name and type)3. showInputDialog4. parseInt5. Add numbers, put result in sum


    Program output

    33 // display result

    34 JOptionPane.showMessageDialog( null, "The sum is " + sum,

    35 "Results", JOptionPane.PLAIN_MESSAGE );

    36

    37

    38

    39 } // end method main

    40

    41 } // end class Addition

    Program output


    Chapter 2 introduction to java applications

    import javax.swing.JOptionPane; // program uses JOptionPane

    public class Addition {

    // main method begins execution of Java application

    public static void main( String args[] )

    {

    String firstNumber; // first string entered by user

    String secondNumber; // second string entered by user

    int number1; // first number to add

    int number2; // second number to add

    int sum; // sum of number1 and number2

    // read in first number from user as a String

    firstNumber = JOptionPane.showInputDialog( "Enter first integer" );

    // read in second number from user as a String

    secondNumber =

    JOptionPane.showInputDialog( "Enter second integer" );


    Chapter 2 introduction to java applications

    number1 = Integer.parseInt( firstNumber );

    number2 = Integer.parseInt( secondNumber );

    // add numbers

    sum = number1 + number2;

    // display result

    JOptionPane.showMessageDialog( null, "The sum is " + sum,

    "Results", JOptionPane.PLAIN_MESSAGE );

    } // end method main

    } // end class Addition


    2 5 another java application adding integers1

    5 import javax.swing.JOptionPane; // program uses JOptionPane

    7 public class Addition {

    12 String firstNumber; // first string entered by user

    13 String secondNumber; // second string entered by user

    2.5Another Java Application: Adding Integers

    • Location of JOptionPane for use in the program

    • Begins public class Addition

      • Recall that file name must be Addition.java

    • Lines 10-11: main

    • Declaration

      • firstNumber and secondNumber are variables


    2 5 another java application adding integers2

    String firstNumber, secondNumber;

    12 String firstNumber; // first string entered by user

    13 String secondNumber; // second string entered by user

    2.5Another Java Application: Adding Integers

    • Variables

      • Location in memory that stores a value

        • Declare with name and type before use

      • firstNumber and secondNumber are of type String (package java.lang)

        • Hold strings

      • Variable name: any valid identifier

      • Declarations end with semicolons ;

        • Can declare multiple variables of the same type at a time

        • Use comma separated list

    • Can add comments to describe purpose of variables


    2 5 another java application adding integers3

    15 int number1; // first number to add

    16 int number2; // second number to add

    17 int sum; // sum of number1 and number2

    2.5Another Java Application: Adding Integers

    • Declares variables number1, number2, and sum of type int

      • int holds integer values (whole numbers): i.e., 0, -4, 97

      • Types float and double can hold decimal numbers

      • Type char can hold a single character: i.e., x, $, \n, 7

      • Primitive types - more in Chapter 4


    2 5 another java application adding integers4

    20 firstNumber = JOptionPane.showInputDialog( "Enter first integer" );

    2.5Another Java Application: Adding Integers

    • Reads String from the user, representing the first number to be added

      • Method JOptionPane.showInputDialog displays the following:

      • Message called a prompt - directs user to perform an action

      • Argument appears as prompt text

      • If wrong type of data entered (non-integer) or click Cancel, error occurs


    2 5 another java application adding integers5

    20 firstNumber = JOptionPane.showInputDialog( "Enter first integer" );

    2.5Another Java Application: Adding Integers

    • Result of call to showInputDialog given to firstNumber using assignment operator =

      • Assignment statement

      • = binary operator - takes two operands

        • Expression on right evaluated and assigned to variable on left

      • Read as:firstNumber gets value of JOptionPane.showInputDialog( "Enter first integer" )


    2 5 another java application adding integers6

    23 secondNumber =

    24 JOptionPane.showInputDialog( "Enter second integer" );

    27 number1 = Integer.parseInt( firstNumber );

    28 number2 = Integer.parseInt( secondNumber );

    2.5Another Java Application: Adding Integers

    • Similar to previous statement

      • Assigns variable secondNumber to second integer input

    • Method Integer.parseInt

      • Converts String argument into an integer (type int)

        • Class Integer in java.lang

      • Integer returned by Integer.parseInt is assigned to variable number1 (line 27)

        • Remember that number1 was declared as type int

      • Line 28 similar


    2 5 another java application adding integers7

    31 sum = number1 + number2;

    2.5Another Java Application: Adding Integers

    • Assignment statement

      • Calculates sum ofnumber1 and number2 (right hand side)

      • Uses assignment operator = to assign result to variable sum

      • Read as:sum gets the value of number1 + number2

      • number1 and number2are operands


    2 5 another java application adding integers8

    34 JOptionPane.showMessageDialog( null, "The sum is " + sum,

    35 "Results", JOptionPane.PLAIN_MESSAGE );

    2.5Another Java Application: Adding Integers

    • Use showMessageDialog to display results

    • "Thesumis"+sum

      • Uses the operator + to "add" the string literal "Thesumis" and sum

      • Concatenation of a String and another type

        • Results in a new string

      • If sum contains 117, then "Thesumis"+sum results in the new string "Thesumis117"

      • Note the space in "Thesumis"


    2 5 another java application adding integers9

    34 JOptionPane.showMessageDialog( null, "The sum is " + sum,

    35 "Results", JOptionPane.PLAIN_MESSAGE );

    2.5Another Java Application: Adding Integers

    • Different version of showMessageDialog

      • Requires four arguments (instead of two as before)

      • First argument: null for now

      • Second: string to display

      • Third: string in title bar

      • Fourth: type of message dialog with icon

        • Line 35 no icon: JOptionPane.PLAIN_MESSAGE


    2 5 another java application adding integers10

    2.5Another Java Application: Adding Integers


    2 5 another java application adding integers11

    2.5Another Java Application: Adding Integers

    • Upcoming program

      • Use Scanner class to input two values from the console


    Chapter 2 introduction to java applications

    1 // Fig. 2.7: Addition.java

    2 // Addition program that displays the sum of two numbers.

    3import java.util.Scanner; // program uses class Scanner

    4

    • public class Addition

    • {

      7// main method begins execution of Java application

      8public static void main( String args[] )

    • {

    • // criate Scanner to optain input ftom comment window

    • Scanner input = new Scanner(System.in);

      13int number1; // first number to add

      14int number2; // second number to add

      15 int sum; // sum of two numbers

      16

      17 System.out.print(“Enter first integer:”);

      18 number1 = input.nextInt(); //read first number


    Chapter 2 introduction to java applications

    19

    20 System.out.print(“Enter second integer:”);

    21 number2 = input.nextInt(); //read first number

    22

    • sum = number1 + number2

    • System.out.pritf(“Sum is %d\n”, sum);

    • } // end of main

    • } // end of calss Addition

      The programs output:

      Enter first integer 45

      Enter second integer 72

      Sum is 117


    2 5 another java application adding integers12

    2.5Another Java Application: Adding Integers

    inport java.util.Scanner;

    • line 3 inport decleration

      • help the compiler to locate a class used in this program

      • program uses predefined Scanner class in the java.util package

    • if the inport decleration is not used

      • Scanner class should be used like that

        • java.util.Scanner

      • Example:

        • Scanner input = new Scanner(System.in);

      • Should be replaced with

        • java.util.Scanner input = new java.util.Scanner(System.in);


    2 5 another java application adding integers13

    2.5Another Java Application: Adding Integers

    Scanner input = new Scanner(System.in);

    • line 11 variable decleration statement

      • variable name input

      • varaible type Scanner

    • Names are identifiers

    • Scanner

      • enables to read data (numbers, strings)

      • sources:

        • file on a disk

        • user from keyboard

    • before using a Scanner type variable

      • criate it and

      • specify the source of data


    2 5 another java application adding integers14

    2.5Another Java Application: Adding Integers

    • in line 11 Scanner variable input should be initialized

    • the expression

      • new Scanner(System.in)

      • criates a Scanner objcet that reads data typed by the user from the keyboard

    • System.out: standard output objcet

      • display characters in the command window

    • Syste.in: standard input objcet

      • enables users to enter input from keyboard


    2 5 another java application adding integers15

    2.5Another Java Application: Adding Integers

    number1 = input.nextInt();

    • line 18 Scanner object input’s nextInt method

      • to obtain an integer from the user at the keyboard

      • if the user types an non ingeger value at the keyboard

        • the program terminates – logic runtime error

      • nextInt method return an intger variable – input by the user

      • by the assignment opperator

        • assigned to int variable number1


    2 5 another java application adding integers16

    2.5Another Java Application: Adding Integers

    • Note that

      • nextInt method is called with the input object a Scanner type objcet - general format

      • objcet name.method name

    • In the previous example

      • JOptionPane’s showInputDialog method is called with the class name – in general

      • class name.method name

      • thess are static method which are used by class names

      • non-static mehods are used with objcets criated from classes


    2 6 memory concepts

    2.6 Memory Concepts

    • Variables

      • Every variable has a name, a type, a size and a value

        • Name corresponds to location in memory

      • When new value is placed into a variable, replaces (and destroys) previous value

      • Reading variables from memory does not change them


    2 6 memory concepts1

    sum

    0

    sum

    3

    2.6 Memory Concepts

    • Visual Representation

      • Sum = 0; number1 = 1; number2 = 2;

      • Sum = number1 + number2; after execution of statement


    2 7 arithmetic

    2.7 Arithmetic

    • Arithmetic calculations used in most programs

      • Usage

        • * for multiplication

        • / for division

        • +, -

        • No operator for exponentiation (more in Chapter 5)

      • Integer division truncates remainder

        7 / 5 evaluates to 1

      • Remainder operator % returns the remainder

        7 % 5 evaluates to 2


    Casting

    Casting

    • int i=5,j=2;

    • What is i / j

    • : 5 / 2 = 2 integer division

      • Both nominator and denominator are integers

    • İf you want to get a decimal number

    • Use casting

    • (float) i / j = 5.0 / 2 = 2.5

    • (double) i / j = 5.0 / 2 =2.5 or

    • i / (double)j = 5/ 2.0 =2.5

    • The original values of i or j does not change they temporarily promoted to a (double float) in evaluationg the expression


    2 7 arithmetic1

    2.7 Arithmetic


    4 11 compound assignment operators

    4.11 Compound Assignment Operators

    • Assignment Operators

      • Abbreviate assignment expressions

      • Any statement of form

        • variable =variableoperatorexpression;

      • Can be written as

        • variable operator=expression;

      • e.g., addition assignment operator +=

        • c = c + 3

      • can be written as

        • c += 3


    4 12 increment and decrement operators

    4.12 Increment and Decrement Operators

    • Unary increment operator (++)

      • Increment variable’s value by 1

    • Unary decrement operator (--)

      • Decrement variable’s value by 1

    • Preincrement / predecrement operator

    • Post-increment / post-decrement operator


    Increment java line 13 postincrement line 21 preincrement

    Line 13 postincrements c

    Line 21 preincrements c

    1 // Fig. 4.14: Increment.java

    2 // Preincrementing and postincrementing operators.

    3

    4 public class Increment {

    5

    6 public static void main( String args[] )

    7 {

    8 int c;

    9

    10 // demonstrate postincrement

    11 c = 5; // assign 5 to c

    12 System.out.println( c ); // print 5

    13 System.out.println( c++ ); // print 5 then postincrement

    14 System.out.println( c ); // print 6

    15

    16 System.out.println(); // skip a line

    17

    18 // demonstrate preincrement

    19 c = 5; // assign 5 to c

    20 System.out.println( c ); // print 5

    21 System.out.println( ++c ); // preincrement then print 6

    22 System.out.println( c ); // print 6

    23

    24 } // end main

    25

    26 } // end class Increment

    Increment.javaLine 13 postincrementLine 21 preincrement

    556566


    4 13 primitive types

    4.13 Primitive Types

    • Primitive types

      • “building blocks” for more complicated types

    • Java is strongly typed

      • All variables in a Java program must have a type

    • Java primitive types

      • portable across computer platforms that support Java


    Boolean variables

    Boolean Variables

    • A primitive variable in java

      • either true or false

    • Decleration

      • boolean b1,b2; // declaring two boolean variables

      • boolean b3= true;// declaring and initilizing

      • b1 = 2<1;

      • /* 2<1 is a logical expression whose value is false

    • right side of expression is false

    • it is assigned to b1

    • so b1 is false */


    Chapter 2 introduction to java applications

    • b2 = b1 && b3;

    • /* b1 is false b3 is true

    • so b2 is false */

    • System.out.println(“b1 is ”+b1);

    • System.out.println(“b2 && b3 is ”+(b2 && b3));

    • System.out.printf(“b2 && b3 is %b\n”,

    • (b2 && b3));

    • if(b1)

    • System.out.println(“b1 is true”);

    • else

    • System.out.println(“b1 is false”);


    Chapter 2 introduction to java applications

    • The output is:

      b1 is false

      b2 && b3 is false

      b2 && b3 is false

      b1 is false


    2 8 decision making equality and relational operators

    2.8Decision Making: Equality and Relational Operators

    • if control statement

      • Simple version in this section, more detail later

      • If a condition is true, then the body of the if statement executed

      • Control always resumes after the if structure

      • Conditions for if statements can be formed using equality or relational operators (next slide)

        if ( condition )

        statement executed if condition true

        • No semicolon needed after condition

          • Else conditional task not performed


    Chapter 2 introduction to java applications

    • condition should be a logical expression not an aritmetic expression as in C

    • Example:

      • int i =1;

        if(i-1)

        System.out.printf(“true”);

        else

        System.out.printf(“false”);

        Syntax error in java as

      • int i =1;

      • boolean b = i-1==0;

        if(b) // or if(i-1==0)

        System.out.printf(“true”);

        else

        System.out.printf(“false”);


    2 8 decision making equality and relational operators1

    2.8Decision Making: Equality and Relational Operators

    • Upcoming program uses if statements

      • Discussion afterwards


    Chapter 2 introduction to java applications

    1 // Fig. 2.20: Comparison.java

    2 // Compare integers using if statements, relational operators

    3 // and equality operators.

    4

    5 // Java packages

    6 import javax.swing.JOptionPane;

    7

    8 public class Comparison {

    9

    10 // main method begins execution of Java application

    11 public static void main( String args[] )

    12 {

    13 String firstNumber; // first string entered by user

    14 String secondNumber; // second string entered by user

    15 String result; // a string containing the output

    16

    17 int number1; // first number to compare

    18 int number2; // second number to compare

    19

    20 // read first number from user as a string

    21 firstNumber = JOptionPane.showInputDialog( "Enter first integer:" );

    22

    23 // read second number from user as a string

    24 secondNumber =

    25 JOptionPane.showInputDialog( "Enter second integer:" );

    26

    27 // convert numbers from type String to type int

    28 number1 = Integer.parseInt( firstNumber );

    29 number2 = Integer.parseInt( secondNumber );

    30

    31 // initialize result to empty String

    32 result = "";

    33

    Comparison.java1. import2. Class Comparison2.1 main2.2 Declarations2.3 Input data (showInputDialog)2.4 parseInt2.5 Initialize result


    Comparison java 3 if statements 4 showmessagedialog

    Test for equality, create new string, assign to result.

    Notice use of JOptionPane.INFORMATION_MESSAGE

    34 if ( number1 == number2 )

    35 result = result + number1 + " == " + number2;

    36

    37 if ( number1 != number2 )

    38 result = result + number1 + " != " + number2;

    39

    40 if ( number1 < number2 )

    41 result = result + "\n" + number1 + " < " + number2;

    42

    43 if ( number1 > number2 )

    44 result = result + "\n" + number1 + " > " + number2;

    45

    46 if ( number1 <= number2 )

    47 result = result + "\n" + number1 + " <= " + number2;

    48

    49 if ( number1 >= number2 )

    50 result = result + "\n" + number1 + " >= " + number2;

    51

    52 // Display results

    53 JOptionPane.showMessageDialog( null, result, "Comparison Results",

    54 JOptionPane.INFORMATION_MESSAGE );

    55

    56

    57

    58 } // end method main

    59

    60 } // end class Comparison

    Comparison.java3. if statements4. showMessageDialog


    Program output1

    Program Output


    Chapter 2 introduction to java applications

    1 // Fig. 2.20: Comparison.java

    2 // Compare integers using if statements, relational operators

    3 // and equality operators.

    4

    5 // Java packages

    6 import javax.swing.JOptionPane;

    7

    8 public class Comparison {

    9

    10 // main method begins execution of Java application

    11 public static void main( String args[] )

    12 {

    13 String firstNumber; // first string entered by user

    14 String secondNumber; // second string entered by user

    15 String result; // a string containing the output

    16

    17 int number1; // first number to compare

    18 int number2; // second number to compare


    Chapter 2 introduction to java applications

    20 // read first number from user as a string

    21 firstNumber = JOptionPane.showInputDialog( "Enter first integer:" );

    22

    23 // read second number from user as a string

    24 secondNumber =

    25 JOptionPane.showInputDialog( "Enter second integer:" );

    26

    27 // convert numbers from type String to type int

    28 number1 = Integer.parseInt( firstNumber );

    29 number2 = Integer.parseInt( secondNumber );

    30

    31 // initialize result to empty String

    32 result = "";


    Chapter 2 introduction to java applications

    34 if ( number1 == number2 )

    35 result = result + number1 + " == " + number2;

    36

    37 if ( number1 != number2 )

    38 result = result + number1 + " != " + number2;

    39

    40 if ( number1 < number2 )

    41 result = result + "\n" + number1 + " < " + number2;

    42

    43 if ( number1 > number2 )

    44 result = result + "\n" + number1 + " > " + number2;

    45

    46 if ( number1 <= number2 )

    47 result = result + "\n" + number1 + " <= " + number2;

    48

    49 if ( number1 >= number2 )

    50 result = result + "\n" + number1 + " >= " + number2;


    Chapter 2 introduction to java applications

    52 // Display results

    53 JOptionPane.showMessageDialog( null, result, "Comparison Results",

    54 JOptionPane.INFORMATION_MESSAGE );

    55

    56

    57

    58 } // end method main

    59

    60 } // end class Comparison


    2 8 decision making equality and relational operators2

    13 String firstNumber,

    14 secondNumber,

    15 result;

    2.8Decision Making: Equality and Relational Operators

    • Lines 1-12: Comments, importJOptionPane, beginclass Comparison and main

    • Lines 13-18: declare variables

      • Can use comma-separated lists instead:

    • Lines 21-30: obtain user-input numbers and parses input string into integer variables


    2 8 decision making equality and relational operators3

    32 result = "";

    34 if ( number1 == number2 )

    35 result = result + number1 + " == " + number2;

    2.8Decision Making: Equality and Relational Operators

    • Initialize result with empty string

    • if statement to test for equality using (==)

      • If variables equal (condition true)

        • result concatenated using + operator

        • result = result + other strings

        • Right side evaluated first, new string assigned to result

      • If variables not equal, statement skipped


    2 8 decision making equality and relational operators4

    2.8Decision Making: Equality and Relational Operators

    • Lines 37-50: other if statements testing for less than, more than, etc.

      • If number1 = 123 and number2 = 123

        • Line 34 evaluates true (if number1 = = number 2)

          • Because number1 equals number2

        • Line 40 evaluates false (if number1 < number 2)

          • Because number1 is not less than number2

        • Line 49 evaluates true (if number1 >= number2)

          • Because number1 is greater than or equal to number2

    • Lines 53-54: result displayed in a dialog box using showMessageDialog


    2 8 decision making equality and relational operators5

    2.8Decision Making: Equality and Relational Operators

    • Precedence of operators

      • All operators except for = (assignment) associates from left to right

        • For example: x = y = z is evaluated x = (y = z)


    4 5 if single selection statement

    4.5 if Single-Selection Statement

    • Single-entry/single-exit control structure

    • Perform action only when condition is true

    • Action/decision programming model


    Chapter 2 introduction to java applications

    [grade >= 60]

    [grade < 60]

    print “Passed”

    • Fig 4.3 if single-selections statement activity diagram.


    4 6 if else selection statement

    4.6 if…else Selection Statement

    • Perform action only when condition is true

    • Perform different specified action when condition is false

    • Conditional operator (?:)

    • Nested if…else selection structures


    Chapter 2 introduction to java applications

    [grade < 60]

    [grade >= 60]

    print “Passed”

    print “Failed”

    • Fig 4.4 if…else double-selections statement activity diagram.


    5 8 logical operators

    5.8 Logical Operators

    • Logical operators

      • Allows for forming more complex conditions

      • Combines simple conditions

    • Java logical operators

      • && (conditional AND)

      • & (boolean logical AND)

      • || (conditional OR)

      • | (boolean logical inclusive OR)

      • ^ (boolean logical exclusive OR)

      • ! (logical NOT)


    Logicaloperators java lines 16 20 lines 23 27

    Conditional AND truth table

    Conditional OR truth table

    1 // Fig. 5.19: LogicalOperators.java

    2 // Logical operators.

    3 import javax.swing.*;

    4

    5 public class LogicalOperators

    6

    7 public static void main( String args[] )

    8 {

    9 // create JTextArea to display results

    10 JTextArea outputArea = new JTextArea( 17, 20 );

    11

    12 // attach JTextArea to a JScrollPane so user can scroll results

    13 JScrollPane scroller = new JScrollPane( outputArea );

    14

    15 // create truth table for && (conditional AND) operator

    16 String output = "Logical AND (&&)" +

    17 "\nfalse && false: " + ( false && false ) +

    18 "\nfalse && true: " + ( false && true ) +

    19 "\ntrue && false: " + ( true && false ) +

    20 "\ntrue && true: " + ( true && true );

    21

    22 // create truth table for || (conditional OR) operator

    23 output += "\n\nLogical OR (||)" +

    24 "\nfalse || false: " + ( false || false ) +

    25 "\nfalse || true: " + ( false || true ) +

    26 "\ntrue || false: " + ( true || false ) +

    27 "\ntrue || true: " + ( true || true );

    28

    LogicalOperators.javaLines 16-20Lines 23-27


    Logicaloperators java lines 30 34 lines 37 41 lines 44 48 lines 51 53

    Boolean logical AND truth table

    Boolean logical inclusive OR truth table

    Boolean logical exclusive OR truth table

    Logical NOT truth table

    29 // create truth table for & (boolean logical AND) operator

    30 output += "\n\nBoolean logical AND (&)" +

    31 "\nfalse & false: " + ( false & false ) +

    32 "\nfalse & true: " + ( false & true ) +

    33 "\ntrue & false: " + ( true & false ) +

    34 "\ntrue & true: " + ( true & true );

    35

    36 // create truth table for | (boolean logical inclusive OR) operator

    37 output += "\n\nBoolean logical inclusive OR (|)" +

    38 "\nfalse | false: " + ( false | false ) +

    39 "\nfalse | true: " + ( false | true ) +

    40 "\ntrue | false: " + ( true | false ) +

    41 "\ntrue | true: " + ( true | true );

    42

    43 // create truth table for ^ (boolean logical exclusive OR) operator

    44 output += "\n\nBoolean logical exclusive OR (^)" +

    45 "\nfalse ^ false: " + ( false ^ false ) +

    46 "\nfalse ^ true: " + ( false ^ true ) +

    47 "\ntrue ^ false: " + ( true ^ false ) +

    48 "\ntrue ^ true: " + ( true ^ true );

    49

    50 // create truth table for ! (logical negation) operator

    51 output += "\n\nLogical NOT (!)" +

    52 "\n!false: " + ( !false ) +

    53 "\n!true: " + ( !true );

    54

    55 outputArea.setText( output ); // place results in JTextArea

    56

    LogicalOperators.javaLines 30-34Lines 37-41Lines 44-48Lines 51-53


    Logicaloperators java

    57 JOptionPane.showMessageDialog( null, scroller,

    58 "Truth Tables", JOptionPane.INFORMATION_MESSAGE );

    59

    60 System.exit( 0 ); // terminate application

    61

    62 } // end main

    63

    64 } // end class LogicalOperators

    LogicalOperators.java


    What is the output

    What is the output

    int i =1;

    boolean b1 = ++i == i++;

    boolean b2 = i++ == ++i;

    System.out.printf(“%d%b%b”,i,b1,b2);

    ----------------

    String s1 = 1 + 2 + “what is this”;

    String s2 = “what is this” + 1 + 2;

    System.out.printf(“%s\n%s”,s1,s2);

    ----------------------

    String s3 = “”+1 + 2 + “what is this”;

    String s4 = “what is this” + (1 + 2);

    System.out.printf(“%s\n%s”,s3,s4);


    What is the output1

    What is the output

    ----------------

    int i =1;

    System.out.printf(“%d %d %d”,++i,i,i++);

    System.out.printf(“%d %d %d”, i++,i,++i);

    ----------------------

    int i =1;

    System.out.printf(“%d %d %d”,++i,i,i++);

    System.out.printf(“%d %d %d”, i++,i,++i);


    Exercise

    Exercise

    • A user intends to withdraw money from a ATM machine by entering the amount she needs

    • The ATM machine contains a set of notes e.g.:

      • 100 TL, 50 TL, 20 TL...

      • For the time beeing assume that there is no availability problem for any of these notes

      • ATM first pays 100 TLs as much as possible then pays 50 TLs and so on

    • e.g.: the user demands 328

      • Available notes are 100,50,20,10

      • ATM pays 3 100s , 1 20 but the 8 TL can not be paid

    • e.g.: the user demands 483

      • Available notes are 100,50,20,10

      • ATM pays 4 100s , 1 50 , 1 20, 1 10 but the 3 TL can not be paid


    Chapter 2 introduction to java applications

    • Write a program obtaining the amout of money from the user and outputing how it is paid with availabe note in the ATM. The program should also give the amout of money that can not be paid.

    • Externsion:

    • You can extend the problem to TL and kurushes with say 2 digits

    • Availabel notes are say 100,50,20,10,5,1

    • Available coints are 50,25,10,5


    Chapter 2 introduction to java applications

    • e.g.: how to pay 37.86 TL

    • 1: 20 + 1: 10 + 1: 5 + 2: 1 notes

    • 1: 50 + 1: 25 + 1: 10 coins

    • 1 krush can not be paid


    Exercise1

    Exercise

    • Leap year problem

    • Given a year determine whether it is a leap year or not

    • i. A year is a leap year if it is divided by four

      • 2004, 2000, 1900 are but

      • 2005, 2001 not

    • ii. in addition it can not be divided by 100

      • 2004 is but

      • 2000 is not as 2000 mode 100 = 0

    • iii. in addition it is divided by 400

      • 2000 is as 2000 mde 400 = 0 but

      • 1900 is not, as 1900 mode 100 =0 by B and 1900 mode 400 =300 not zero


    Chapter 2 introduction to java applications

    2000

    1900

    C year mode 400=0

    B year mode 100 = 0

    A. Year mode 4 = 0

    2004


    Chapter 2 introduction to java applications

    • i can be codes as

    • İf (year % 4 == 0)

    • System.out.print(year +“ is a leap year”);

    • ii can be coded as

    • if (year % 4 == 0 && year % 100 !=0 )

    • System.out.print(year +“ is a leap year”);

    • Solve iii yourself

    • Solve the same problem both i ii and iii without using logical oppertators (and or not)


    Chapter 2 introduction to java applications

    • For case ii

    • year b1b2b1&&b2

      year % 4 ==0 year % 100 !=0

      ----------------------------------------------------------

      2008 truetruetrue

      2000 truefalsefalse


    Chapter 2 introduction to java applications

    • We are going to use this in our coming examples

      • To calculste difference between days

      • How many days you live?

      • To calculate punishments as a function of number of days between due date and today


    Exercise2

    Exercise

    • Progressive taxation

    • Given the yearly income of a person the amout of income tax is progressively increases. Say

      • For the first 10,000 TL - no income

      • Between 10,000 and 20,000 – 5%

      • Between 20,000 and 50,000 - 10%

      • After 50,000 – 20%

    • E.g.: if income is 15,000

      • Tax = 0.05*(15,000-10,000) = 250

    • E.g.: if income is 35,000

      • Tax = 0.05*(20,000-10,000) + 0.1*(35,000-20,000)=2000


    Chapter 2 introduction to java applications

    • Write program taking yearly income and calculating and printing the income tax due of a person

      • For the time being the tax rates and slices are fixed and assigned in the program

    • i – using the if else structure

    • ii – using only simple if sturcture without using else part


  • Login