Sunteți pe pagina 1din 67

CS-201/CS-261

Object Oriented Design &


Programming/Lab
OOP languages
• Both Java and C++ are most popular object-
oriented programming languages

• C++ was created at AT&T Bell Labs in 1979

• Java was born in Sun Microsystems in 1990


Variables for built-in types

In both C++ and Java

int x;
X


X
x = 5; 5
Reference variables
(in Java)

• Reference type variables


X
Button x; Button Object
… X

x = new Button(“click”); “click”


Variables that “hold” objects
(in C++)

• Declaration of an object variable


allocates space for the object
X

Button x(“Click”);
“click”
Pointers (in C++)
• Variables can be explicitly declared as
pointers to objects

Button *x;
X


Button Object
x = new Button(“click”); X

“click”
Disposing of allocated memory
• In Java, garbage collection is automatic
– Memory allocated to objects are reclaimed
when no variables refer to them
– Need to set reference variables to null when
the object is no longer needed

• In C++, object destruction is the


programmer’s responsibility using the
delete keyword
C++ control over copy and assignment

• In C++, the semantics of “a = b”


(assignment) can be specified
– by defining the copy-assignment operator
– both (a and b) are diff. objects but same
content

– In java it copies the address


Java basics
• Treats primitive data types and objects
differently
– int i; // i actually holds the value
– Account ac; // ac reference to a account
obj
Summary

• No pointer • Pointer
• No multiple • Multiple inheritance
inheritance • Manual garbage
• Automatic garbage collection
collection • Operator
• No operator overloading
overloading • goto statement and
• No goto statement structure and union
and no structure and data structure
union data structure
Why Java ?

• Java is a general purpose object


oriented programming language

• Internet programming language


History of Java
• A general purpose OOP language

• Developed by Sun Microsystems. (James Gostling)

• Initially called “Oak” but was renamed as “Java” in 1995

• Initial motivation is to develop a platform independent


language to create software to be embedded in various
consumer electronics devices

• Become the language of internet (portability and security)


Compiled and Interpreted
• Java works in two stage
– Java compiler translate the source code into byte code
– Java interpreter converts the byte code into machine
level representation
Byte Code:
- A highly optimized set of instructions to be executed by
the java runtime system, known as java virtual machine
(JVM)
- Not executable code
JVM:
- Need to be implemented for each platform
- Although the details vary from machine to machine, all
JVM understand the same byte code
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed
• Java Is Interpreted
• Java Is Robust
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic

www.cs.armstrong.edu/liang/intro6e/JavaCharacteristics.pdf
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed
Java is partially modeled on C++, but
• Java Is Interpreted
greatly simplified and improved. It is like
• Java Is Robust
C++ but with more functionality and fewer
• Java Is Secure negative aspects
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed
• Java Is Interpreted Java is inherently object-oriented. It
• Java Is Robust was designed from the start to be
• Java Is Secure object-oriented.
• Java Is Architecture-Neutral
One of the central issues in software
• Java Is Portable
development is how to reuse code.
• Java's Performance Object-oriented programming provides
• Java Is Multithreaded great flexibility, modularity, clarity, and
• Java Is Dynamic reusability through encapsulation,
inheritance, and polymorphism.
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed
• Java Is Interpreted
Distributed computing involves several
• Java Is Robust
computers working together on a
• Java Is Secure network.
• Java Is Architecture-Neutral
• Java Is Portable Java is designed to make distributed
• Java's Performance computing (e.g. Web Services) easy.
• Java Is Multithreaded Since networking capability is
• Java Is Dynamic inherently integrated into Java, writing
network programs is like sending and
receiving data to and from a file
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed
• Java Is Interpreted
• Java Is Robust
You need an interpreter to run Java
• Java Is Secure programs.
• Java Is Architecture-Neutral
• Java Is Portable The programs are compiled into
• Java's Performance bytecode. The bytecode is machine-
• Java Is Multithreaded independent and can run on any
• Java Is Dynamic machine that has a Java interpreter,
which is part of the JVM
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed
• Java Is Interpreted
• Java Is Robust
Java compiler can detect many
• Java Is Secure problems that would first show up at
• Java Is Architecture-Neutral execution time in other languages
• Java Is Portable
• Java's Performance Java has eliminated certain types of
• Java Is Multithreaded error-prone programming constructs
• Java Is Dynamic found in other languages (default
value, memory leak)

Java has a runtime exception-handling


