Sei sulla pagina 1di 119

INTRODUCTION TO JAVA

PROGRAMMING

Java: Write Once, Run


Anywhere (3)

Java has been used by large and reputable companies to


create serious stand-alone applications.
Example:
Eclipse1: started as a programming environment created by
IBM for developing Java programs. The program Eclipse was
itself written in Java.

1 For more information:

Java Development Kit (JDK)


It is a collection of development tools.
These are used for developing and running java
programs.
Components of JDK
Javac (Java compiler)
Java (Java Interpreter)
Javap (Java disassembler- disassembles one or more class
files)
Javah (for cretaing C header files or source or output files)
Javadoc (for creating HTML documents)
Appletviewer (for viewing Java applets)
Jdb (Java Debugger)

Process of Building and Running Java Programs


Text Editor
Java Source
Code

javadoc

HTML Files

javah

Header Files

javac

Java Class File

java

Output

jdb

Java Runtime Environment vs. Java Development Kit


A Java distribution comes typically in two flavors, the Java
Runtime Environment (JRE) and the Java Development Kit
(JDK).
The Java runtime environment (JRE) consists of the JVM and
the Java class libraries and contains the necessary functionality
to start Java programs.
The JDK contains in addition the development tools necessary to
create Java programs. The JDK consists therefore of a Java
compiler etc.

Java Virtual Machine(JVM)


The JVM is the environment in which Java programs execute.
It is a software that is implemented on top of real hardware and
operating system.
When the source code (.java files) is compiled, it is translated into
byte codes and then placed into (.class) files.
The JVM executes these bytecodes. So Java byte codes can be thought
of as the machine language of the JVM.
A JVM can either interpret the bytecode one instruction at a time or the
bytecode can be compiled further for the real microprocessor using
what is called a just-in-time compiler (e.g Oracle JRockit JVM)
The JVM must be implemented on a particular platform before
compiled programs can run on that platform.

The Java Software Development Kit (SDK)

The Java SDK comes in three versions:

J2ME - Micro Edition (for handheld and portable devices)


J2SE - Standard Edition (PC development)
J2EE - Enterprise Edition (Distributed and Enterprise Computing)

The SDK is a set of command line tools for developing Java applications:
javac - Java Compiler
java - Java Interpreter (Java VM)
appletviewer - Run applets without a browser
javadoc - automated documentation generator
jdb - Java debugger

The SDK is NOT an IDE (Integrated Development Environment)


Command line only. No GUI.

Commonly Used Packages


While it should be your goal to learn as many packages as you can, there are some
packages you will use more than others:

Language
(general)

java.lang

Common classes used for all


application development

GUI

java.awt
java.awt.event
javax.swing

Graphical User Interface,


Windowing,
Event processing

Misc. Utilities
and Collections

java.util

Helper classes, collections

Input/Output

java.io

File and Stream I/O

Networking

java.net

Sockets, Datagrams

COMPILING AND EXECUTING

FIRST JAVA PROGRAM

Getting Started
(1) Create the source file:
open a text editor, type in the code which defines a class (HelloWorldApp) and then save it in a
file (HelloWorldApp.java)
file and class name are case sensitive and must be matched exactly (except the .java part)
Example Code: HelloWorldApp.java

public class HelloWorldApp


{
public static void main(String[] args)
{
// Display "Hello World!"
System.out.println("Hello World!");
}
}

Java is CASE SENSITIVE!

Getting Started
(2) Compile the program:
compile HelloWorldApp.java by using the following command:
javac HelloWorldApp.java

it generates a file named HelloWorldApp.class

javac

is not recognized as an internal or


command, operable program or batch file.

external

javac: Command not found


if you see one of these errors, you have two choices:
1) specify the full path in which the javac program locates every
time. For example:
C:\j2sdk1.4.2_09\bin\javac HelloWorldApp.java

2) set the PATH environment variable

Getting Started
(3) Run the program:
run the code through:
java HelloWorldApp

Note that the command is java, not javac, and you


refer to
HelloWorldApp, not HelloWorldApp.java or
HelloWorldApp.class
Exception in thread "main"
java.lang.NoClassDefFoundError:
HelloWorldApp

if you see this error, you may need to set the environment
variable CLASSPATH.

Explaining first program


public class HelloWorldApp
{
public static void main(String[] args)
{
// Display "Hello World!"
System.out.println("Hello World!");
}
}

public: so that JVM can


access the main method
static: so that JVM can call
main method w/o creating
object.
void : no return type
main: starting point
String args[] : command line
arguments in form of string
array.

Explaining first program


public class HelloWorldApp
{
public static void main(String[] args)
{
// Display "Hello World!"
System.out.println("Hello World!");
Is a method of
}
printstream class
Object of printStream
}
Inbuilt class in Java.lang
package

class

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

Characteristics of Java

Java is partially modeled on C++,


Java Is Simple
but greatly simplified and improved.
Java Is Object-Oriented
Some people refer to Java as "C+
Java Is Distributed
+--" because it is like C++ but with
more functionality and fewer
Java Is Interpreted
negative aspects.
Java Is Robust
Java Is Secure
Java Is ArchitectureNeutral
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 Robust
Java Is Secure
Java Is ArchitectureNeutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic

