0% found this document useful (0 votes)
33 views57 pages

Introduction To Java Applications: Object-Oriented Programming CMPE 201

Uploaded by

Omar Zardasht
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views57 pages

Introduction To Java Applications: Object-Oriented Programming CMPE 201

Uploaded by

Omar Zardasht
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

Introduction to

Java Applications
LECTURE 1
Object-Oriented Programming
CMPE 201
✓Identify the importance of Java
✓Learning of using different Programming Languages
✓Identify the additional features of Java compared to C++
✓Identify the difference between Compiler and Interpreter
✓Apply Object Oriented Principles of Encapsulations, Data
abstraction, Inheritance, Polymorphism
✓Program using java API (Application Programming
Interface)
✓Program using Exception
✓Program using swings and GUI (Extra)
2
✓ Write simple Java applications
✓ Use input and output statements
✓ Learn about Java’s primitive types
✓ Understand basic memory concepts
✓ Use arithmetic operators
✓ Learn the precedence of arithmetic operators
✓ Write decision-making statements
✓ Use relational and equality operators

3
Paul Deitel and Harvey Deitel, Java How to Program Early Objects,
10th Edition
✓ Chapter 2 (from page 34 to 68)
✓James Gosling - Sun Microsystems
✓Originally named Oak – then renamed to Java, 1995
✓JDK Evolutions (Java Development Kit)
✓ JDK 1.0 (January 23, 1996)
✓ JDK 1.1 (February 19, 1997)
✓ J2SE 1.2 (December 8, 1998)
✓ J2SE 1.3 (May 8, 2000)
✓ J2SE 1.4 (February 6, 2002)
✓ J2SE 5.0 (September 30, 2004)
✓ Java SE 6 (December 11, 2006)
✓ Java SE 7 (July 28, 2011)
✓ Java SE 8 (March 18, 2014)
✓ Java SE 9 (September 21, 2017) 5
▪ J2SE(Java 2 Standard Edition) - to develop
client-side standalone applications or applets
▪ J2ME(Java 2 Micro Edition ) - to develop
applications for mobile devices such as cell Phones
▪ J2EE(Java 2 Enterprise Edition ) - to develop
server-side applications such as Java servlets and
Java ServerPages

6
▪A general-purpose Object-Oriented
Language.
▪Write Once Run Anywhere (WORA).
▪Designed for easy Web/Internet
applications.
▪Widespread acceptance
▪3 Billion Devices run on Java

7
8
9
2.1 Introduction
2.2 First Program in Java: Printing a Line of Text
2.3 Modifying Our First Java Program
2.4 Displaying Text with printf
2.5 Java Application: Adding Integers
2.6 Memory Concepts
2.7 Arithmetic
2.8 Decision Making: Equality and Relational Operators

10
• Java application programming
– Display messages
– Obtain information from the user
– Arithmetic calculations
– Decision-making fundamentals

11
• Application
– Executes when you use the java command to launch the Java
Virtual Machine (JVM)
• Sample program
– Displays a line of text
– Illustrates several important Java language features

12
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 clazss Welcome1

Welcome to Java Programming!

13
1 // Fig. 2.1: Welcome1.java

– Comments start with: //


• 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


2 // Text-printing program.
– Note: line numbers not part of program, added for reference

14
Good Programming Practice 2.1

Every program should begin with a comment


that explains the purpose of the program.

15
3
– Blank line
• Makes program more readable
• Blank lines, spaces, and tabs are white-space characters
– Ignored by compiler

4 public class Welcome1


– 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

16
Good Programming Practice 2.2

Use blank lines and space characters to enhance


program readability.

17
4 public class Welcome1

– Java 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 is invalid
• Java is case sensitive (capitalization matters)
– a1 and A1 are different

18
Good Programming Practice 2.3

By convention, always begin a class name’s


identifier with a capital letter and start each
subsequent word in the identifier with a capital
letter.

19
4 public class Welcome1

– Saving files
• File name must be class name with .java extension
• Welcome1.java