feature to provide programming
support for robustness
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed Java implements several security
• Java Is Interpreted mechanisms to protect your system
•enforce array bound check(buffer overflow)
• Java Is Robust
•not allow to perform unsafe operations such
• Java Is Secure as pointer arithmetic or unchecked type casts
• Java Is Architecture-Neutral •not allow manual control over memory
• Java Is Portable allocation and deallocation; users rely on
• Java's Performance automatic garbage collection
• Java Is Multithreaded •Java Library provides APIs related to
• Java Is Dynamic security, such as standard cryptographic
algo’s, Auth., and secure comm protocols.
•Exception handling
•Ensure that no viruses are communicated
with an applet
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed
• Java Is Interpreted
• Java Is Robust
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
Write once, run anywhere
• Java Is Multithreaded
• Java Is Dynamic With a Java Virtual Machine (JVM),
you can write one program that will
run on any platform
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed
• Java Is Interpreted
• Java Is Robust
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable The execution of byte code by the JVM
makes java programs portable
• Java's Performance
• Java Is Multithreaded
Because Java is architecture neutral,
• Java Is Dynamic Java programs are portable. They can
be run on any platform without being
recompiled
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed
• Java Is Interpreted
• Java Is Robust
• Java Is Secure
•Java performance is slower than C
• Java Is Architecture-Neutral
•Can sometimes be even faster than
• Java Is Portable compiled C code!
• Java's Performance •Incorporation of multithreading enhance
• Java Is Multithreaded the overall execution speed
• Java Is Dynamic •Just-in-Time (JIT) can compile the byte
code into machine code

JIT compiler turns Java bytecode into instructions that can


be sent directly to a particular hardware platform's
processor.
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed
• Java Is Interpreted
• Java Is Robust
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable Multithread programming is smoothly
• Java's Performance integrated in Java,
• Java Is Multithreaded
• Java Is Dynamic whereas in other languages you have to
call procedures specific to the operating
system to enable multithreading
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed
• Java Is Interpreted
• Java Is Robust
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
• Capable of dynamically linking a new class
libraries, methods and objects.
• Java can use efficient functions available in
C/C++.
• Installing new version of library
automatically updates all programs
Basics of Java Environments

• Java programs normally undergo five phases


– Edit
• Programmer writes program (and stores program on disk)
– Compile
• Compiler creates bytecodes from program
– Load
• Class loader stores bytecodes in primary memory
– Verify
• Verifier ensures bytecodes do not violate security
requirements
– Execute
• Interpreter translates bytecodes into machine language
Program is created in an
Phase 1 Editor Disk editor and stored on disk
in a file ending with
.java.

Compiler creates
Phase 2 Compiler Disk bytecodes and stores
them on disk in a file
ending with .class.
Primary
Memory
Phase 3 Class Loader Class loader reads
.class files
containing
bytecodes from disk
and puts those
Disk bytecodes in
. .. memory.
..
.

Primary
Memory
Phase 4 Bytecode Verifier Bytecode verifier
confirms that all
bytecodes are valid
and do not violate
Java’s security
restrictions.
. ..
..
.

Primary
Memory Interpreter reads
Phase 5 Interpreter bytecodes and
translates them into a
language that the
computer can
understand, possibly
storing data values as
the program executes.
. ..
..
.
Java Environment

• Development tools-part of Java Development Kit (JDK)

• Classes and methods-part of Java Standard Library (JSL), also


known as Application Programming Interface (API)

1. JDK:
• Appletviewer ( for viewing applets)
• Javac (Compiler)
• Java (Interpreter)
• Javah (for C header files)
• Javadoc ( for creating HTML description)
Java Environment
2. Application Package Interface (API)
Contains hundreds of classes and methods grouped into several
functional packages:
• Language Support Package
• Utility Packages (random num. gen., sys. date manipulation)
• Input/Output Packages
• Networking Packages (implementing networking app. )
• AWT Package (classes for painting graphics and images)
• Applet Package (web page using java)
The Evolution of Java

1. Java 1.0 (96)