Java is inherently object-oriented.


Although many object-oriented
languages began strictly as
procedural languages, Java was
designed from the start to be
object-oriented. Object-oriented
programming (OOP) is a popular
programming approach that is
replacing traditional procedural
programming techniques.
One of the central issues in
software development is how to
reuse code. Object-oriented
programming provides great
flexibility, modularity, clarity, and
reusability through encapsulation,
inheritance, and polymorphism.

Characteristics of Java

Java Is Simple
Java Is Object-Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is ArchitectureNeutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic

Distributed computing involves


several computers working
together on a network. Java is
designed to make distributed
computing easy. Since networking
capability is 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
Java Is Secure
Java Is ArchitectureNeutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic

You need an interpreter to run


Java programs. The programs are
compiled into the Java Virtual
Machine code called bytecode.
The bytecode is machineindependent and can run on any
machine that has a Java
interpreter, which is part of the
Java Virtual Machine (JVM).

Characteristics of Java

Java Is Simple
Java Is Object-Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is ArchitectureNeutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic

Java compilers can detect many


problems that would first show up
at execution time in other
languages.
Java has eliminated certain types
of error-prone programming
constructs found in other
languages.
Java has a runtime exceptionhandling feature to provide
programming support for
robustness.

Characteristics of Java

Java Is Simple
Java Is Object-Oriented
Java Is Distributed
Java Is Interpreted
Java implements several security
Java Is Robust
mechanisms to protect your
Java Is Secure
system against harm caused by
stray programs.
Java Is ArchitectureNeutral
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 Robust
Java Is Secure
Java Is ArchitectureNeutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic

Write once, run anywhere


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 ArchitectureNeutral
Because Java is architecture
Java Is Portable
neutral, Java programs are
Java's Performance portable. They can be run on any
platform without being
Java Is Multithreaded recompiled.
Java Is Dynamic

Characteristics of Java

Java Is Simple
Java Is Object-Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is ArchitectureNeutral
Javas performance Because Java
Java Is Portable
is architecture neutral, Java
Java's Performance programs are portable. They can
be run on any platform without
Java Is Multithreaded being recompiled.
Java Is Dynamic

Characteristics of Java

Java Is Simple
Java Is Object-Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is ArchitectureNeutral
Java Is Portable
Java's Performance Multithread programming is smoothly
integrated in Java, whereas in other
Java Is Multithreadedlanguages you have to call
procedures specific to the operating
Java Is Dynamic
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 ArchitectureNeutral
Java Is Portable
Java was designed to adapt to an
Java's Performance evolving environment. New code can be
loaded on the fly without recompilation.
Java Is MultithreadedThere is no need for developers to create,
and for users to install, major new
Java Is Dynamic
software versions. New features can be
incorporated transparently as needed.

Main Differences

JAVA AND C++

Java vs C++
Java is (an interpreted) write once, run anywhere
language.
- Write once, run everywhere does (nearly) NEVER work with C++, but
does (nearly) ALWAYS work with JAVA.
- Acheived using bytecode concept.

You don't have separated HEADER-files defining classproperties


You can define elements only within a class.
All method definitions are also defined in the body of the class.
File- and classname must be identical in JAVA
Instead of C++ #include you use the import keyword.
For example: import java.awt.*;.
#include does not directly map to import, but it has a similar feel to it

JAVA vs C++
Instead of controlling blocks of
declarations like C++ does, the
access specifiers (public, private, and
protected) are placed on each
definition for each member of a class
Without an explicit access specifier, an element defaults
to "friendly," which means that it is accessible to other
elements in the same package (which is a collection of
classes being friends)
The class, and each method within the class, has an
access specifier to determine whether its visible outside
the file.

JAVA vs C++
Everything must be in a class.
There are no global functions or global data. If you want
the equivalent of globals, make static methods and
static data within a class.
There are no structs or enumerations or unions, only
classes.
Class definitions are roughly the same form in Java as in C++,
but theres no closing semicolon.

Java has no preprocessor.


