Presentation is loading. Please wait.

Presentation is loading. Please wait.

INTRODUCTION TO JAVA CENG 104 FUNDAMENTALS OF COMPUTER PROGRAMMING II Melek OKTAY

Similar presentations


Presentation on theme: "INTRODUCTION TO JAVA CENG 104 FUNDAMENTALS OF COMPUTER PROGRAMMING II Melek OKTAY"— Presentation transcript:

1 INTRODUCTION TO JAVA CENG 104 FUNDAMENTALS OF COMPUTER PROGRAMMING II Melek OKTAY moktay@fatih.edu.tr

2 Referenced Book The metarils of this course are taken from two different books “Java Software Solutions: Foundations of Program Design, 6th Edition” “Java How to Program, 6/e-7/e Deitel”

3 J AVA T RANSLATION 1-3 © 2007 Pearson Addison-Wesley. All rights reserved Java source code Machine code Java bytecode Bytecode interpreter Bytecode compiler Java compiler

4 “W RITE ONCE, R UN EVERYWHERE ”

5 F OCUS OF THE C OURSE Object-Oriented Software Development problem solving program design, implementation, and testing object-oriented concepts classes objects encapsulation inheritance polymorphism graphical user interfaces  not included (out of scope) 1-5 © 2007 Pearson Addison-Wesley. All rights reserved

6 J AVA A programming language specifies the words and symbols that we can use to write a program A programming language employs a set of rules that dictate how the words and symbols can be put together to form valid program statements The Java programming language was created by Sun Microsystems, Inc. It was introduced in 1995 and it's popularity has grown quickly since 1-6 © 2007 Pearson Addison-Wesley. All rights reserved

7 J AVA P ROGRAM S TRUCTURE In the Java programming language: A program is made up of one or more classes A class contains one or more methods A method contains program statements These terms will be explored in detail throughout the course A Java application always contains a method called main See Lincoln.java (page 27) Lincoln.java 1-7 © 2007 Pearson Addison-Wesley. All rights reserved

8 J AVA P ROGRAM S TRUCTURE 1-8 © 2007 Pearson Addison-Wesley. All rights reserved public class MyProgram {}{} // comments about the class class header class body Comments can be placed almost anywhere

9 J AVA P ROGRAM S TRUCTURE 1-9 © 2007 Pearson Addison-Wesley. All rights reserved public class MyProgram {}{} // comments about the class public static void main (String[] args) {}{} // comments about the method method header method body

10 C OMMENTS Comments in a program are called inline documentation They should be included to explain the purpose of the program and describe processing steps They do not affect how a program works Java comments can take three forms: 1-10 © 2007 Pearson Addison-Wesley. All rights reserved // this comment runs to the end of the line /* this comment runs to the terminating symbol, even across line breaks */ /** this is a javadoc comment */

11 I DENTIFIERS Identifiers are the words a programmer uses in a program An identifier can be made up of letters, digits, the underscore character ( _ ), and the dollar sign Identifiers cannot begin with a digit Java is case sensitive - Total, total, and TOTAL are different identifiers By convention, programmers use different case styles for different types of identifiers, such as title case for class names - Lincoln upper case for constants - MAXIMUM 1-11 © 2007 Pearson Addison-Wesley. All rights reserved

12 I DENTIFIERS Sometimes we choose identifiers ourselves when writing a program (such as Lincoln ) Sometimes we are using another programmer's code, so we use the identifiers that he or she chose (such as println ) Often we use special identifiers called reserved words that already have a predefined meaning in the language A reserved word cannot be used in any other way 1-12 © 2007 Pearson Addison-Wesley. All rights reserved

13 R ESERVED W ORDS The Java reserved words: 1-13 © 2007 Pearson Addison-Wesley. All rights reserved abstract assert boolean break byte case catch char class const continue default do double else enum extends false final finally float for goto if implements import instanceof int interface long native new null package private protected public return short static strictfp super switch synchronized this throw throws transient true try void volatile while

