CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS · CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS...

38
CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS Principles of Object-Oriented Programming in Java Dr. Hikmat Abdeljaber ©2014 by SAU. All Rights Reserved.

Transcript of CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS · CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS...

Page 1: CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS · CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS Principles of Object-Oriented Programming in Java ... compile and run Java programs. To

CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS

Principles of Object-Oriented Programming in Java

Dr. Hikmat Abdeljaber

©2014 by SAU. All Rights Reserved.

Page 2: CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS · CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS Principles of Object-Oriented Programming in Java ... compile and run Java programs. To

2.2 Working with NetBeans™ IDE

©2014 by SAU. All Rights Reserved.

Writing a Java program requires three-step processes: create the program, compile the program, and run the program.

NetBeans™ 6.5 is an IDE software used to create, compile and run Java programs.

To use NetBeans™ 6.5, you need to do two steps: first install JDK 6 and second install NetBeans™ 6.5.

Page 3: CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS · CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS Principles of Object-Oriented Programming in Java ... compile and run Java programs. To

NetBeans™ 6.5 IDE after starting and loading Start Page.

2.2 Working with NetBeans™ IDE (Cont.)

©2014 by SAU. All Rights Reserved.

Page 4: CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS · CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS Principles of Object-Oriented Programming in Java ... compile and run Java programs. To

2.2 Working with NetBeans™ IDE (Cont.)

©2014 by SAU. All Rights Reserved.

NetBeans™ 6.5 allows you to create many types of Java programs ranging from simple desktop and web applications to enterprise networked applications.

To develop a Java application, create a new project, then use the default package or create new package in this new project, and finally create class(es) in the package.

The created project contains package(es) and package(es) contain class(es).

Page 5: CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS · CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS Principles of Object-Oriented Programming in Java ... compile and run Java programs. To

2.2 Working with NetBeans™ IDE (Cont.)

©2014 by SAU. All Rights Reserved.

The created project that contain package(es) and class(es) is placed in the upper left pane of the IDE.

A single Java program file may have more than one non-public class, but there can be only one public

class.

A non-public class is default class if it is preceded with no access modifier.

Page 6: CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS · CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS Principles of Object-Oriented Programming in Java ... compile and run Java programs. To

2.2 Working with NetBeans™ IDE (Cont.)

©2014 by SAU. All Rights Reserved.

The program file name should match with the name of the public class.

package statement has to come first statement in the program.

import statement has to come after package statement.

Class definition comes after import statement

In Java, class combines instance variables with methods.

Page 7: CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS · CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS Principles of Object-Oriented Programming in Java ... compile and run Java programs. To

2.3 A Simple Java Program: Printing a Line of Text

©2014 by SAU. All Rights Reserved.

Printing a line of text program

1 // PrintText.java

2 // This program displays a line of text.

3

4 public class PrintText

5 {

6 // main method begins execution of Java application

7 public static void main( String[] args )

8 {

9 System.out.println( "I Like Java Programming." );

10 } // end method main

11 } // end class PrintText.java

Page 8: CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS · CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS Principles of Object-Oriented Programming in Java ... compile and run Java programs. To

2.4 Compiling and Running Java Programs

©2014 by SAU. All Rights Reserved.

The created Java source file (i.e. Java program file) has an extension .java.

You can press the function key F9 to compile the Java source code file.

The compilation process translates the source code file into bytecode file with extension .class.

You can use the function key F6 to run the bytecode file. The run process executes the bytecode file by using the interpreter.

Page 9: CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS · CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS Principles of Object-Oriented Programming in Java ... compile and run Java programs. To

Compiling and running the source code file are performed by clicking icon

2.4 Compiling and Running Java Programs (Cont.)

©2014 by SAU. All Rights Reserved.

Page 10: CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS · CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS Principles of Object-Oriented Programming in Java ... compile and run Java programs. To

2.5 Escape Sequences

©2014 by SAU. All Rights Reserved.