5 {

– Left brace {
• Begins body of every class
• Right brace ends declarations (line 13)

20
Common Programming Error 2.3

It is an error for a public class to have a file


name that is not identical to the class name
(plus the .java extension) in terms of both
spelling and capitalization.

21
Common Programming Error 2.4

It is a syntax error if braces do not occur in


matching pairs.

It is an error not to end a file name with the


.java extension for a file containing a class
declaration.

22
7 public static void main( String args[] )

– Part of every Java application


• Applications begin executing at main
– Parentheses indicate main is a method
– Java applications contain one or more methods
• Exactly one method must be called main
– Methods can perform tasks and return
information
• void means main returns no information

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

– Instructs computer to perform an action


• Prints string of characters
– String – series of characters inside double quotes
• White-spaces in strings are not ignored by compiler
– System.out
• Standard output object
– Method System.out.println
• Displays line of text
– This line known as a statement
• Statements must end with semicolon ;

24
Common Programming Error 2.6

Omitting the semicolon ; at the end of a


statement is a syntax error.

25
• Modifying programs
– Welcome2.java produces same output as Welcome1.java
– Using different code

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


10 System.out.println( "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

26
#include <iostream>
using namespace std;

int main()
{
//comments
cout << "Welcome to “ ;
cout << "Java Programming!“ << endl;

return 0;
} 27
• Escape characters
– Backslash ( \ )
– Indicates special characters to 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

9 System.out.println( "Welcome\nto\nJava\nProgramming!" );
– Line breaks at \n

28
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

Welcome
to
Java
Programming!

A new line begins after each \n escape


sequence is output.

29
Escape Description
sequence
\n Newline. Position the screen cursor at the beginning of the next line.
\t Horizontal tab. Move the screen cursor to the next tab stop.
\r Carriage return. Position the screen cursor at the beginning of the
current line—do not advance to the next line. Any characters output
after the carriage return overwrite the characters previously output
on that line.
\\ Backslash. Used to print a backslash character.
\" Double quote. Used to print a double-quote character. For example,
System.out.println( "\"in quotes\"" );
displays
"in quotes"

Fig. 2.5 | Some common escape sequences.

30
•System.out.printf
– Feature added in Java SE 5.0
– Displays formatted data
9 System.out.printf( "%s\n%s\n",
10 "Welcome to", "Java Programming!" );

– Format string
• Fixed text
• Format specifier – placeholder for a value
– Format specifier %s – placeholder for a string

31
System.out.printf
displays formatted data.

32
• Upcoming program
– Use Scanner to read two integers from user
– Use printf to display sum of the two values
– Use packages

33
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.

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

– import declarations
• Used by compiler to identify and locate classes used in
Java programs
• Tells compiler to load class Scanner from java.util
package

35
Common Programming Error 2.8

All import declarations must appear before the


first class declaration in the file.
Placing an import declaration inside a class
declaration’s body or after a class declaration
is a syntax error.

36
10 // create Scanner to obtain input from command window
11 Scanner input = new Scanner( System.in );

– 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
37
13 int number1; // first number to add
14 int number2; // second number to add
15 int sum; // sum of number 1 and number 2

– 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 number1, // first number to add


number2, // second number to add
sum; // sum of number1 and number2

– Can declare multiple variables of the same type in one


declaration
– Use comma-separated list

38
Good Programming Practice 2.11

Choosing meaningful variable names helps a


program to be self-documenting and readable.

39
17 System.out.print( "Enter first integer: " ); // prompt

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


– Package java.lang

– Result
18 call to=nextInt
of number1 given
input.nextInt(); to number1
// read first number using assignment
from user
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()

40
Software Engineering Observation 2.1

By default, package java.lang is imported in


every Java program; thus, java.lang is the
only package in the Java API that does not
require an import declaration.

41
23 sum = number1 + number2; // add numbers

– 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

42
25 System.out.printf( "Sum is %d\n: " , sum ); // display sum
– Use System.out.printf to display results
– Format specifier %d
• Placeholder for an int value

System.out.printf( "Sum is %d\n: " , ( number1 + number2 ) );

– Calculations can also be performed inside printf


– Parentheses around the expression number1 + number2
are not required

43
• 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

44
• 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

45
Arithmetic operators.

46
• 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

47
Precedence of arithmetic operators.

48
Good Programming Practice 2.14

Using parentheses for complex arithmetic


expressions, even when the parentheses are
not necessary, can make the arithmetic
expressions easier to read.

49
• 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)

50
Equality and relational operators.

51
Test for equality, display
result using printf.

Compares two numbers


using relational operator <.
52
Compares two numbers
using relational operators
>, <= and >=.

53
23 if ( number1 == number2 )
24 System.out.printf( "%d == %d\n", number1, number2 );

– 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 line
• Empty statement
– No task is performed

54
Common Programming Error 2.11

It is a syntax error if the operators ==, !=, >=


and <= contain spaces between their symbols,
as in = =, ! =, > = and < =, respectively.

55
Common Programming Error 2.13

Placing a semicolon immediately after the


right parenthesis of the condition in an if
statement is normally a logic error.

56
Precedence and associativity of operators discussed

57

You might also like