14 W HITE S PACE Spaces, blank lines, and tabs are called white space White space is used to separate words and symbols in a program Extra white space is ignored A valid Java program can be formatted many ways Programs should be formatted to enhance readability, using consistent indentation See Lincoln2.java (page 33)Lincoln2.java See Lincoln3.java (page 34)Lincoln3.java 1-14 © 2007 Pearson Addison-Wesley. All rights reserved

15

16 2.3 M ODIFYING O UR F IRST J AVA P ROGRAM (C ONT.) Modifying programs 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 16 9 System.out.print( "Welcome to " ); 10 System.out.println( "Java Programming!" );

17 O UTLINE Welcome2.java 1. Comments 2. Blank line 3. Begin class Welcome2 3.1 Method main 4. Method System.out.prin t 4.1 Method System.out.prin tln 5. end main, Welcome2 Program Output 17 System.out.print keeps the cursor on the same line, so System.out.println continues on the same line.

18 2.3 M ODIFYING O UR F IRST J AVA P ROGRAM (C ONT.) Escape characters Backslash ( \ ) Indicates special characters be output Newline characters ( \n ) Interpreted as “special characters” by methods System.out.print and System.out.println Indicates cursor should be at the beginning of the next line Welcome3.java (Fig. 2.4) Line breaks at \n 18 9 System.out.println( "Welcome\nto\nJava\nProgramming!" );

19 O UTLINE Welcome3.java 1. main 2. System.out.println (uses \n for new line) Program Output 19 Notice how a new line is output for each \n escape sequence.

20 2.4 D ISPLAYING T EXT WITH PRINTF System.out.printf New feature of J2SE 5.0 Displays formatted data Format string Fixed text Format specifier – placeholder for a value Format specifier %s – placeholder for a string 20 9 System.out.printf( "%s\n%s\n", 10 "Welcome to", "Java Programming!" );

21 O UTLINE Welcome4.j ava main printf Program output 21 System.out.printf displays formatted data.

22 2.5 A NOTHER J AVA A PPLICATION : A DDING I NTEGERS Upcoming program Use Scanner to read two integers from user Use printf to display sum of the two values Use packages 22

23 O UTLINE Addition. java (1 of 2) import declaration Scanner nextInt 23 import declaration imports class Scanner from package java.util. Declare and initialize variable input, which is a Scanner. Declare variables number1, number2 and sum. Read an integer from the user and assign it to number1.

24 O UTLINE Additio n.java (2 of 2) 4. Addition 5. printf 24 Read an integer from the user and assign it to number2. Calculate the sum of the variables number1 and number2, assign result to sum. Display the sum using formatted output. Two integers entered by the user.

25 2.5 A NOTHER J AVA A PPLICATION : A DDING I NTEGERS (C ONT.) import declarations Used by compiler to identify and locate classes used in Java programs Tells compiler to load class Scanner from java.util package Begins public class Addition Recall that file name must be Addition.java Lines 8-9: begins main 25 3 import java.util.Scanner; // program uses class Scanner 5 public class Addition 6 {

26 2.5 A NOTHER J AVA A PPLICATION : A DDING I NTEGERS (C ONT.) Variable Declaration Statement Variables Location in memory that stores a value Declare with name and type before use Input is of type Scanner Enables a program to read data for use Variable name: any valid identifier Declarations end with semicolons ; Initialize variable in its declaration Equal sign Standard input object System.in 26 10 // create Scanner to obtain input from command window 11 Scanner input = new Scanner( System.in );

27 2.5 A NOTHER J AVA A PPLICATION : A DDING I NTEGERS (C ONT.) Declare variable 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 int, float, double and char are primitive types Can add comments to describe purpose of variables Can declare multiple variables of the same type in one declaration Use comma-separated list 27 13 int number1; // first number to add 14 int number2; // second number to add 15 int sum; // second number to add int number1, // first number to add number2, // second number to add sum; // second number to add

28 2.5 A NOTHER J AVA A PPLICATION : A DDING I NTEGERS (C ONT.) Message called a prompt - directs user to perform an action Package java.lang Result of call to nextInt given to number1 using assignment operator = Assignment statement = binary operator - takes two operands Expression on right evaluated and assigned to variable on left Read as: number1 gets the value of input.nextInt() 28 17 System.out.print( "Enter first integer: " ); // prompt 18 number1 = input.nextInt(); // read first number from user

