1

B. Sc Computer Science

Subject : Internet and Java Programming

Unit : II

Semester : 6

Unit – II - OBJECT ORIENTED FUNDAMENTALS AND JAVA REVOLUTION

Object oriented programming – Encapsulation – Inheritance – Polymorphism – Java Genesis – Characteristics – Java Programming techniques – Reserved words – Identifiers – Literals – Operators – Separators – Variables – Types – Arrays – Operator Precedence

OBJECT ORIENTED PROGRAMMING.

Object Oriented Programming is a method of implementation in which programs are organized as a collection of objects each of which represents an instance of some class.

TWO PARADIGMS OF OBJECT ORIENTED PROGRAMMING

All programs consists of two elements code and data. A program can be conceptually organized around its code or around the data. The process – oriented approach or model characterizes a program as a series of linear steps . This approach can be thought of as code acting on data. Procedural languages like C employ this model to considerable success. Problems with model appear as programs grow larger and complex. To manage the increasing complexity the second approach called object – oriented programming was conceived. Object oriented programming organizes a program around its data and a set of well defined interfaces to that data. An object oriented program can be characterized as data controlling access to code.

ABSTRACTION

Humans manage complexity through abstraction. For ex, people do not think of a car as a set of individual parts. They think of it as a well defined object. This abstraction allows people to drive a car without being overwhelmed by its complexity. They can ignore the details of how the engine, braking systems work.

A powerful way to manage abstraction is through the use of hierarchical classifications. The data from a traditional process- oriented program can be transformed by abstraction into its components. A sequence of process steps can become a collection of messages between these objects. Each of these objects describes its own behavior. These objects are treated as concrete entities that respond to messages telling them to do something. This is the essence of object-oriented programming.

OOP PRINCIPLES

ENCAPSULATION

It is the process of localizing data definition, i.e. of binding together (wrapping) code and data specifically related to a single entity to form a logical unit called a class. This mechanism keeps the data safe from outside interference and misuse. Encapsulation is a protective wrapper that prevents the code and data from being arbitrarily accessed by other code defined outside the wrapper.

The basis of encapsulation is the ‘class’. Object is an instance of a class. Class is a logical construct and object is a physical reality. The code and data within a class are called as members of the class. The data are referred to as the instance variables or member variables. The code that access or operate the data are referred to as member methods or methods. Each method in a class may be marked as private or public. The public interface of a class represents everything that a external user can know. The private methods and data can only be accessed by code that is a member of the class. So any other code that is not a member of a class cannot access a private method or variable.

INHERITANCE

Inheritance is the ability of a class to acquire the characteristics and behavior i.e. nothing but the properties another class. The most common method of using inheritance is to create class hierarchies that move from the most general concept to the most specific representation. The class that inherits the properties from other is called the derived class or subclass and the one from which it is derived is called the base class or the super class. Each subclass has an “is a relationship” to its super class.

Transportation

PublicTransport Private Transport

Bus Plane Train Automobile Motorcycle

Yamaha Honda

In the above example, Yamaha is a bike. A bike is a private transport. A private transport ‘is a ‘ form of transportation.

POLYMORPHISM

Polymorphism is a feature that allows one interface to be used for a general class of actions. Ie a concrete operation inherits its definition and properties from a generic operation. It allows a method to have multiple implementations that are selected based on the type of the object that is passed to the method invocation. i.e. one interface multiple methods.

Consider a stack. You might have a program that requires three types of stacks. One stack is used for integers, one for floating point values, and one for characters. The algorithm that implements each stack is the same, even though the data being stored differs. In a procedural language, you have to create three different sets of stack routines, with each set using different name. With polymorphism, you can specify a general set of stack routines that all share the same names.

JAVA GENESIS

Java is related to C++. Much of the character of Java is inherited from c, and c++. Java derives its syntax from c and many of its object-oriented features from c++. Java was influenced by C++ and not an enhanced version of C++. Java was conceived by James Gosling, Patrick Noughton, Chris Wrath, Ed Frank and Mike Sheridan at Sun Microsystems in 1991. It took 18 months to develop the first working version. The language was initially called Oak but was renamed Java in 1995. The primary motivation was the need for a platform-independent language that could be used to create software to be embedded in various consumer electronic devices, such as microwave ovens and remote controls.

A Java compiler converts the Java source code into a binary program consisting of byte codes. Byte codes are optimized set of instructions designed to be executed by the Java run-time system, which is called the Java Virtual Machine (JVM). JVM is an interpreted for byte code. This interpreter inspects and deciphers the byte codes and executes the actions that the byte codes specify. A Java interpreter can run stand-alone or it can be a part of a web browser such as Netscape Navigator or IE where it can be invoked automatically to run applets in a web page.