An escape sequence is a combination of escape character (\) and task specifier character (", ', \, t, n, etc).

Escape sequence \" prints double quote character and escape sequence character \t moves the screen cursor to the next tab stop.

Page 11: CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS · CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS Principles of Object-Oriented Programming in Java ... compile and run Java programs. To

2.5 Escape Sequences (Cont.)

©2014 by SAU. All Rights Reserved.

Escape Sequences.

Escape sequence Description

\' Single quote. Output the single quote (') character.

\" Double quote. Output the double quote (") character.

\\ Backslash. Output the backslash (\) character.

\b Backspace. Move the cursor back one position on the current line.

\f Form feed. Move the cursor to the start of the next logical page.

\n Newline. Move the cursor to the beginning of the next line.

\r Carriage return. Move the cursor to the beginning of the current line.

\t Tab. Move the cursor to the next horizontal tab position.

Page 12: CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS · CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS Principles of Object-Oriented Programming in Java ... compile and run Java programs. To

2.6 Literals

©2014 by SAU. All Rights Reserved.

A literal is an explicit data value such as 25, 13.9, false, 'H', "This is text", etc.

Numeric literals include integer literals and floating-point literals.

Integer literals include binary, octal, decimal, and hexadecimal literals.

A string literal is sometimes called a character string, a message or a text.

Page 13: CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS · CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS Principles of Object-Oriented Programming in Java ... compile and run Java programs. To

2.6 Literals (Cont.)

©2014 by SAU. All Rights Reserved.

A character literal is a single character between single quotes such as 'B', '$' and '9'.

A booean literal is the value true and false.

Page 14: CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS · CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS Principles of Object-Oriented Programming in Java ... compile and run Java programs. To

2.7 Identifiers

©2014 by SAU. All Rights Reserved.

An identifier is a name of memory location that keeps either variable or constant value.

A variable is an identifier that it is allowed to change its value during program execution.

A named constant is an identifier that it is not allowed to change its value during program execution.

The modifier final is used to declare named constants.

Page 15: CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS · CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS Principles of Object-Oriented Programming in Java ... compile and run Java programs. To

2.7 Identifiers (Cont.)

©2014 by SAU. All Rights Reserved.

The identifier name must fulfill certain conditions to be a valid identifier name.

There are local identifiers and instance identifiers in Java.

Local identifiers are identifiers belong to a particular method and thereafter defined inside that method.

Instance identifiers are identifiers belong to the class definition and thereafter defined outside of all the class methods.

Page 16: CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS · CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS Principles of Object-Oriented Programming in Java ... compile and run Java programs. To

2.7 Identifiers (Cont.)

©2014 by SAU. All Rights Reserved.

Initialization means assigning an initial value to the identifier.

Identifier types in Java.

Page 17: CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS · CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS Principles of Object-Oriented Programming in Java ... compile and run Java programs. To

2.8 Memory Concepts

©2014 by SAU. All Rights Reserved.

Every identifier has four properties: name, type, size and value.

27

number

int

4 bytes

name

value

size

type

Memory location showing name, type, size and value of variable number.

Page 18: CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS · CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS Principles of Object-Oriented Programming in Java ... compile and run Java programs. To

2.9 Primitive Data Types

©2014 by SAU. All Rights Reserved.

There are primitive data types and reference data types in Java.

Primitive data types are categorized into numeric data types, Unicode character data type, and logical data type.

Numeric data types are categorized into integer data types and floating-point data types.

Integer data types include the keywords byte, short, int, and long.

Page 19: CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS · CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS Principles of Object-Oriented Programming in Java ... compile and run Java programs. To

2.9 Primitive Data Types (Cont.)

©2014 by SAU. All Rights Reserved.

Floating-point data types include the keywords float and double.

Unicode character data type includes the keyword char.

Logical data type includes the keyword boolean.

An identifier declaration is the step of stating what data type the identifier should hold.

An identifier initialization is the step of assigning an initial value to the identifier after declaring it.

