0% found this document useful (0 votes)
15 views72 pages

Lec 01 02 Introduction Review

This document provides an introduction to Object-Oriented Programming in Java, covering the basics of Java programming, including classes, objects, methods, and the structure of a Java program. It explains the importance of comments, identifiers, reserved words, and the role of variables and constants in programming. Additionally, it discusses the development environment, syntax and semantics, types of errors, and the fundamental concepts of object-oriented programming.

Uploaded by

rashidminhas1298
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)
15 views72 pages

Lec 01 02 Introduction Review

This document provides an introduction to Object-Oriented Programming in Java, covering the basics of Java programming, including classes, objects, methods, and the structure of a Java program. It explains the importance of comments, identifiers, reserved words, and the role of variables and constants in programming. Additionally, it discusses the development environment, syntax and semantics, types of errors, and the fundamental concepts of object-oriented programming.

Uploaded by

rashidminhas1298
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/ 72

Object Oriented

Programming in Java
Lecture 01 : Introduction and Review
Overview

´ Java Programming Basics


´ Classes and Objects
´ Review of Basic Java
3
Java Program Basics
4 Java

´ 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
5 Java Program Structure

´ 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


Java Program Structure
6
// comments about the class
public class MyProgram
{
class header

class body

Comments can be placed almost anywhere


}
Java Program Structure
7
// comments about the class
public class MyProgram
{

// comments about the method


public static void main (String[] args)
{
method header
method body
}

}
8 A Basic Java Program

´In Java, every variable, constant, and function


(including main) must be inside some class.

public class Test{


public static void main(String [] args){
System.out.println("Hello world!");
}
}
9 Compiling and Executing java Program

´ Compile the source file, Test.java


´ javac Test.java
´ This will result in a .class file “Test.class”
´ Execute the .class file
´ java Test
´ Note:
´ The process can be automated using an IDE
10 A Basic Java Program

´ No final semi-colon at the end of the class definition.


´ Function main is a member of class Test.
´ In general, main must:
´ Be inside some class.
´ Be public static void
´ To write to standard output, we can use either of the following:
´ System.out.println( ... );
´ System.out.print( ... );
11

´ Printing on console;
´ System.out.print("hello"); // print a String
´ System.out.print(16); // print an integer
´ System.out.print(5.5 * .2); // print a floating-point number
´ String Concatenation
int x = 20, y = 10;
System.out.println("x: " + x + "\ny: " + y);
´ Output
x: 20
y: 10
12 Comments

´ 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:

// 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 */


13 Identifiers

´ 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
14 Identifiers

´ 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


Reserved Words
15

´ The Java reserved words:

abstract else interface switch


assert enum long synchronized
boolean extends native this
break false new throw
byte final null throws
case finally package transient
catch float private true
char for protected try
class goto public void
const if return volatile
continue implements short while
default import static
do instanceof strictfp
double int super
White Space
16

´ 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
17

Program Development
18 Program Development

´ The mechanics of developing a program include several activities


´ writing the program in a specific programming language (such as Java)

´ translating the program into a form that the computer can execute

´ investigating and fixing various types of errors that can occur

´ Software tools can be used to help with all parts of this process
19 Development Environments

´ There are many programs that support the development of Java


software, including:
´ Java Development Kit (JDK)
´ Eclipse IDE (www.eclipse.org/)
´ Sun NetBeans
´ Borland JBuilder
´ MetroWerks CodeWarrior
´ BlueJ
´ jGRASP

´ Though the details of these environments differ, the basic


compilation and execution process is essentially the same
20 Syntax and Semantics

´ The syntax rules of a language define how we can put together


symbols, reserved words, and identifiers to make a valid program

´ The semantics of a program statement define what that


statement means (its purpose or role in a program)

´ A program that is syntactically correct is not necessarily logically


(semantically) correct

´ A program will always do what we tell it to do, not what we


meant to tell it to do
21 Errors

´ A program can have three types of errors