Translating a Java program into byte code makes it easier to run a program in a wide variety of environments. Only JVM needs to be implemented for each platform. Although the details of JVM differ from platform to platform, all interpret the same Java byte code. If a Java program were compiled to native code, then different versions of the same program would have to exist for each type of CPU connected to the Internet.

When a program is interpreted, it generally runs substantially slower than it would run if compiled to executable code. However with Java, the difference is not great. The use of byte code enables the Java run-time system to execute program much faster than you might expect.

Sun has just completed its Just In Time (JIT) compiler for byte code, which is included in Java 2. JIT is a part of JVM, it compiles the byte code into executable code in real time. It is not possible to compile a entire Java program into executable code all at once, as Java performs various run-time checks that can be done only at run time. Instead JIT compiles the code as needed only during execution.

JAVA CHARACTERISTICS

Simple – Java removes many c, c++ features that were either redundant, sources of confusion, i.e. no use of pointers, no multiple inheritance, no need to explicitly free memory. This has reduced the complexity and has increased the reliability of the language.

Robust and secure – Java is robust in its many safeguards to ensure reliable code.

  1. There is no Java preprocessor, i.e. the program will execute just as it is written without worry that a variable is #defined to mean something else.
  2. Java has strict compile time and runtime checking for the proper use of the type system.
  3. Free from numerous memory bugs as it is garbage-collected (explicit de-allocation, Garbage collection is a technique that eliminates the need for memory management by periodically reclaiming unused memory)

Security features

The automatic downloading of program across the insecure Internet made security a high priority for the Java Development Team.

  1. The first security feature is that computer memory is not directly accessible by any Java program.
  2. Byte codes are verified for accuracy and tested for security violation
  3. Java’s network package allows the user to set the level of access for each system.

Architecture Neutral

If you run a program today there is no assurance that it will execute tomorrow, on the same machine. Operating system upgrades, processor upgrades and changes in core system resources can all collude to make a program cease to function. The Java designers made several hard decisions in the Java Language and runtime so you can truly write once run anywhere. Write a good program and Java will make sure that it works on Macintosh, UNIX etc.

Multi- threaded

Java was designed to meet the real-world requirement of creating interactive, networked programs. To accomplish this Java supports multithreaded programming which allows you to write programs that do many things simultaneously. Java runtime system supports multi process synchronization which enables you to construct smoothly running interactive systems.

Distributed

Java is designed for the distributed environment of the Internet, because it handles TCP/IP protocols. The original version of Java included features for intra-address-space messaging. This allows objects on two different computers to execute procedures remotely. Java has revived these interfaces in a package called ‘Remote Method Invocation (RMI).

Dynamic

Java programs carry with them substantial amounts of run-time type information that is used to verify and resolve accesses to objects at run-time. This makes it possible to dynamically link code in a safe and expedient manner. This is crucial to the robustness of the applet environment, in which small fragments of byte code may be dynamically updated on a running system.

JAVA PROGRAMMING TECHNIQUES

A simple Java program can be as follows

class Sample{

public static void main(String args[ ]){

System.out.println(“Welcome”);

}

}

The reserved word ‘class’ is used to declare a class.

public - main() must be declared public since it must be accessed by code outside of its class when the program is started

static – the method can be called independent of an instance of a class, i.e. its not necessary to instantiate the class to invoke the method.

void – specifies that the method main() doesn’t return any value

String args[ ] declares a parameter named args, which is an array of instances of the class String. Objects of type String store character strings. args[ ] receives any command line arguments .

RESERVED WORDS

Reserved words are special identifiers, and these keywords can only be used for their intended purpose and cannot be used as an identifier for a variable, class or method name.

The Java reserved words are as follows

abstract boolean break byte byvalue

casecast catch char class

constcontinue default do double

else extends final finally float

for goto if implements import

instanceof int interface long native

new package private protected public

return short static strictfp synchronized

switch this throws transient try

void volatile while

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 dollar sign characters. They must not begin with a number, they should not be confused with a numeric literal. Java is case sensitive so ‘MATRIX’ is a different identifier from ‘matrix’.

Some examples of valid identifiers are

value b5 $sname dt_of_join

Invalid identifiers

8value max-level or/and

SEPARATORS

The most commonly used separator is semicolon. The other separators are

Symbol purpose

() Used to specify the list of parameters in method definition

and invocation

{ } To represent the values of initialized arrays. To define a

block code for classes, methods and local scopes.

[ ] Use to declare array types. Also used when dereferencing

array values.

; semicolon is used to terminate statements