Page 20: CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS · CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS Principles of Object-Oriented Programming in Java ... compile and run Java programs. To

2.9 Primitive Data Types (Cont.)

©2014 by SAU. All Rights Reserved.

Category Subcategory Type Size

(in bytes) Range

Numeric

Integer

byte 1 –128 to +127 (–27 to 27 – 1)

short 2 –32,768 to +32,767 (–215 to 215 – 1)

int 4 –2,147,483,648 to +2,147,483,647

(–231 to 231 – 1)

long 8

–9,223,372,036,854,775,808 to

+9,223,372,036,854,775,807

(–263 to 263 – 1)

Floating-point

float 4 –3.4028234663852886E+38 to

3.4028234663852886E+38

double 8 –1.7976931348623157E+308 to

1.7976931348623157E+308

Single Unicode

character char 2 '\u0000' to '\uFFFF' (0 to 65535)

Logical boolean Specific to JVM true or false

Java Primitive Types

Page 21: CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS · CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS Principles of Object-Oriented Programming in Java ... compile and run Java programs. To

2.9 Primitive Data Types (Cont.)

©2014 by SAU. All Rights Reserved.

To declare a local variable, use the form: data-type identifier ;

To declare a local constant, use the form: final data-type identifier = literal ;

To declare an instance variable, use the form: modifier data-type identifier ;.

To declare an instance constant, use the form: modifier final data-type identifier ;

Page 22: CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS · CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS Principles of Object-Oriented Programming in Java ... compile and run Java programs. To

2.9 Primitive Data Types (Cont.)

©2014 by SAU. All Rights Reserved.

Default values for data fields of types Boolean, numeric, String, and object are false, 0, "", and null, respectively.

Assigning values out of the range of the type specified to the identifier produces a syntax error.

Java uses Unicode character set to encode and decode characters therefore they each occupy 16 bits (2 bytes) in memory.

Page 23: CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS · CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS Principles of Object-Oriented Programming in Java ... compile and run Java programs. To

2.9 Primitive Data Types (Cont.)

©2014 by SAU. All Rights Reserved.

A 16-bit Unicode encoding system takes two bytes, preceded by \u, expressed in four hexadecimal digits that run from '\u0000' to '\uFFFF' .

Variables of type boolean cannot be cast to any other primitive type, and the other primitive types cannot be cast to type boolean.

Page 24: CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS · CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS Principles of Object-Oriented Programming in Java ... compile and run Java programs. To

2.10 String Concatenation

©2014 by SAU. All Rights Reserved.

System.out is known as the standard output object.

Concatenation is the process of joining strings.

The operator + concatenates strings

println method (and print method) comes with several overloaded versions: int version that receives int numbers, double version that receives double numbers, char version that receives characters, etc.

Page 25: CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS · CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS Principles of Object-Oriented Programming in Java ... compile and run Java programs. To

2.11 Input/Output Data

©2014 by SAU. All Rights Reserved.

Packages java.io and javax.swing are used to input and output data.

Java defines I/O in terms of classes known as streams.

A stream is a sequence of bits of information that is passed along a virtual path between a source and a destination.

An input stream provides a path from a source to a program and an output stream provides a path from a program to a destination.

Page 26: CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS · CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS Principles of Object-Oriented Programming in Java ... compile and run Java programs. To

2.11 Input/Output Data (Cont.)

©2014 by SAU. All Rights Reserved.

Package java.io provides System.in and System.out streams.

System.in stream is used to enter program's data from the keyboard or file.

System.out stream is used to display program's data on the screen or file.

Package java.util provides class Scanner to input data from the Console. Scanner class invokes methods (next(), nextInt(), nextDouble(), etc.) to input data.

Page 27: CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS · CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS Principles of Object-Oriented Programming in Java ... compile and run Java programs. To

2.11 Input/Output Data (Cont.)

©2014 by SAU. All Rights Reserved.

Method Description Example

next() to enter one string token String firstName = input.next()