If you want to use classes in another library, you say import
and the name of the library.
There are no preprocessor-like macros.
There is no conditional compiling (#ifdef)

JAVA vs C++
All the primitive types in Java have
specified sizes that are machine
independent for portability.
- The char type uses the international 16-bit Unicode
character set, so it can automatically represent most
national characters.

Type-checking and type requirements are


much tighter in Java.
For example:
1. Conditional expressions can be only boolean, not
integral.
2. The result of an expression like X + Y must be used; you
cant just say "X + Y" for the side effect.

JAVA vs C++
There are Strings in JAVA
Strings are represented by the String-class, they arent
only some renamed pointers
Static quoted strings are automatically converted into
String objects.
There is no independent static character array string like
there is in C and C++.

There are no Java pointers in the


sense of C and C++

JAVA vs C++
Although they look similar, arrays have a very
different structure and behavior in Java than they do
in C++.

Theres a read-only length member that tells you how big the array
is, and run-time checking throws an exception if you go out of bounds.

All arrays are created on the heap, and you can assign one array to
another (the array handle is simply copied).

There is a garbage collection in JAVA


Garbage collection means memory leaks are much harder to cause in
Java, but not impossible.

There are no destructors in Java.


There's no need because of garbage collection.

JAVA vs C++
Java has method overloading, but no
operator overloading.
Java has both kinds of comments like C++ does.
Theres no goto in Java.
The one unconditional jump mechanism is the break label or
continue label, which is used to jump out of the middle of
multiply-nested loops.

Java contains standard libraries for GUIs


Simple, robust and effective way of creating user-interfaces
Graphical output as part of the language

Features of C++ omitted in


JAVA
1. No Typedef, pre-processor(#define,#include),
2.
3.
4.
5.
6.
7.
8.
9.

Structure & Unions.


No standalone functions, global functions, global
data everything in a class.
Member functions to be defined only inside a class
(No inline functions)
No goto and delete keyword used.
No default arguments to functions.
Objects are passed by reference only not by value
but references are themselves values.
No Pointers so no use of :: & -> operators
No Multiple Inheritance interfaces instead.
No forward declaration, no semicolon at end of
class.

Features of C++ omitted in JAVA


10. No automatic type conversion that results in loss of
precision.
11. Primitive data type size is same for all platforms
12. No copy constructors as all objects are passed by references
only.
13. No destructors as work done automatically by Garbage
collector..
14. No declaration of static member outside class.
15. Interpretation of private, public and protected keyword is
different.
16. No Templates but support collections/generics
17. No virtual functions all dynamic binding (final keyword)
18. No Operator Overloading.

Lexical Issues
There are many atomic elements of Java. Java programs are a
collection of whitespace, identifiers, comments, literals, operators,
separators and keywords.
Whitespace
Java is a free-form language. It means we do not need to follow any special
indentation rules. In java whitespace is a space, tab, or newline.

Identifiers
Identifiers are used for class names, method names and variable names.
An identifier may be any descriptive sequence of uppercase and lowercase
letters, numbers, or the underscore and dollor-sign characters.

Eg: AvgTemp, count, $calculate, s5, value_display

An identifier must not begin with a number because it leads to invalid


indentifier.

5/7/16

Eg: 5s, yes/no


BY: Raju Pal

37

Lexical Issues
Literals
A constant value in Java is created by using a literal representation. A literal is
allowed to use anywhere in the program.
Eg:

Integer literal : 100


Floating-point literal : 98.6
Character literal : s
String literal : sample

Comments
// This comment extends to the end of the line.
/*..............the multi-line comments are given with in this comment
............................................................................................................*/
/**....... Documentation comments..........*/
(readable to both human and computer)
5/7/16

BY: Raju Pal

38

Lexical Issues
Separators
Separators are used to terminate statements. In java there are few
characters are used as separators . They are, parentheses(), braces{},
brackets[], semicolon;, period., and comma,.
Java Keywords ( 49 )

5/7/16

BY: Raju Pal

39

Data Types

1.
2.
3.
4.

Data type specify the size and type of values


Java defines eight simple types of data. These can be put into
four groups:
Integers
Floating-point numbers
Characters
Boolean

Range: -2x-1 to 2x-1-1 where x is number of bits.


Leftmost bit is reserved for the sign.
5/7/16

BY: Raju Pal

40

Data Types
Integers
Name

Width(Size)

Range

byte

8 bits

-128 to 127

short

16 bits

-32768 to 32767

int

32 bits

-2147483648 to 2147483647

long

64 bits

-264-1 to 264-1 -1

Floating-point

5/7/16

Name

Width(Size)

Range

float

32 bits

1.4e-045 to 3.4e+038

double

64 bits

4.9e-324 to 1.8e+038

BY: Raju Pal

41

Data Types
Characters
A char variable stores a single character from the Unicode
character set
A character set is an ordered list of characters, and each
character corresponds to a unique number
Unicode is an international character set, containing symbols
and characters from many world languages
The Unicode character set uses 16 bits per character, allowing
for 65,536 unique characters
Character literals are enclosed in single quotes:
A' c' 3' '$' .' '\n
5/7/16

BY: Raju Pal

42

Data Types
You might have heard about the ASCII character set
ASCII 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,
digits 0, 1, 2,
special symbols *, &, +, ?,
control characters
backspace \b

escape sequences) new line \n,

Characters
Data type used to store character is char.
It requires 16 bits.
Range of a char is 0 to 65536 (no negative char)
5/7/16

BY: Raju Pal

43

Data Types
Boolean
Used to test a particular condition
It can take only two values: true and false
Uses only 1 bit of storage
All comparison operators return boolean value

5/7/16

BY: Raju Pal

44

Constants
Refer to fixed values that do not change during the execution of a
program.
Integer Constants: sequence of digits
123 037 0X2
Real Constants: numbers containing fractional parts
0.0083 -0.75 435.36
Single character Constants: single character
5 A ;
String Constants: sequence of characters
Hello World ?+;;;;.#
Backslash character (Symbolic) Constants: used in output methods

\n\b\t \ \\ \\

5/7/16

BY: Raju Pal

45

Constants

5/7/16

BY: Raju Pal

46

Symbolic Constants
Some constants may appear repeatedly in a number of places in
the program.
These constants can be defined as a symbolic name
Make a program:
easily modifiable
More understandable
final type symbolic name = value
ex:
final float PI = 3.14159
5/7/16

BY: Raju Pal

47

Variables
An identifier that denotes a storage location used to store a data value.
May take different values at different times during the execution of the
program
Naming Conventions: may consists of alphabets, digits, underscore and dollar
with following conditions
Must not begin with a digit
Uppercase and Lowercase are distinct.
Should not be a keyword
Space is not allowed
Variable declaration and assignment
<type> variable_name;
Variable_name =value; // initializtaion
Variable_name=Math.sqrt(Variable_name* Variable_name);
dynamic initialization
5/7/16

BY: Raju Pal

//

48

Scope of Variables
Classified into three kinds:
Instance Variables
Created when the objects are instantiated
Take different values for each object
Class Variables
Global to a class
Belong to the entire set of objects that class creates
Only one memory location is created
Local Variables
Used inside methods or inside program blocks.
Blocks are defined between opening brace { and a closing brace }
Visible to program only from the beginning to the end of the block.
5/7/16

BY: Raju Pal

49

Type Casting

The process of converting one data type to another is called


casting
type variable1 = (type) variable2
int m = 50;
byte n = (byte) m

Casting into a smaller type may result in a loss of data

Automatic Conversion:(smaller to larger-promotion)


Automatic type conversion is possible only if the destination
type has enough space to store the source value.

5/7/16

BY: Raju Pal

50

Type Casting
Type
Casting

Widening
(implicit)

5/7/16

Narrowing
(Explicit)

Assigning a smaller type to


a larger one

Assigning a larger type to


a smaller one

No need to write anything


(automatic conversion)

Write the target data type


within parenthesis

byte b = 75

int a = 75

int a =b

byte b = (byte) a
BY: Raju Pal

51

Type Casting

5/7/16

BY: Raju Pal

52

Type Casting

5/7/16

BY: Raju Pal

53

Type Casting

5/7/16

BY: Raju Pal

54

Array

Array is a list of finite number n of homogeneous data elements


such that:

The elements of the array are referenced respectively by


an index set of n consecutive numbers.

The element of the array are stored respectively in


successive memory location.

The number n of elements is called the length or size.

5/7/16

BY: Raju Pal

55

Creation of Arrays
After declaring arrays, we need to allocate memory for
storage array items.
In Java, this is carried out by using new operator, as
follows:
stude
Arrayname = new type[size];
nts
0
Examples:
1
students = new int[7];
2
3

Declaring and defining in the same statement:

int[] students=new students[10];


double myList[] = new double[10];

5/7/16

BY: Raju Pal

56

Initialization of Arrays
1. Once arrays are created, they need to be initialised with
some values before access their content. A general form of
initialisation is:
Arrayname [index/subscript] = value;
2. Example:
stude
nts
students[0] = 50;
0
50
students[1] = 40;
1
3. Array index starts with 0 and ends with n-1
2
3
4. Trying to access an array beyond its
4
boundaries will generate an error message.
5
students[7] = 100;
6

5/7/16

BY: Raju Pal

57

Explicit initialization
1.

Arrays can also be initialised like standard variables at the time of their
declaration.
Type arrayname[] = {list of values};

2.

Example:
int[] students = {55, 69, 70, 30, 80, 90, 45};

3.

Creates and initializes the array of integers of length 7.

4.

In this case it is not necessary to use the new operator.

5/7/16

BY: Raju Pal

stude
nts
0
55
1

69

70

30

80

90

45

58

Array: Default Values


When an array is created, its elements are assigned the default
value of
0 for the numeric primitive data types,
'\u0000' for char types, and
false for boolean types
Once an array is created, its size is fixed. It cannot be changed.
You can find its size using
arrayRefVar.length
5/7/16

BY: Raju Pal

59

Processing Array Elements using loop


Often a for( ) loop is used to process each of the elements of the array in
turn.

The loop control variable, i, is used as the index to access array


components

5/7/16

BY: Raju Pal

60

Array as Parameters
Methods can accept arrays via parameters
Use square brackets [ ] in the parameter declaration:

5/7/16

BY: Raju Pal

61

Returning Array
A method may return an array as its result
double [] readArray(int n)
{
double result[] = new double[n];
for (i = 0; i < n; i++)
{
result[i] = i;
}
return result;
}

5/7/16

BY: Raju Pal

62

Two Dimensional Arrays


Two dimensional arrays allows us to store data that are recorded in
table.
int[][] student=new int[4][4];
4 arrays each having 4 elements
First index: specifies array (row)
Second Index: specifies element in that array (column)

5/7/16

10

20

85

45

56

58

25

58

45

85

65

78

65

14

28

56
BY: Raju Pal

63

Accessing 2D Array Elements


Sum the Elements
Here is code that sums all the numbers in table.
The outer loop iterates four times and moves down the
rows.
Each time through the outer loop, the inner loop iterates
five times and moves across a different row.

5/7/16

BY: Raju Pal

64

Declaration and Instantiation of 2D


Array

Declaring and instantiating two-dimensional arrays are


accomplished by extending the processes used for onedimensional arrays:
Declaration:
int myArray [][];
Creation or Instantiation:
myArray = new int[4][3]; // OR
int myArray [][] = new int[4][3];
Initialisation:
- Single Value;
myArray[0][0] = 10;
- Multiple values:
int table[2][3] = {{10, 15, 30}, {14, 30, 33}};
int table[][] = {{10, 15, 30}, {14, 30, 33}};
5/7/16

BY: Raju Pal

65

2D Array as Array of Arrays


int table [][] = new int[4][5];

The variable table references an array of four elements.


Each of these elements in turn references an array of five integers.

5/7/16

BY: Raju Pal

66

Variable Size Arrays


Java treats multidimensional arrays as arrays of arrays. It
is possible to declare a 2D arrays as follows:
int a[][] = new int [3][];
a[0]= new int [2];
a[1]= new int [3];

[0]

[0
]

[1]

[0] [1] [2]

[2]

[0] [1] [2] [3]

[1
]

a[2]= new int [4];

5/7/16

BY: Raju Pal

67

Multidimensional Arrays
Example: A farmer has 10 farms of beans each in 5
countries, and each farm has 30 fields!
Three-dimensional array:
long[][][] beans=new long[5][10][30];
//beans[country][farm][fields]

5/7/16

BY: Raju Pal

68

Varying length in Multidimensional


Arrays
Same features apply to multi-dimensional arrays as those of 2
dimensional arrays
long beans=new long[3][][]; //3 countries
beans[0]=new long[4][]; //First country has 4 farms
beans[0][4]=new long[10];//Each farm in first country has 10
fields

5/7/16

BY: Raju Pal

69

Exercise-1
1.
2.

3.

4.

WAP in Java that create an array and simple print the element of the array.
(Array Traversing).
WAP in Java that implements following three methods:
1. boolean Search( int [] A, int Key): it takes an array A and a Key as input and
returns true if Key is in the array else return false.
2. int Position(int [] A, int Key): it takes an array A and a Key as input and
returns the position of Key in the array.
3. int [] Sort(int [] A): it takes an array A and returns another array. The output
array has same element as in input array but in ascending order.
WAP in Java that takes an two dimensional array as input parameter to a method
and returns one dimensional array. Each element of the output array is the sum
of the element of corresponding row in input array.
WAP in Java to add, multiply, and subtract two Matrices. The decision of
operation should be made based on users choice.

5/7/16

BY: Raju Pal

70

Classes
A class is a user-defined data type. Once defined, this
new type can be used to create variables of that type.
These variables are termed as instances of classes,
which are the actual objects.
A class is a template for an object, and an object is an
instance of a class.
5/7/16

BY: Raju Pal

71

Classes and Objects


Class Name: Circle

A class template

Data Fields:
radius is _______
Methods:
getArea

Circle Object 1

Circle Object 2

Circle Object 3

Data Fields:
radius is 10

Data Fields:
radius is 25

Data Fields:
radius is 125

Three objects of
the Circle class

An object has both a state and behavior. The state


defines the object, and the behavior defines what
the object does.
5/7/16

BY: Raju Pal

72

Class cont..
//Basic form of a class
class classname
{
type variable1
type variable2
-----------------------------type methodname1(parameter_list)
{
//body of method
}
type methodname2(parameter_list)
{
//body of method
}
--------------}

5/7/16

BY: Raju Pal

//A Simple Class


class Box
{
double width
double height
double depth
}
Data is encapsulated in a class
by placing data fields inside
the body of the class definition.

73

Declaring (creating) Objects


Declaring Object Reference Variables
ClassName objectReference;
Example:

Box myBox;

Creating Objects
objectReference = new ClassName();
Example: myBox = new Box();
The object reference is assigned to the object reference variable.
Declaring/Creating Objects in a Single Step
ClassName objectReference = new ClassName();
Example: Box myBox = new Box();
5/7/16

BY: Raju Pal

74

Accessing Objects
Referencing the objects data:
objectRefVar.data
e.g., myBox.width
myBox.height
myBox.depth

Invoking the objects method:


objectRefVar.methodName(arguments)
e.g., myBox.getArea()
5/7/16

BY: Raju Pal

75

Classes and Objects


Trace Code
Declare myBox

Box myBox = new Box();

myBox

null

Box yourBox = new Box();


yourBox.width = 100;
yourBox.height = 10;
yourBox.depth= 50;

5/7/16

BY: Raju Pal

76

Classes and Objects


Trace Code, cont.
Box myBox = new Box();
myBox

Box yourBox = new Box();


yourBox.width = 100;

null

Box

yourBox.height = 10;

Width
Height
Depth

yourBox.depth= 50;

Create a Box

5/7/16

BY: Raju Pal

77

Classes and Objects


Trace Code, cont.
Box myBox = new Box();
myBox

Box yourBox = new Box();


yourBox.width = 100;
yourBox.height = 10;

Assign object
reference to myBox

Box
Width
Height
Depth

yourBox.depth= 50;

5/7/16

reference value

BY: Raju Pal

78

Classes and Objects


Trace Code, cont.
Box myBox = new Box();
myBox

Box yourBox = new Box();


yourBox.width = 100;

reference value

Box

yourBox.height = 10;

Width
Height
Depth

yourBox.depth= 50;

yourBox

null

Declare yourBox

5/7/16

BY: Raju Pal

79

Classes and Objects


Trace Code, cont.

Box myBox = new Box();


myBox

Box yourBox = new Box();


yourBox.width = 100;

reference value

Box

yourBox.height = 10;

Width
Height
Depth

yourBox.depth= 50;

null

yourBox
Create a new
Box object
5/7/16

BY: Raju Pal

Box
Width
Height
Depth

80

Classes and Objects


Trace Code, cont.

Box myBox = new Box();


myBox

Box yourBox = new Box();


yourBox.width = 100;

reference value

Box

yourBox.height = 10;

Width
Height
Depth

yourBox.depth= 50;

yourBox
Assign object
reference to yourBox
5/7/16

BY: Raju Pal

reference value

Box
Width
Height
Depth

81

Classes and Objects


Trace Code, cont.

Box myBox = new Box();


myBox

Box yourBox = new Box();

reference value

yourBox.width = 100;

Box

yourBox.height = 10;

Width
Height
Depth

yourBox.depth= 50;

reference value

yourBox
Change variables in
yourBox

5/7/16

BY: Raju Pal

Box
Width =100
Height=10
Depth =50

82

Classes and Objects


Trace Code, cont.

Box myBox = new Box();


myBox

Box yourBox = new Box();


yourBox.width = 100;

reference value

Box

yourBox.height = 10;

Width
Height
Depth

yourBox.depth= 50;
myBox = yourBox;

yourBox

reference value

Box
Assigning Object
Reference Variables
5/7/16

BY: Raju Pal

Width =100
Height=10
Depth =50

83

Garbage Collection

When no references to an object exist, that object is assumed too


be no longer needed, and the memory occupied by the object
can be reclaimed.
As shown in the previous figure, after the assignment statement
myBox = yourBox, myBox points to the same object referenced
by yourBox. The object previously referenced by myBox is no
longer referenced. This object is known as garbage. Garbage is
automatically collected by JVM.
If you know that an object is no longer needed, you can
explicitly assign null to a reference variable for the object. The
JVM will automatically collect the space if the object is not
referenced by any variable.

5/7/16

BY: Raju Pal

84

The finalize() Method


Sometimes an object will need to perform some action when it is
destroyed.
The garbage collector calls a special method named finalize in your
object if that method exists.
If an object hold some non-Java resources (file handle or window
character font) or any reference to other objects, these resources can be
freed using finalize method.
Avoiding circular reference.
protected void finalize()
{
//finalization code here
}
5/7/16

BY: Raju Pal

85

Differences between Variables of


Primitive Data Types and Object Types
Primitive type

int i = 1

Object type

Circle c

reference

c: Circle
Created using
new Circle()

5/7/16

radius = 1

BY: Raju Pal

86

Copying Variables of Primitive Data Types and


Object Types
Primitive type assignment
i=j

Object type assignment


c1 = c2

Before:

After:

c1

c1

c2

c2

5/7/16

Before:

After:

c1: Circle

c2: Circle

radius = 5

radius = 9

BY: Raju Pal

87

Introducing Methods
type name(parameter-list)
{
//body of method
return value; (if type is not void)
}
Define the interface to most classes.
Hide specific layout of internal data structures(Abstraction)
Add method to Box class
void volume()
{
System.out.print(Volume is: );;
System.out.println(width*height*depth);
}
5/7/16

BY: Raju Pal

88

Returning a Value
double volume()
{
return width*height*depth;
}

The type of data returned by a method must be compatible


with the return type specified by the method.
The variable receiving the value returned by a method must
also be compatible with the return type specified for the
method.
5/7/16

BY: Raju Pal

89

Parameterized Methods
void setDim(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}

Parameters: variable defined by a method that receives a value


when the method is called
Arguments: value that is passed to a method when it is invoked.
5/7/16

BY: Raju Pal

90

Constructors

Box()
{
//default constructor
}
Box()
{
width = 10;
height = 10;
depth = 10;
}
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
Box myBox = Box();
Box yourBox = Box(20,20,20);
5/7/16

BY: Raju Pal

Constructors are a special


kind of methods that are
invoked to construct
objects.
A Constructor initializes
an object immediately
upon creation.
Automatic initialization.

91

Constructors cont
A constructor with no parameters is referred to as a default
constructor.
Constructors must have the same name as the class itself.
Constructors do not have a return typenot even void.
Implicit return type of a class constructor is the class type
itself.
Constructors are invoked using the new operator when
an object is created.
Constructors play the role of initializing objects.
5/7/16

BY: Raju Pal

92

The this Keyword


this can be used inside any method to refer to the current
object.
When you want to pass the current object to a method.
To resolve any name space collisions that might occur
between instance variables and local variables.
Box(double width, double height, double depth)
{
this.width = width;
this.height = height;
this.depth = depth;
}
5/7/16

BY: Raju Pal

93

The this Keyword Cont


class Data
{
private String data_string;
Data(String S){data_string = s;}
public String getData(){return data_string;}
public void printData()
{
Printer p = new Printer();
p.print(this);
}
}
class Printer
{
void print(Data d){System.out.println(d.getData);}
}
public class app
{
public static void main(String args[])
{
(new Data(Hello from Java)).printData();
5/7/16
BY: Raju Pal
}

94

Overloading Methods
Method overloading defines several different versions of a method
all with the same name, but each with a different parameter list.
At the time of method call, java compiler will know which one you
mean by the number and/or types of the parameters.
Overloaded methods must differ in the type and/or number of their
parameters.
Implements polymorphism
May have different return types.
To overload a method, you just define it more than once,
specifying a new parameter list different from every other
5/7/16

BY: Raju Pal

95

Overloading Methods example


Class calculator
{
int add(int op1, int op2)
{
return op1+op2;
}
int add(int op1, int op2, op3)
{
return op1+op2+op3;
}
}
In C you have three functions to get the absolute value of different data types
abs() for integer, fabs() for floating point, and lfabs() for long integer.
5/7/16

BY: Raju Pal

96

Overloading Constructors
Works like overloading other methods.
Define the constructor a number of times, each time with a different parameter
list.
//when all dimensions specified
Box(double w, double h, double d){
Width = w;
Height = h;
Depth = d;
}
//when cube is created
Box(double l){
Width = Height = Depth = l;
}
Box myBox = new Box(10,20,15);
Box yourBox = new Box(25);
5/7/16

BY: Raju Pal

97

Using Objects as Parameters


An object of a class can be passed as parameter to both methods and
constructors of a class.
/*construct a new object so that it is initially the same
as some existing object.
Define a new constructor Box that takes an object of its
class as a parameter.
*/
Box(Box ob){
Width = ob.Width;
Height = ob.Height;
Depth = ob.Depth;
}
Box myBox = new Box(10,20,15);
Box yourBox = new Box(myBox);
5/7/16

BY: Raju Pal

98

Using Objects as Parameters cont


//objects may be passed to methods
class Test{
int a,b;
Test(int i, int j){
a = i;
b = j;
}
//return true if obj is equal to the invoking obbject
boolean equals(Test obj){
if(obj.a == a && obj.b == b) return true;
else return false;
}
}
Test ob1 = new Test(100, 22);
Test ob2 = new Test(100, 22);
Test ob3 = new Test(-1,-1);
ob1.equals(ob2); true
Ob1.equals(ob3); false
5/7/16

BY: Raju Pal

99

Type of Argument Passing


Call-by-value:
When you pass an item of a simple data type to a method.
Method only gets a copy of the data item.
The code in the method cannot affect the original data item at all.
class Test{
void meth(int i, int j){
i=i*2;
j=j/2;
}
}
Test ob = new Test();
int a = 15, b = 20;
Systeem.out.println( a and b before call: +a+ +b); 15 20
ob.meth(a,b);
Systeem.out.println( a and b after call: +a+ +b); 15 20
5/7/16

BY: Raju Pal

100

Type of Argument Passing cont


Call-by-reference:
When you pass an object to a method.
Java actually passes a reference to the object.
Code in the method can reach the original object.
Any change made to the passed object affect the original object .
class Test{
int a,b;
Test(int i, int j){
a = i;
b = j;
}
void meth(Test o){
o.a = o.a*2;
o.b = o.b/2;
}
}
Test ob = new Test(15,20);
Systeem.out.println( a and b before call: +a+ +b); 15
ob.meth(ob);
Systeem.out.println( a and b after call: +a+ +b); 30

5/7/16

BY: Raju Pal

20
10

101

Returning Objects from Methods


A method can return objects just like other data types.
The object created by a method will continue to exist as long as
there is a reference to it.
No need to worry about an object going out-of-scope because
the method in which it was created terminates.

5/7/16

BY: Raju Pal

102

Returning Objects Example


class Test{
int a;
Test (int i){
a = i;
}
Test incrByTen(){
Test temp = new Test(a+10);
return temp;
}
}
Class RetOb{
public static void main(String args[]){
Test ob1 = new Test(2);
Test ob2;
ob2 = ob1.incrByTen();
System.out.println(ob1.a: +ob1.a);
System.out.println(ob2.a: +ob2.a);
}
}
ob1.a = 2;
ob2.a = 12;

5/7/16

BY: Raju Pal

103

Visibility Modifiers Accessor Methods


Visibility modifiers specify which parts of the program may see
and use any particular class/method/field.
How a member can be accessed is determined by the access
specifier that modifies its declaration.
Java has three visibility modifiers:
protected.

public, private, and

When no access specifier is used , then by default the member


of a class is public within its own package but can not be
accessed outside its package.(default visibility)

5/7/16

BY: Raju Pal

104

Visibility Modifiers - Classes


A class can be defined either with the public modifier or
without a visibility modifier (default visibility).
If a class is declared as public it can be used by any other class
If a class is declared without a visibility modifier it has a default
visibility.
A member is a field, a method or a constructor of the class.
Members of a class can be declared as private, protected,
public or without a visibility modifier (default):
5/7/16

BY: Raju Pal

105

Public Visibility
Members that are declared as public can be accessed from any
class that can access the class of the member
We expose methods that are part of the interface of the class by
declaring them as public
We do not want to reveal the internal representation of the
objects data. So we usually do not declare its state variables as
public (encapsulation)

5/7/16

BY: Raju Pal

106

Private Visibility
A class member that is declared as private, can be accessed only
by code that is within the class of this member.
We hide the internal implementation of the class by declaring its
state variables and auxiliary methods as private.
Data hiding is essential for encapsulation.

5/7/16

BY: Raju Pal

107

class Data
{
public int []
a={0,0,0,0,0,0,0};
}
class app
{
public static void main(String
args[])
{
Data d= new Data();
for(int i=0;i<d.a.length;i+
+)
System.out.println(d.a[i]);
}
}

5/7/16

class Data
{public int [] a={1,0,0,0,0,0,0};}
class app
{
void print(Data obj)
{System.out.println(obj.a[0]);

public static void main(String args[])


{
Data d= new Data();
app b=new app();
b.print(d);
for(int i=0;i<d.a.length;i++)
System.out.println(d.a[i]);
}
}

BY: Raju Pal

108

class Test {
class AccessTest {
int a; // default access
public int b; // public access public static void main(String args[]) {
private int c; // private accessTest ob = new Test();
// These are OK, a and b may be accessed
// methods to access c
directly
void setc(int i)
ob.a = 10;
{ // set c's value
ob.b = 20;
c = i;
// This is not OK and will cause an error
}
// ob.c = 100; // Error!
int getc() { // get c's value // You must access c through its methods
ob.setc(100); // OK
return c;
System.out.println("a, b, and c: " + ob.a + "
}
"+
}
ob.b + " " + ob.getc());
}
}

5/7/16

BY: Raju Pal

109

The static Keyword


Create a member that can be used by itself, without reference to
a specific instance or object.
A static member can be accessed before any objects of its class
are created.
You can declare both methods and variables to be static.
These variables are, essentially, global variables.
No copy of a static variable is made when objects of its class
are declared.
All instances of the class share the same static variables.
5/7/16

BY: Raju Pal

110

static Methods
Methods declared as static have several restrictions:
They can only call other static methods.
They must only access static data.
They cannot refer to this or super in any way.
final Keyword
A variable can be declared as final.
contents of the variable cannot can not be modified.
Must initialize a final variable when it is declared.
Final int a=10;
Final flaot = 10.45f

5/7/16

BY: Raju Pal

111

// Demonstrate static variables, methods, and


blocks.
class UseStatic
{
static int a = 3;
static int b;
Output:
static void meth(int x)
Static block
{
initialized.
System.out.println("x = " + x);
x = 42
System.out.println("a = " + a);
a=3
System.out.println("b = " + b);
b = 12
}
static
{
System.out.println("Static block initialized.");
b = a * 4;
}
public static void main(String args[]) {
meth(42);
}
BY: Raju Pal
} 5/7/16

112

class StaticDemo {
static int a = 42;
static int b = 99;
static void callme()
{
System.out.println("a = " + a);
}

Output:
a = 42
b = 99

class StaticByName {
public static void main(String args[])
{
StaticDemo.callme();
System.out.println("b = " +
StaticDemo.b);
}
}

5/7/16

BY: Raju Pal

113

Exploring the String


Class
every string you create is actually an object of type
String. Even string constants are actually String
objects.
System.out.println("This is a String, too");
the string This is a String, too is a String constant.
objects of type String are immutable; once a String
object is created, its contents cannot be altered
If you need to change a string, you can always create a
new one that contains the modifications.
Java defines a peer class of String, called
StringBuffer, which allows strings to be altered, so all
of the normal string manipulations are still available in
Java.
5/7/16

BY: Raju Pal

114

// Demonstrating Strings.
class StringDemo {
public static void main(String args[])
{
String strOb1 = "First String";
String strOb2 = "Second String";
String strOb3 = strOb1 + " and " +
strOb2;
System.out.println(strOb1);
System.out.println(strOb2);
System.out.println(strOb3);
}
}

5/7/16

Methods of String Class


Javap java.lang.String
boolean equals(String
object)
int length( )
char charAt(int index)

BY: Raju Pal

115

// Demonstrate String arrays.


class StringDemo3 {
public static void main(String args[])
{
String str[] = { "one", "two", "three" };
for(int i=0; i<str.length; i++)
System.out.println("str[" + i + "]: " +
str[i]);
}
}

5/7/16

BY: Raju Pal

116

Using Command-Line
Arguments
// Display all command-line
arguments.
class CommandLine {
public static void main(String args[])
{
for(int i=0; i<args.length; i++)
System.out.println("args[" + i + "]: "
+args[i]);
}
} CommandLine this is a test 100 -1
java
args[0]:
args[1]:
args[2]:
args[3]:
args[4]:
args[5]:
5/7/16

this
is
a
test
100
-1

BY: Raju Pal

117

Taking Input from User


import java.io.*;
class StringDemo
{
public static void main(String args[]) throws IOException
{
System.out.println("Enter");
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
String A= br.readLine();
int a=Integer.parseInt(br.readLine());
char c=(char)br.read();
System.out.println(a);
System.out.println(A);
}
}
5/7/16

BY: Raju Pal

118

5/7/16

BY: Raju Pal

119

Potrebbero piacerti anche