´ The compiler will find syntax errors and other basic problems
(compile-time errors)
´ If compile-time errors exist, an executable version of the program is
not created

´ A problem can occur during program execution, such as trying


to divide by zero, which causes a program to terminate
abnormally (run-time errors)

´ A program may run, but produce incorrect results, perhaps


using an incorrect formula (logical errors)
Basic Program Development
22

Edit and
save program
errors

errors
Compile program

Execute program and


evaluate results
23
Object-Oriented Programming
24 Object-Oriented Programming

´ Java is an object-oriented programming language

´ As the term implies, an object is a fundamental entity in a Java


program

´ Objects can be used effectively to represent real-world entities

´ For instance, an object might represent a particular employee in


a company

´ Each employee object handles the processing and data


management related to that employee
25 Objects

´ An object has:
´ state - descriptive characteristics (attributes)
´ behaviors - what it can do (or what can be done to it)

´ The state of a bank account includes its account number and its
current balance

´ The behaviors associated with a bank account include the ability


to make deposits and withdrawals

´ Note that the behavior of an object might change its state


26 Classes

´ An object is defined by a class


´ A class is the blueprint of an object
´ The class uses methods to define the behaviors of the object
´ The class that contains the main method of a Java program
represents the entire program
´ A class represents a concept, and an object represents the
embodiment of that concept
´ Multiple objects can be created from the same class
Objects and Classes
27

A class An object
(the concept) (the realization)

Bank John’s Bank Account


Account Balance: $5,257

Bill’s Bank Account


Balance: $1,245,069
Multiple objects
from the same class
Mary’s Bank Account
Balance: $16,833
28
More Basics of Java
29
Character Strings
30 Character Strings

´ A string of characters can be represented as a string literal by putting


double quotes around the text:

´ Examples:
"This is a string literal."
"123 Main Street"
"X"
´ Every character string is an object in Java, defined by the String class
´ Every string literal represents a String object
31 The println Method

´ The System.out object represents a destination (the monitor


screen) to which we can send output

System.out.println ("Whatever you are, be a good one.");

method
information provided to the method
name
(parameters)
32 The print Method

´ The System.out object provides another service as well

´ The print method is similar to the println method, except that it


does not advance to the next line

´ Therefore anything printed after a print statement will appear on


the same line
33 String Concatenation

´ + is used as a concatenation operator


´ Concatenation operator appends one string to the end of another
"Peanut butter " + "and jelly"
´ Can be use to append more than two strings as well
´ “First string ” + “Second string “ + “Third string “ + “Fourth string”
´ A string literal cannot be broken across two lines in a program
34 String Concatenation

´ If both operands are strings, resultant is also a string


´ If one is a string and one is a number, resultant is string
´ If both operands are numeric, + adds them
35 Escape Sequences

´ An escape sequence is a series of characters that represents a special


character
´ An escape sequence begins with a backslash character (\)

System.out.println ("I said \"Hello\" to you.");

´ Following is the output


´ I said “Hello” to you.
Escape Sequences
36

Escape Sequence Meaning


\b backspace
\t tab
\n newline
\r carriage return
\" double quote
\' single quote
\\ backslash
37

Variables and Assignment


Variables
38

´ A variable is a name for a location in memory


´ A variable must be declared by specifying the variable's name
and the type of information that it will hold

data type variable name

int total;
int count, temp, result;

Multiple variables can be created in one declaration


Variable Initialization
39

´ A variable can be given an initial value in the declaration

int sum = 0;
int base = 32, max = 149;

When a variable is referenced in a program, its current value is used


Assignment
40

´ An assignment statement changes the value of a variable


´ The assignment operator is the = sign

total = 55;

The expression on the right is evaluated and the result is stored in the
variable on the left

The value that was in total is overwritten


You can only assign a value to a variable that is consistent with the
variable's declared type
41 Constants

´ A constant is an identifier that is similar to a variable except that