nextLine() to enter a complete string line String address = input.next()

nextByte() to enter a byte integer value byte b = input.nextByte()

nextShort() to enter a short integer value short s = input.nextShort()

nextInt() to enter an integer value int i = input.nextInt()

nextLong() to enter a long integer value long l = input.nextLong()

nextFloat() to enter a float value float f = input.nextFloat()

nextDouble() to enter a double value double d = input.nextDuble()

nextBoolean() to enter a Boolean value Boolean n = input.nextBoolean()

Methods of class Scanner for entering data.

Page 28: CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS · CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS Principles of Object-Oriented Programming in Java ... compile and run Java programs. To

2.11 Input/Output Data (Cont.)

©2014 by SAU. All Rights Reserved.

Input integer data using Scanner method nextInt().

1 import java.util.Scanner;

2

3 public class Rectangle

4 {

5 public static void main (String[] args)

6 {

7 int length, width;

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

9

10 System.out.print ("Enter rectangle length: ");

11 length = input.nextInt();

12 System.out.print ("Enter rectangle width: ");

13 width = input.nextInt();

14 }

15 }

output

Enter rectangle length: 5

Enter rectangle width: 2

Page 29: CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS · CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS Principles of Object-Oriented Programming in Java ... compile and run Java programs. To

2.11 Input/Output Data (Cont.)

©2014 by SAU. All Rights Reserved.

Package javax.swing provides class JOptionPane to input data from a dialog box. Class JOptionPane invokes showInputDialog( ) method to input data.

Method showInputDialog( ) always store the input data in a string variable which should be converted to the desire type by using the method parseInt( ) in class Integer or the method parseDouble( ) in class Double, etc.

Page 30: CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS · CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS Principles of Object-Oriented Programming in Java ... compile and run Java programs. To

2.11 Input/Output Data (Cont.)

©2014 by SAU. All Rights Reserved.

Class Method Description Example

Byte parseByte() convert string to byte byte b = Byte.parseByte("77")

Short parseShort() convert string to short short s = Short.parseShort("193")

Integer parseInt() convert string to integer int i = Integer.parseInteger("401")

Long parseLong() convert string to long long l = Long.parseLong("8355")

Float parseFloat() convert string to float float f = Float.parseFloat("9.72")

Double parseDouble() convert string to double double d = Double.parseDouble("3.5")

Boolean parseBoolean() convert string to boolean Boolean n = Boolean.parseBoolean("true")

Classes and their methods for converting strings to different data type values.

Page 31: CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS · CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS Principles of Object-Oriented Programming in Java ... compile and run Java programs. To

2.11 Input/Output Data (Cont.)

©2014 by SAU. All Rights Reserved.

1 import javax.swing.JOptionPane;

2

3 public class MyFirstName

4 {

5 public static void main( String[] args )

6 {

7 String firstName;

8 firstName = JOptionPane.showInputDialog( null, "Enter your first name",

"First Name", JOptionPane. INFORMATION_MESSAGE); 9

10 }

11 }

output

Input data using four-argument version of the showInputDialog method.

Page 32: CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS · CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS Principles of Object-Oriented Programming in Java ... compile and run Java programs. To

2.11 Input/Output Data (Cont.)

©2014 by SAU. All Rights Reserved.

For input data, an object of class Scanner invokes the methods next(), nextInt(), nextDouble(), etc., whereas the class JOptionPane itself invokes the method showInputDialog() because showInputDialog() is a static method.

The standard output object System.out invokes the method print(), println(), and printf() to display data on the console.

Page 33: CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS · CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS Principles of Object-Oriented Programming in Java ... compile and run Java programs. To

2.11 Input/Output Data (Cont.)

©2014 by SAU. All Rights Reserved.

Method printf() uses format specifiers for displaying data. Format specifier specifies how an item should be displayed. %f, %d and %b are some examples of specifiers.

Package javax.swing provides class JOptionPane to output data in a dialog box. Class JOptionPane invokes the method showMessageDialog() to display data in a dialog box.