2. Java 1.1 (97)(Add new library, redefine applet handling and
reconfigured many features.)
3. Java 2 (98)(Second generation). Version no:1.2 (Internal
version number of java library). Also known as J2SE [ Java
2 Platform Standard Edition].
- Add swing, the collection framework, enhanced JVM etc.
4. J2SE 1.3 (2000)
5. J2SE 1.4 (2002)
6. J2SE 1.5 (2004)
7. J2SE 1.6 (2006) [1.7-(2011), in queue 1.8, 1.9]
Comments
In Java, comments are preceded by two slashes (//) in a
line, or
enclosed between /* and */ in one or multiple lines

When the compiler sees //, it ignores all text after // in


the same line

When it sees /*, it scans for the next */ and ignores any
text between /* and */
Example
/* Traditional "Hello World!" program. */

// package pack1;
// import java.lang.System;
class prog1
{
public static void main (String args[])
{
System.out.println("Hello World!");
}
}

Save program as prog1.java


Java Program Structure

Package Statement
• Javac command compiles the source code prog1.java then,
generates prog1.class and store it under a directory which
is
called as name of the package
• package statement if used must be the first statement in a
compilation unit. Its syntax is:
package packageName;

❑ For example:
package pack1;
Example
/* Traditional "Hello World!" program. */

// package pack1;
// import java.lang.System;
class prog1
{
public static void main (String args[])
{
System.out.println("Hello World!");
}
}
Import Statement

• The import statements are similar to


#include statements in C and C++
• In the above program, System class of java.lang
package is imported into all Java programs by
default. The syntax of import statement is as:
import fullClassName;
• For example, the following import statement
imports the System class from java.lang:
import java.lang.System;
import java.lang.*;
Example
/* Traditional "Hello World!" program. */

// package pack1;
// import java.lang.System;
class prog1
{
public static void main (String args[])
{
System.out.println("Hello World!");
}
}
Classes
• Class declarations contain a keyword class and an
identifier
• Class members are enclosed within braces. The
syntax of defining a class is shown below:

class prog1
{ // program code
}
Example
/* Traditional "Hello World!" program. */

// package pack1;
// import java.lang.System;
class prog1
{
public static void main (String args[])
{
System.out.println("Hello World!");
}
}
Main method
• To execute a class, it must contain a valid main
method

• It is the first method that automatically gets


invoked when the program executed

public static void main (String args[])


{ //instructions
}
Main method
public static void main (String args[])
{
//instructions
}
• The main method must always be defined as
public: to make it publicly accessible,
• static: to declare it as a class member and
• void: returns no value
• args[]: parameter is an array of class String.
It provides access to command line
parameters
Example
/* Traditional "Hello World!" program. */

// package pack1;
// import java.lang.System;
class prog1
{
public static void main (String args[])
{
System.out.println("Hello World!");
}
}
System class
System.out.println("Hello World!");

• invokes println method on object


named out variable (of type
java.io.PrintStream), which is a member
of System class. The println method
takes a String parameter and displays it on
the console
Read & Display a number
import java.io.*;
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
// Declare the variables
int num;

// Input the integer


System.out.println("Enter the integer: ");

// Create Scanner object


Scanner s = new Scanner(System.in);

// Read the next integer from the screen


num = s.nextInt();

// Display the integer


System.out.println("Entered integer is: " + num);
}
}
Check number is positive or negative
import java.io.*;
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
int n;
Scanner s = new Scanner(System.in);
System.out.print("Enter the number you want to check:");
n = s.nextInt();
if(n > 0)
{
System.out.println("The given number "+n+" is Positive");
}
else if(n < 0)
{
System.out.println("The given number "+n+" is Negative");
}
else
{
System.out.println("The given number "+n+" is neither Positive nor Negative ");
}
}
}
Add two number and display sum
import java.io.*;
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
int x, y, z;

System.out.println("Enter two integers to calculate their sum");


Scanner in = new Scanner(System.in);

x = in.nextInt();
y = in.nextInt();
z = x + y;

System.out.println("Sum of the integers = " + z);


}
}
Swap two numbers
import java.io.*;
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
int x = 10;
int y = 5;
System.out.println("Before swaping:" + " x = " + x + ", y = " + y);
x = x + y;
y = x - y;
x = x - y;
System.out.println("After swaping:“ + " x = " + x + ", y = " + y);
}
}
Data Types
• Java defines eight simple primitive types:
1)byte – 8-bit integer type
2)short – 16-bit integer type
3)int – 32-bit integer type
4)long – 64-bit integer type
5)float – 32-bit floating-point type
6)double – 64-bit floating-point type
7)char – symbols in a character set
8)boolean – logical values true and false
Data Types
• byte: 8-bit integer type.
Range: -128 to 127.
Example: byte b = -15;
Usage: particularly when working with data
streams.
• short: 16-bit integer type.
Range: -32768 to 32767.
Example: short c = 1000;
Usage: probably the least used simple type.
Data Types
• int: 32-bit integer type.
Range: -2147483648 to 2147483647.
Example: int b = -50000;
Usage:
1) Most common integer type.
2) Typically used to control loops and to index
arrays.
3) Expressions involving the byte, short and int
values are promoted to int before calculation.
Data Types
 long: 64-bit integer type.
Range: -9223372036854775808 to
9223372036854775807.
Example: long l = 10000000000000000;
Usage: 1) useful when int type is not large enough to
hold the desired value
 float: 32-bit floating-point number.