it holds the same value during its entire existence

´ As the name implies, it is constant, not variable

´ The compiler will issue an error if you try to change the value of
a constant

´ In Java, we use the final modifier to declare a constant

final int MIN_HEIGHT = 69;


42 Constants

´ Constants are useful for three important reasons

´ First, they give meaning to otherwise unclear literal values


´ For example, MAX_LOAD means more than the literal 250

´ Second, they facilitate program maintenance


´ If a constant is used in multiple places, its value need only be updated
in one place

´ Third, they formally establish that a value should not change,


avoiding inadvertent errors by other programmers
43
Primitive Data Types
Primitive Data
44

´ There are eight primitive data types in Java


´ Four of them represent integers:
´ byte, short, int, long

´ Two of them represent floating point numbers:


´ float, double

´ One of them represents characters:


´ char

´ And one of them represents boolean values:


´ boolean
45 Numeric Primitive Data

´ The difference between the various numeric primitive


types is their size, and therefore the values they can
store:

Type Storage Min Value Max Value

byte 8 bits -128 127


short 16 bits -32,768 32,767
int 32 bits -2,147,483,648 2,147,483,647
long 64 bits < -9 x 1018 > 9 x 1018

float 32 bits +/- 3.4 x 1038 with 7 significant digits


double 64 bits +/- 1.7 x 10308 with 15 significant digits
46 Characters

´ A char variable stores a single character


´ Character literals are delimited by single quotes:

'a' 'X' '7' '$' ',' '\n'

´ Example declarations:
char topGrade = 'A';
char terminator = ';', separator = ' ';

´ Note the distinction between a primitive character


variable, which holds only one character, and a String
object, which can hold multiple characters
47 Character Sets

´ A character set is an ordered list of characters, with each character


corresponding to a unique number
´ A char variable in Java can store any character from the Unicode
character set
´ The Unicode character set uses sixteen bits per character, allowing
for 65,536 unique characters
´ It is an international character set, containing symbols and
characters from many world languages
48 Characters

´ The ASCII character set is older and smaller than Unicode, but is still quite
popular

´ The ASCII characters are a subset of the Unicode character set, including:

uppercase letters A, B, C, …
lowercase letters a, b, c, …
punctuation period, semi-colon, …
digits 0, 1, 2, …
special symbols &, |, \, …
control characters carriage return, tab, ...
49 Boolean

´ A boolean value represents a true or false condition

´ The reserved words true and false are the only valid values
for a boolean type

boolean done = false;

´ A boolean variable can also be used to represent any two states,


such as a light bulb being on or off
50
Expressions
51 Expressions

´ An expression is a combination of one or more operators and


operands
´ Arithmetic expressions compute numeric results and make use of
the arithmetic operators:

Addition +
Subtraction -
Multiplication *
Division /
Remainder %

If either or both operands used by an arithmetic operator are


floating point, then the result is a floating point
52
Division and Remainder

´ If both operands to the division operator (/) are integers, the result
is an integer (the fractional part is discarded)

14 / 3 equals 4

8 / 12 equals 0

The remainder operator (%) returns the remainder after dividing the
second operand into the first

14 % 3 equals 2

8 % 12 equals 8
Operator Precedence
53

´ Operators can be combined into complex expressions

result = total + count / max - offset;


´ Operators have a well-defined precedence which determines
the order in which they are evaluated

´ Multiplication, division, and remainder are evaluated prior to


addition, subtraction, and string concatenation

´ Arithmetic operators with the same precedence are evaluated


from left to right, but parentheses can be used to force the
evaluation order
Operator Precedence
54

´ What is the order of evaluation in the following expressions?

a + b + c + d + e a + b * c - d / e
1 2 3 4 3 1 4 2

a / (b + c) - d % e
2 1 4 3

a / (b * (c + (d - e)))
4 3 2 1
55 Expression Trees

´ The evaluation of a particular expression can be shown using an