Page 34: CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS · CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS Principles of Object-Oriented Programming in Java ... compile and run Java programs. To

2.11 Input/Output Data (Cont.)

©2014 by SAU. All Rights Reserved.

Class JOptionPane itself invokes the method showMessageDialog() because showMessageDialog() is a static method.

1 import javax.swing.JOptionPane;

2

3 public class RadarResult

4 {

5 public static void main( String[] args )

6 {

7

JOptionPane.showMessageDialog( null, "Your car has exceeded the speed limit.",

"Radar Result", JOptionPane.PLAIN_MESSAGE ); 8

9 }

10 }

output

Page 35: CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS · CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS Principles of Object-Oriented Programming in Java ... compile and run Java programs. To

2.12 Another Java Application: Adding Two Integers

©2014 by SAU. All Rights Reserved.

1 /* AddTwoIntegers Program: Add two integers 2 File: AddTwoIntegers.java */

3 4 import java.util.Scanner; 5 6 public class AddTwoIntegers 7 { 8 public static void main (String[] args) 9 { 10 int intNumber1, intNumber2, sum; 11 Scanner input = new Scanner( System.in ); 12 13 System.out.print ("Enter the first integer number: "); 14 intNumber1 = input.nextInt(); // input first integer number. 15 System.out.print ("Enter the second integer number: "); 16 intNumber2 = input.nextInt(); // input second integer number. 17 18 sum = intNumber1+intNumber2; // add the two integers into sum. 19 . 20 System.out.println("The sum of " + intNumber1 + " and " + intNumber2 + " is " + sum); // print the sum. 21 } 22 } output

Enter the first integer number: 65

Enter the second integer number: 19

The sum of 65 and 19 is 84

Page 36: CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS · CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS Principles of Object-Oriented Programming in Java ... compile and run Java programs. To

2.13 Programming Errors

©2014 by SAU. All Rights Reserved.

There are three types of errors in Java: syntax errors, run-time errors, and logical errors.

Syntax errors occur when you violate the syntax rules of the language. The syntax errors are also called compile-time errors because they are detected at compile time.

Run-time errors occur when we ask the computer to do something it considers to be illegal, such as dividing by zero.

Page 37: CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS · CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS Principles of Object-Oriented Programming in Java ... compile and run Java programs. To

2.13 Programming Errors (Cont.)

©2014 by SAU. All Rights Reserved.

Logical errors occur when the result the program produces doesn't match the result your test data suggest it should produce.

Page 38: CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS · CHAPTER 2 INTRODUCTION TO JAVA APPLICATIONS Principles of Object-Oriented Programming in Java ... compile and run Java programs. To

2.14 Problem: Average of Four Marks for a Student

©2014 by SAU. All Rights Reserved.

1 // Average Program: For calculating average of four marks for a student

2 import java.util.Scanner;

3

4 public class Average

5 {

6 public static void main (String[] args)

7 {

8 double mark1, mark2, mark3, mark4, sum, average;

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

10

11 System.out.print ("Enter the first mark: ");

12 mark1 = input.nextDouble(); // input first mark.

13 System.out.print ("Enter the second mark: ");

14 mark2 = input.nextDouble(); // input second mark.

15 System.out.print ("Enter the third mark: ");

16 mark3 = input.nextDouble(); // input third mark.

17 System.out.print ("Enter the fourth mark: ");

18 mark4 = input.nextDouble(); // input fourth mark.

19

20 sum = (mark1+mark2+mark3+mark4); // sum the four marks.

21 average = sum/4.0; // divide sum by 4.

22 .

23 System.out.println("Average of " + mark1 + ", " + mark2 + ", " + mark3 + ", " + mark4 + " is " + average); // print marks & average

24 }.

25 }

output

Enter the first mark: 65

Enter the second mark: 73

Enter the third mark: 91

Enter the fourth mark: 87

Average of 65.0, 73.0, 91.0, 87.0 is 79.0