29 2.5 A NOTHER J AVA A PPLICATION : A DDING I NTEGERS (C ONT.) Similar to previous statement Prompts the user to input the second integer Similar to previous statement Assign variable number2 to second integer input Assignment statement Calculates sum of number1 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 number2 are operands 29 20 System.out.print( "Enter second integer: " ); // prompt 21 number2 = input.nextInt(); // read second number from user 23 sum = number1 + number2; // add numbers

30 2.5 A NOTHER J AVA A PPLICATION : A DDING I NTEGERS (C ONT.) Use System.out.printf to display results Format specifier %d Placeholder for an int value Calculations can also be performed inside printf Parentheses around the expression number1 + number2 are not required 30 25 System.out.printf( "Sum is %d\n: ", sum ); // display sum System.out.printf( "Sum is %d\n: ", ( number1 + number2 ) );

31 2.6 M EMORY C ONCEPTS 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 31

32 F IG. 2.8 | M EMORY LOCATION SHOWING THE NAME AND VALUE OF VARIABLE NUMBER 1. 32

33 F IG. 2.9 | M EMORY LOCATIONS AFTER STORING VALUES FOR NUMBER 1 AND NUMBER 2. 33

34 F IG. 2.10 | M EMORY LOCATIONS AFTER CALCULATING AND STORING THE SUM OF NUMBER 1 AND NUMBER 2. 34

35 2.7 A RITHMETIC Arithmetic calculations used in most programs Usage * for multiplication / for division % for remainder +, - Integer division truncates remainder 7 / 5 evaluates to 1 Remainder operator % returns the remainder 7 % 5 evaluates to 2 35

36 F IG. 2.11 | A RITHMETIC OPERATORS. 36

37 2.7 A RITHMETIC (C ONT.) Operator precedence Some arithmetic operators act before others (i.e., multiplication before addition) Use parenthesis when needed Example: Find the average of three variables a, b and c Do not use: a + b + c / 3 Use: ( a + b + c ) / 3 37

38 F IG. 2.12 | P RECEDENCE OF ARITHMETIC OPERATORS. 38

39 2.8 D ECISION M AKING : E QUALITY AND R ELATIONAL O PERATORS Condition Expression can be either true or false if 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 statement Conditions in if statements can be formed using equality or relational operators (next slide) 39

40 F IG. 2.14 | E QUALITY AND RELATIONAL OPERATORS. 40

41 O UTLINE Compar ison.jav a (1 of 2) 1. Class Comparison 1.1 main 1.2 Declarations 1.3 Input data (nextInt) 1.4 Compare two inputs using if statements 41 Test for equality, display result using printf. Compares two numbers using relational operator <.

42 O UTLINE Compariso n.java (2 of 2) Program output 42 Compares two numbers using relational operator >, =.

43 2.8 D ECISION M AKING : E QUALITY AND R ELATIONAL O PERATORS (C ONT.) Line 6: begins class Comparison declaration Line 12: declares Scanner variable input and assigns it a Scanner that inputs data from the standard input Lines 14-15: declare int variables Lines 17-18: prompt the user to enter the first integer and input the value Lines 20-21: prompt the user to enter the second integer and input the value 43

44 2.8 D ECISION M AKING : E QUALITY AND R ELATIONAL O PERATORS (C ONT.) if statement to test for equality using ( == ) If variables equal (condition true) Line 24 executes If variables not equal, statement skipped No semicolon at the end of if statement Empty statement No task is performed Lines 26-27, 29-30, 32-33, 35-36 and 38-39 Compare number1 and number2 with the operators !=,, =, respectively 44 23 if ( number1 == number2 ) 24 System.out.printf( "%d == %d\n", number1, number2 );

45 F IG. 2.16 | P RECEDENCE AND ASSOCIATIVITY OF OPERATIONS DISCUSSED. 45


Download ppt "INTRODUCTION TO JAVA CENG 104 FUNDAMENTALS OF COMPUTER PROGRAMMING II Melek OKTAY"

Similar presentations


Ads by Google