expression tree
´ The operators lower in the tree have higher precedence for that
expression

+
a + (b – c) / d
a /

- d

b c
56 Assignment Revisited

´ The assignment operator has a lower precedence than the


arithmetic operators

First the expression on the right hand


side of the = operator is evaluated

answer = sum / 4 + MAX * lowest;


4 1 3 2

Then the result is stored in the


variable on the left hand side
57 Assignment Revisited

´ The right and left hand sides of an assignment statement can


contain the same variable

First, one is added to the


original value of count

count = count + 1;

Then the result is stored back into count


(overwriting the original value)
58 Increment and Decrement

´ The increment and decrement operators use only one operand


´ The increment operator (++) adds one to its operand
´ The decrement operator (--) subtracts one from its operand
´ The statement
count++;
is functionally equivalent to
count = count + 1;
59 Increment and Decrement

´ The increment and decrement operators can be applied in postfix form:

count++

´ prefix form:

++count

´ When used as part of a larger expression, the two forms can have different
effects

´ Because of their subtleties, the increment and decrement operators should


be used with care
60 Assignment Operators

´ Often we perform an operation on a variable, and then store the result


back into that variable

´ Java provides assignment operators to simplify that process

´ For example, the statement

num += count; //compound assign

is equivalent to

num = num + count;


61 Assignment Operators

´ There are many assignment operators in Java, including the following:

Operator Example Equivalent To

+= x += y x = x + y
-= x -= y x = x - y
*= x *= y x = x * y
/= x /= y x = x / y
%= x %= y x = x % y
62 Assignment Operators

´ The right hand side of an assignment operator can be a complex


expression

´ The entire right-hand expression is evaluated first, then the result is


combined with the original variable

´ Therefore

result /= (total-MIN) % num;

is equivalent to

result = result / ((total-MIN) % num);


63 Assignment Operators

´ The behavior of some assignment operators depends on the types


of the operands

´ If the operands to the += operator are strings, the assignment


operator performs string concatenation

´ The behavior of an assignment operator (+=) is always consistent


with the behavior of the corresponding operator (+)
64
Data Conversion
65 Data Conversion

´ Sometimes it is convenient to convert data from one type to


another
´ For example, in a particular situation we may want to treat an
integer as a floating point value
´ These conversions do not change the type of a variable or the
value that's stored in it – they only convert a value as part of a
computation
66 Data Conversion

´ Conversions must be handled carefully to avoid losing


information
´ Widening conversions are safest because they tend to go from a
small data type to a larger one (such as a short to an int)
´ Narrowing conversions can lose information because they tend
to go from a large data type to a smaller one (such as an int to
a short)
´ In Java, data conversions can occur in three ways:
´ conversion by assignment
´ promotion
´ casting
67 Assignment Conversion

´ Assignment conversion occurs when a value of one type is


assigned to a variable of another

´ If money is a float variable and dollars is an int variable, the


following assignment converts the value in dollars to a float

money = dollars
´ Only widening conversions can happen via assignment

´ Note that the value or type of dollars did not change


68 Data Conversion

´ Promotion happens automatically when operators in expressions


convert their operands

´ For example, if sum is a float and count is an int, the value of


count is converted to a floating point value to perform the
following calculation:
result = sum / count;
69 Casting

´ Casting is the most powerful, and dangerous, technique for


conversion

´ Both widening and narrowing conversions can be accomplished


by explicitly casting a value

´ To cast, the type is put in parentheses in front of the value being


converted
´ For example, if total and count are integers, but we want a
floating point result when dividing them, we can cast total:

result = (float) total / count;


70 if statement

if (condition){
// TRUE block
}
else{
//FALSE block
}
71 Loops in java

´ for loop
for(int i=0; i<10; i++){
//body of the loop
}
´ while loop
while( condition){
//body of the loop
}
72 Acknowledgment

´ Material presented in these slides is adopted from


´ www.cs.njit.edu/cis113/

You might also like