, Comma separates consecutive identifiers in a variable

declaration. Also used to chain statements together inside a

for statement

. Period is used to separate package names from

subpackages and classes. Also used to separate a variable

or method from a reference variable

TYPES

Java defines eight simple types of data : byte, short, int, long, char, float , double and boolean.

These can be put in four groups.

Integers - this group includes byte, short, int and long which are for whole-valued signed numbers

Floating - point numbers : This includes float and double

Characters - this includes char

Boolean - this includes boolean, which is a special type for representing true/false values

Integers

All the four integer types are signed, positive and negative values. Java doesn’t support unsigned, positive-only integers.

The width and the range of the integer types can be specified

Type width Range

long 64-9,233,372,036,854,775,808 to 9,233,372,036,854,775,807

int 32-2,147,483,648 to 2,147,483,647

short 16-32,768 to 32,768

byte 8-128 to 127

byte- This is a signed 8-bit type that has a range from –128 to 127. The variables of type byte are used when you work with a stream of data from a network or file. The variables can be declared as - byte a ;

short - This is a signed 16-bit type that range from -32,768 to 32,768.

int - It is a signed 32 bit type that ranges from -2,147,483,648 to 2,147,483,647

long - long is a signed 64 bit type and is useful when an int type is not large enough to hold the desired value.

Floating –point types

The two kinds of floating point types are float and double which represent single and double precision numbers

type width range

double 64 bits1.7e-308 to 1.7e+308

long 32 bits3.4e-038 to 3.4e+038.

float- specifies single precision values. Single precision is faster on some processors and takes half as much space as double precision. float can be useful when representing dollars and cents

double – It uses 64 bits to store a value. double precision is actually faster than single precision. All mathematic, trigonometric functions such as sqrt(), sin(), cos() return double values. double is the best choice if you need to maintain accuracy.

Characters

The data type used to store characters is char. Java uses Unicode to represent characters. Unicode defines fully international char set that represents characters of all languages, such as Latin, Greek. Arabic etc. It requires 16 bits. The range of char is 0 to 65536. There are no negative chars.

Ex

class Chardemo{

public static void main(String args[ ]){

char ch1, ch2;

ch1 = 88;

ch2 = “Y”;

System.out.println(“ch1 and ch2 : ” + ch1+” “+ch2);

}

}

The output is

ch1 and ch2 : X Y

where 88 is the ASCII value that corresponds to X.

Booleans

boolean is the type used for logical values. It can have any one of the two possible values true or false. This is the type returned by all relational operators such as a > b. boolean is the type required by conditional expressions that govern the control statements such as if or for.

LITERALS

Literals are nothing but constants. A literal represents a value of certain type, whereas the type itself describes how the value behaves and how it is stored.

The various literals are as follows

Integer literals

Any integral numeric value is an integer value. Ex are 5, 7 etc. These are decimal values i.e. of base 10.

The other two bases used in integral literals are octal and hexadecimal. Octal values are denoted in Java with a leading zero. Decimal numbers cannot have leading zero. A hexadecimal constant can be specified with a leading 0x or 0X.

Floating Point literals

Floating Point numbers represent decimal values with a fractional component. They can be expressed in two ways

Standard notation – use some number followed by a decimal point and then some fractional digit.

Ex – 5768.33333333

Scientific notation – a standard notation floating point number with a additional notation that indicates a multiplication times ten to the specified exponent. The exponent is given by a E or e followed by decimal number. Ex – 45.34e12, 348e-01.

Floating point literals in Java default to double precision, you need to append an F or f to force the constant to be small enough to store into a variable declared as a float.

Boolean Literals

The Boolean literals can have two values i.e. true or false.

Character Literals

A literal character is represented inside a pair of Parentheses (‘ ‘). For characters that are impossible to enter directly, there are several escape sequences which allow to enter the character such as (‘\’), for the single quote character itself and ‘\n’ for new line character.

String literals

String literals are arbitrary text enclosed in double quotes. Ex – “name”, “Command”. Java strings must begin and end in the same line. There is no line continuation escape sequence as in other language.

ARRAYS

Array is a collection of values of the same data type referred by a common value.

One-dimensional arrays

The general form of one-dimensional array is

type var-name[ ];

type is the data type of the each element that comprises the array.

Ex –

int marks[ ];

marks is a array variable, no array actually exists. The value of marks is set to null.

A operator “new” is used to allocated space for an array.

marks = new int[6];

marks refers to an array of 6 integers. The individual elements of the array can be accessed starting from the index or subscript 0.

For Ex.

class Student{

public static void main(String args[ ]){

int marks[ ] = new int[6];