Range: 1.4e-045 to 3.4e+038.
Example: float f = 1.5;
Usage:
1) fractional part is needed
2) large degree of precision is not required
Data Types
• double: 64-bit floating-point number.
Range: 4.9e-324 to 1.8e+308.
Example: double pi = 3.1416;
Usage:
1) accuracy over many iterative calculations
2) manipulation of large-valued numbers
Data Types
char: 16-bit data type used to store
characters.
Range: 0 to 65536.
Example: char c = ‘a’;
Usage:
1) Represents both ASCII and UNICODE character
sets;
2) 2) Not the same as in C/C++ where char is 8-bit
and represents ASCII only.
Data Types
• boolean: Two-valued type of logical values.
Range: values true and false.
Example: boolean b = (1<2);
Usage:
1) returned by relational operators, such as
1<2
2) required by branching expressions such as
if or for
JAVA is strongly typed language !!
Variables
• declaration – how to assign a type to a variable
• initialization – how to give an initial value to a
variable
• scope – how the variable is visible to other parts of
the program
• lifetime – how the variable is created, used and
destroyed
• type conversion – how Java handles automatic type
conversion
• type casting – how the type of a variable can be
narrowed down
• type promotion – how the type of a variable can be
expanded
Variables
• Java uses variables to store data.
• To allocate memory space for a variable JVM
requires:
1) to specify the data type of the variable
2) to associate an identifier with the variable
3) optionally, the variable may be assigned an
initial value
• All done as part of variable declaration.
Basic Variable Declaration
• datatype identifier [=value];
• datatype must be
– A simple datatype
– User defined datatype (class type)
• Identifier is a recognizable name confirm
to identifier rules
• Value is an optional initial value.
Variable Declaration
• We can declare several variables at the same
time:
type identifier [=value][, identifier [=value]
…];
Examples:
int a, b, c;
int d = 3, e, f = 5;
byte g = 22;
double pi = 3.14159;
char ch = 'x';
Variable Scope
• Scope determines the visibility of program elements with
respect to other program elements.

• In Java, scope is defined separately for classes and


methods:
1) variables defined by a class have a global scope
2) variables defined by a method have a local scope
A scope is defined by a block:
{

}
A variable declared inside the scope is not
visible outside:
{
int n;
}
n = 1;// this is illegal
Variable Lifetime
• Variables are created when their scope is
entered by control flow and destroyed when their
scope is left:
• A variable declared in a method will not hold its
value between different invocations of this
method.
• A variable declared in a block looses its value
when the block is left.
• Initialized in a block, a variable will be re-
initialized with every re-entry. Variables lifetime
is confined to its scope!
Scope & Lifetime
// Demonstrate block scope.
class Scope {
public static void main(String args[]) {
int x; // known to all code within main

x = 10;
if(x == 10) { // start new scope
int y = 20; // known only to this block

// x and y both known here.


System.out.println("x and y: " + x + " " + y);
x = y * 2;
}
// y = 100; // Error! y not known here

// x is still known here.


System.out.println("x is " + x);
}
}
Scope & Lifetime
// Demonstrate lifetime of a variable.
class LifeTime {
public static void main(String args[]) {
int x;

for(x = 0; x < 3; x++) {


int y = -1; // y is initialized each time block
is entered
System.out.println("y iz: " + y); // this always
prints -1
y = 100;
System.out.println("y is now: " + y);
}
}
}
Arrays
• An array is a group of liked-typed
variables referred to by a common
• name, with individual variables accessed
by their index.
• Arrays are:
1) declared
2) created
3) initialized
4) used
• Also, arrays can have one or several
dimensions.
Array Declaration
• Array declaration involves:
1) declaring an array identifier
2) declaring the number of dimensions
3) declaring the data type of the array elements
• Two styles of array declaration:
type array-variable[];
or
type [] array-variable;
Array Creation
• After declaration, no array actually exists.
• In order to create an array, we use the new
operator:
type array-variable[];
array-variable = new type[size];
• This creates a new array to hold size elements of
type type, which reference will be kept in the
variable array-variable.
Array Indexing
• Later we can refer to the elements of this
array through their indexes:
• array-variable[index]
• The array index always starts with zero!
• The Java run-time system makes sure that
all array indexes are in the correct range,
otherwise raises a run-time error.
Array Initialization

• Arrays can be initialized when they are


declared:
• int monthDays[] =
{31,28,31,30,31,30,31,31,30,31,30,31};
• Note:
1) there is no need to use the new operator
2) the array is created large enough to hold
all specified elements

S-ar putea să vă placă și