IT51 Java Programming Unit 1 Notes

yoinkscreechedInternet και Εφαρμογές Web

13 Νοε 2013 (πριν από 4 χρόνια)

105 εμφανίσεις

IT51 Java Programming Unit 1 Notes


A.Jegatheesan/HOD/IT/CIT

Page
1


Object
-
Oriented Programming Concepts


OOP is a new programming paradigm in which programming problem is divided into a set of
objects.


OOP is widely accepted as being far more flexible than other computer programming
languages
.


OOPs such as Java, J2EE, C++, C#, Visual Basic.NET, Python and JavaScript are popular OOP
programming languages.

Basic oop’s concepts

1.Object

2.Class

3.Data Abstraction

4.Encapsulation

5.Inheritance

6.Polymorphism

7.Dynamic Binding

8.Message Communica
tion

Object:

-

An object can be considered a "
thing
" that can perform a set of
related
activities. The set of
activities that the object performs defines the object's behavior.

-
An object is the basic dynamic entity in an object oriented system.

-
An object

contains both data and methods that manipulate that data


-

An object is
active,

not passive; it
does

things


-

An object is
responsible

for its own data

-

Objects can communicate with each other using messages.

Example: A “Rabbit” object



You could (in a
game, for example) create an object representing a rabbit



It would have data:



How hungry it is



How frightened it is



Where it is



And methods:



eat, hide, run

Classes



Every object belongs to (is an instance of) a class

IT51 Java Programming Unit 1 Notes


A.Jegatheesan/HOD/IT/CIT

Page
2




An object may have fields, or variables




The class describes those fields



An object may have methods



The class describes those methods



A class is like a template which defines the structure of the object.



Class is a user defined data type to create objects. Object is the variable of type class
.



A class is a blueprint or prototype from which objects are created.

Approximate Terminology



instance = object



field = instance variable



method = function



sending a message to an object =


calling a function

Example

class Employee


{


// Data or fields


private String name;


private double salary;



// Methods or Functions


void pay ()


{


System.out.println("Pay to the order of " +name + " $" + salary);


}


public String getName()


{



return name;

IT51 Java Programming Unit 1 Notes


A.Jegatheesan/HOD/IT/CIT

Page
3



}

}



Difference Between Object And Class



A class is how you define an object. Classes are descriptive categories or templates.
Book could be a class.



Objects are unique
instances
of classes. This Java Certification book that costs $59
.99
with item ID 62467
-
B is an
object
of the Book
class.

DATA ABSTRACTION



Abstraction refers to the act of representing essential features without including the
background details.



Both the data and functions can be abstracted in class data type.



Classes
that use the concept of data abstraction are known as “Abstract Data Type
(ADT)” .

Object creation:

classname object name=new classname();

Eg:

student s=new student();

Notation: How to declare and create objects



Employee secretary; // declares secretary



secretary = new Employee (); // allocates space



Employee secretary = new Employee(); // both



But the secretary is still "blank"



secretary.name = "Adele"; // dot notation



secretary.birthday (); // sends a message

Encapsulation

IT51 Java Programming Unit 1 Notes


A.Jegatheesan/HOD/IT/CIT

Page
4




The process of combining
data and functions together into a single entity is called as
Encapsulation.



Encapsulation plays a major role in object oriented system. Because the data and
functions are tied into an object, outside world cannot access the data. This is known as
data hid
ing. ie, protect the data.

INHERITANCE



Reusability



Ability of a new class to be created, from an existing class by extending it, is called
inheritance
.



Base class or Parent class or super class
-
>derived class or child class or sub class.

Eg: grand father

-
> father
-
> son



It avoids the redundancy of code

Example of inheritance

class Person {


String name;


String age;


void birthday () {


age = age + 1;


}

}

class Employee


extends Person {


double salary;


void pay () { ...}

}

Every Employee has a name, age, and birthday method
as well as

a salary and a pay method.

Polymorphism



Polymorphism provides a way to take elements in more than one form.

IT51 Java Programming Unit 1 Notes


A.Jegatheesan/HOD/IT/CIT

Page
5




One thing different meanings.



Function overloading
-

by using polymorphism different
methods can be created with
the same name but different parameters.



It reduces software complexity.

Dynamic Binding



The process of linking function call to the appropriate function definition at run time is
known as Dynamic Binding.



Until the time of execu
tion, function definition associated with the function call is
unknown.



Dynamic binding is related with inheritance and polymorphism.


Message Communication (Methods and Messages)



Objects in object oriented system can communicate with each other using
messages.



Message is passed by calling the methods of the object with information(arguments).



Message passing consists of object name, method name with arguments.

Advantages



Programs can be organized as a collection of objects which can be managed easily.



Data hiding provides security to the data, as unrelated functions cannot access its data.



Data abstraction



Each object is independent, changes in one object will not affect others.



Object oriented systems can be easily extended by adding the additional fea
tures.



Polymorphism



Inheritance

Disadvantages



Additional functionalities make compiler overhead




Extra functionalities make runtime overhead

Fundamentals of JAVA

History

IT51 Java Programming Unit 1 Notes


A.Jegatheesan/HOD/IT/CIT

Page
6


-

Developed by James Gosling, Sun Microsystems, USA.

-

Originally designed (1991) as a small language for consumer electronics (cable boxes,
toasters
etc.
)

-

Initially called Oak.

-

Java, May 20, 1995, Sun World

HotJava

The first Java
-
enabled Web browser

Characteristics of Java

Simple



well, simpler than C++

pure object
-
oriented


-

more so than C++

Distributed



Built in support for Internet protocols, URL’s, HTTP
etc.



Support for distributed objects, RMI, CORBA etc.

Robust



Difficult to create memory leaks, go beyond the end of an array, corrupt stack or
code



Portable

-


program typed on notepad, word, wordpad, etc

-

Secure

-

b
ytecode “verifier”

Architecture Neutral

platform independent language
-

Java available for MAC, Win 98/NT, Win XP,
HP, SUN, SGI, Digital Unix, Linux, Amiga, OS/2, BEOS, VMS, and even AIX

Runs on PC, MAC, Unix, VMS

Interpreted

“Compiler” converts code into machine independent “byte codes”

IT51 Java Programming Unit 1 Notes


A.Jegatheesan/HOD/IT/CIT

Page
7


Hig
h Performance

With JIT compiler still several times slower than native C++

Coming soon! Optimizing interpreter from Sun, faster than C++

Multithreaded

Language has direct support for multithreading (c.f. sub processes)

Dynamic

Libraries can change without
recompiling programs that use them

Compared with C++



everything in java is an object.




no pointers




no operator overloading




no templates




no destructor




no delete operator




no typedef, sizeof




no preprocessor




no structures , union and enum




no header f
iles




no auto, extern, register, signed, unsigned variables




does not support multiple inheritance



does not support global variables

What is Java Good For?

Web Applets

Database programming



SQL databases using JDBC



Object databases using ODMG binding

IT51 Java Programming Unit 1 Notes


A.Jegatheesan/HOD/IT/CIT

Page
8


Java Servlets

Stand Alone Applications



GUI based applications

Distributed client
-
server applications



Using TCPIP + RMI + CORBA

Graphics applications



2D and 3D

Physics Analysis

How does Java work?

Java source code is compiled into machine independent “byte
codes”

The bytecodes can be run directly by an interpreter

The bytecodes can be converted to machine code and executed (“Just in Time (JIT)”
compilation).

An optimizing interpreter can dynamically identify program “hotspots” and create code
optimized for
the specific machine/environment.

IT51 Java Programming Unit 1 Notes


A.Jegatheesan/HOD/IT/CIT

Page
9




Compiling/running first java program

Compiling/running first java program

Create source code file (call it for example MyFirstProgram.java).

To compile:

prompt >> javac MyFirstProgram.java

This produces byte code file
named


MyFirstProgram.class

To run:


prompt >> java MyFirstProgram

o
bservations

class file is
not

machine code. It is intermediate form called Java Byte code.
Can run on any platform as long as platform has a Java Virtual Machine (JVM).

The second
step on previous slide invokes the JVM to interpret the byte code on the
given platform.

IT51 Java Programming Unit 1 Notes


A.Jegatheesan/HOD/IT/CIT

Page
10


In theory, byte code can be moved to another platform and be run there without
recompiling


this is the magic of applets.

Leave off the .class part when invoking the
JVM.

Writing first program

In java, the file in which your program resides must contain a .java extension (e.g.
MyFirstProgram.java).

Then, the program must be wrapped in a class definition which is the same as the file
basename (MyFirstProgram). Careful,
Java is case
-
sensitive.


class MyFirstProgram { … }

Finally, main is defined similar to C, but with a few more modifiers:


public static void main(String[] args){ … }

These are all
required
. No shortcuts.

Just as in C, main(..) is the principle entry po
int into the program. When you say


java Program


Java looks in Program for a procedure named main. This is where the program starts.

To print to stdout in java use:


System.out.println(“ …”);

Example

class MyFirstProgram

{


public static void
main(String arg[])


{



System.out.println(“Welcome”);


}

}

public
: this keyword is an access specifier, which allows the programmer to control the
visibility of class members. ie, member may be accessed by code outside the class in
which it is declared.

IT51 Java Programming Unit 1 Notes


A.Jegatheesan/HOD/IT/CIT

Page
11


m
ain(
): this is the starting point for interpreter to begin the execution of the program. A
java application can have any number of classes. But only one of the main() must be
included. It must be declared as public, since it must be called by code outside

of its
class when the program is started.

static
: this keyword allows main() to be called without having to instantiate a particular
instance of the class

void
: the type modifier void states that the main() method does not return any value.

String arg[]:

which is an array of instance of the class String. Object of type String store
character strings. arg[] receives any command line arguments present when the
program is executed.

system:

is a predefined class that provides access to the system.

out:

is the
output stream that is connected to the console.

println
: is similar to the printf or cout statements

The println method is a member of the out object, which is a data member of System
class.

Data Types

Primitive Data Types:

Integer types



int (4 bytes
signed)


32 bits (
-
2147483648 to + 2147483647)



short (2 bytes signed)


16 bits (
-
32768 to +32767)



long (8 bytes signed) use suffix L (eg 1000000000L)


64 bits



(
-
9223372036854775808 to + 9223372036854775808)



byte (1 byte signed)


8bits (
-
128 to 127)

Floating
-
point types



float (4 bytes) use suffix F (eg 1.28F)


32 bits








(3.4e
-
038 to 3.4e+038)



Double (8 bytes)


64 bits (1.7e
-
308 to 1.7e+308)

char



Two
-
byte unicode (0 to 65536) international character set. No negative
characters

IT51 Java Programming Unit 1 Notes


A.Jegatheesan/HOD/IT/CIT

Page
12





it is a unification of dozens of character sets such as latin, greek, arabic and
many more. For this purpose, it requires 16 bits.



The ASCII character set occupies the first 127 values in the unicode character set.



Assignment with ‘ ‘



e.g. char c = ‘h’;

Boolean (
not an int!)


-

true or false

e.g. boolean x = true;

No automatic conversion

You can force conversions with a cast


same syntax as C/C++.

int i = (int) 1.345;

Java Tokens

5 types



Keywords (same as c++)


eg: int, this, if, try, etc.

Additionally
,

super, package, interface, extends, import, implements



Identifiers
-

variables



Constants


integer, float, char(‘a’), string(“hai”)



Operators

Arithmetic



+,
-
,*,/,%

Relational



==,!=,>,<,>=,<=

logical



&&,||,!



assignment




=, +=,
-
=

IT51 Java Programming Unit 1 Notes


A.Jegatheesan/HOD/IT/CIT

Page
13





increment/decrement




--

, ++




conditional



-

? !



Bitwise


-

&, | , ^ , ~ , << , >> , >>> (right shift with zero fill)




separators

( ), [ ] , {}, ; , ‘, .

Statements

conditional: if, if else, switch

loop: while, for, do , goto, break, continue

Enhanced for loop:



For loop
is enhanced to work on arrays or collections by retrieving each element
one by one.


for(typevariable:identifier)


{


statements;


}

Example

class fortest

{


int a[]={10,20,30,40,50,70};


int sum=0;


void cal()


{



for(int i:a)



{

IT51 Java Programming Unit 1 Notes


A.Jegatheesan/HOD/IT/CIT

Page
14





sum=sum+i
;



}



System.out.println("sum = "+sum);


}


}

class test

{


public static void main(String arg[])


{



fortest f=new fortest();



f.cal();



}

}

Input

statements

2 ways

-

command line arguments

-


run time input

Command

line arguments

Give the input value at

the run time in command line.

Eg:


javac test.java



java test 10

Example

class input

{


int r;


double area;

IT51 Java Programming Unit 1 Notes


A.Jegatheesan/HOD/IT/CIT

Page
15



void get(int x)


{



r=x;


}


void cal()


{



area=3.14*r*r;


}



void display()


{



System.out.println("Area of circle = "+area);


}

}

class test

{


public static void main(String arg[])


{



int x;



input in=new input();



x=Integer.parseInt(arg[0]);



in.get(x);



in.cal();



in.display();


}

}


IT51 Java Programming Unit 1 Notes


A.Jegatheesan/HOD/IT/CIT

Page
16


Conversion

string to integer




Integer.parseInt()

String to float


-

Float.valueOf().floatValue()

String to double


-

Double.valueOf().doubleValue()

String to long


-

Integer.valueOf().langValue()

String to Character

C=(char)System.in .read()

Runtime Input

2 ways

-

import java.io.*;

-

BufferedReader

Syntax:


BufferedReader b
r=new BufferedReader(new InputStreamReader (System.in));

Example:

import java.io.*;

class input

{


double r;


double area;


void get(double x)


{



r=x;


}


void cal()


{



area=3.14*r*r;

IT51 Java Programming Unit 1 Notes


A.Jegatheesan/HOD/IT/CIT

Page
17



}


void display()


{



System.out.println("Area of circle =
"+area);


}

}

class test1

{


public static void main(String arg[])throws IOException


{



double x;



input in=new input();



System.out.println("Enter the radius value");

BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));



x=Double.v
alueOf(br.readLine()).doubleValue();



in.get(x);



in.cal();



in.display();


}

}


-

DataInputStream

Syntax:



DataInputStream ds=new DataInputStream(System.in);

Access :




ds.readLine()

Example:

java.io.*;

class input

{


double r;


double area;


void
get(double x)


{



r=x;


}


void cal()


{

IT51 Java Programming Unit 1 Notes


A.Jegatheesan/HOD/IT/CIT

Page
18




area=3.14*r*r;


}


void display()


{



System.out.println("Area of circle = "+area);


}

}

class test2

{


public static void main(String arg[])throws IOException


{



double x;



input in=new input();



System.out
.println("Enter the radius value");



DataInputStream ds=new DataInputStream(System.in);



x=Double.valueOf(ds.readLine()).doubleValue();



in.get(x);



in.cal();



in.display();


}

}


Java

Write Once, Run Anywhere

Java Virtual Machine (JVM): Interprets
bytecodes at runtime

Total Platform Independence

IT51 Java Programming Unit 1 Notes


A.Jegatheesan/HOD/IT/CIT

Page
19



Java bytecode and interpreter



byte code is an intermediate representation of the program (class).



The Java interpreter starts up a new “Virtual Machine”.



The VM starts executing the users class by running
it’s
main()

method.


Classes and Objects



Java is a pure object oriented language. So everything must be inside the class.



The attributes and methods of a class are defined inside a class body.



All Java statements appear within methods, and all methods are
defined within
classes



Java classes are very similar to C++ classes (same concepts).



Class name must match the file name!

-

compiler/interpreter use class names to figure out what file name is

Objects



Objects represent instances of classes



Java uses the keyword
new

for creation of new objects.

Object creation:

classname object name=new classname();

Eg:

IT51 Java Programming Unit 1 Notes


A.Jegatheesan/HOD/IT/CIT

Page
20


student s=new student();


Using objects

Just like C++:



object.method()



object.data

BUT, never like this (no pointers!)



object
-
>method()



obj
ect
-
>data

Access Specifiers

Private




data and methods that are to be protected highly are declared with private
specifier.



Private members are accessible only within its own class.

Protected



data and methods that are to be accessed only within its own c
lass and
subclasses are declared with protected specifier



Protected members are accessible only to all the classes and subclasses in its
own package and subclasses in the other packages. Sub classes in other packages
cannot access protected members.

Defa
ult



Data and methods that are to be accessed only within all the classes and sub
classes in the current package are declared with default specifier.




default members are not accessible to other packages.

Public




public members are accessible to its own package and other packages.

Methods



In Java all functions are contained within classes

IT51 Java Programming Unit 1 Notes


A.Jegatheesan/HOD/IT/CIT

Page
21




For largely historical reasons functions are often called methods or
member functions.



In java, polymorphism represen
ts in 3 ways.


Method overloading


Inheritance


Interface

Method overloading

Methods defined multiple times, each definition having the same name but accepting
different parameters, either in n
umber of parameters (or) types. The compiler knows
which method to call based on the parameter it is passed.

Example:

class over

{




void test()


{



System.out.println("No parameters ");


}


void test(int a)


{



System.out.println("int a is "+a);


}


void test(int a,int b)


{



System.out.println("int a and b is "+a+" "+b);


}


void test(int i,char j,float k)


{

IT51 Java Programming Unit 1 Notes


A.Jegatheesan/HOD/IT/CIT

Page
22




System.out.println("int i , char j and float k are "+i+" "+j+" " +k);


}


double test(double x)


{



System.out.println("double x is "+x);



return x*x;


}

}

class overload

{


public static void main(String ar[])


{



over t=new over();



t.test();



t.test(10);



t.test(20,30);



t.test(12,'J',25.5f);



double res=t.test(5.5);



System.out.println("result : "+res);


}

}


Constructor

A
constructor is a special member function of a class that determine how an object is
initialized and created.

It has the same name as the class itself, it has no return type and is invoked used new
operator.

IT51 Java Programming Unit 1 Notes


A.Jegatheesan/HOD/IT/CIT

Page
23


Types of Constructor

Default constructor



No param
eter

Argument constructor



Using parameters

Example:

class box

{


double width,height,depth;


box(double w,double h,double d)


{



width=w;



height=h;



depth=d;


}


box()


{



width=
-
1;



height=1;



depth=
-
1;


}


box(double length)


{



width=height=depth=length;


}


double volume()

IT51 Java Programming Unit 1 Notes


A.Jegatheesan/HOD/IT/CIT

Page
24



{



return width*height*depth;


}

}


class boxover


{


public static void main(String ar[])


{



box b1=new box();



box b2=new box(7.5);



box b3=new box(10.5,20.5,30.4);



double res1=b1.volume();



System.out.println("result1 : "+res1);



double res2=b2.volume();



System.out.println("result2 : "+res2);



double res3=b3.volume();



System.out.println("result3 : "+res3);


}

}

Copy constructor




is a constructor that replicates (or) duplicates an
existing object. So it is called
the copy constructor. It takes a parameters is a reference to an object of the
same class to which the constructor depend.

Example:


class copy

{


int a,b;

IT51 Java Programming Unit 1 Notes


A.Jegatheesan/HOD/IT/CIT

Page
25



copy(int a1,int b1)


{



a=a1;



b=b1;


}


copy(copy c)


{



a=c.
a;



b=c.b;


}


void view()


{



System.out.println("a = "+a+" "+"b = "+b);


}

}

class copytest

{


public static void main(String s[])


{



copy c=new copy(10,15);



System.out.println("arg constructor");



c.view();



copy c1=new copy(c);



System.out.println("copy constructor");



c1.view();


}

IT51 Java Programming Unit 1 Notes


A.Jegatheesan/HOD/IT/CIT

Page
26


}

Static member

Java has 3 types of variables.



Local variable


inside the method



Instance variable (object variable)



Class variable (static variable)

Instance variable (object variable)

It is used
for particular classes needed by multiple methods in the object.

Eg:

class test

{


int a=10;


public static void main(String ar[])


{




System.out.println(a);


}

}

The above program will not compile and give error message variable a may not have
initializ
ed to, avoid the error simply change

static int a=10;

It makes the variable with default value.

The another way is create an instance of the class and then access the
variable.

class insttest

{


int a=60;


public static void main(String ar[])

IT51 Java Programming Unit 1 Notes


A.Jegatheesan/HOD/IT/CIT

Page
27



{




instte
st t=new insttest();



System.out.println(t.a);


}

}

Static Variable



When we want that a class member should be used independently of any object of
that class, we have to precede that member's declaration with the keyword
static
.

When a member is
declared as static, it can be accessed without creating an object
of the class and without referring to the object. That static is , a static member
belong to a class as a whole and not to any one instance/object of that class.




When a variable is declared

with the static keyword, its called a “class variable”.
All instances share the same copy of the variable. A class variable can be
accessed directly with the class, without the need to create a instance.




Without the “static” keyword, it's called “instanc
e variable”, and each instance of
the class has its own copy of the variable.

class test

{


static int a=10;


public static void main(String ar[])


{




System.out.println(a);


}

}

Static Method

When a method is declared static, it can be called/used with
out having to create a
object .

Eg1:


class test

IT51 Java Programming Unit 1 Notes


A.Jegatheesan/HOD/IT/CIT

Page
28


{



static int triple (int n)



{




return 3*n;



}

}

class t1

{



public static void main(String[] arg)


{ // calling static methods without creating a instance

System.out.println( test.triple(4) );


}

}

Methods declared with static cannot access variables declared without static.

a static method can't access instance variables, it can access static variables. A common
use of static variables is to define "constants".

Eg2:


class test


{



static
int x = 3;



static int returnIt ()



{





return x;



}


}

class t1

{


public static void main(String[] arg)

IT51 Java Programming Unit 1 Notes


A.Jegatheesan/HOD/IT/CIT

Page
29



{




System.out.println(test.returnIt());



}

}

Abstract method

Abstract modifier means that the class can be used as a superclass only.



no objects of this class can be created.

Objects Cleanup/Destructor

Unlike c and c++, memory deallocation is automatic in java, don’t worry about it



no dangling pointers and no memory leak problem.

Java allows you to define
finalizer

method, which is
invoked

(if defined) just before the
object destruction.

In way, this presents an opportunity to perform record
-
maintenance operation or
cleanup any special allocations made by the user.

finalize() method



Called as final step when Object is no longer used
, just before garbage collection



Object version does nothing



Since java has automatic garbage collection, finalize() does not need to be
overridden reclaim memory.

Example:

class input

{


double r;


double area;


void get(double x)


{



r=x;


}


void cal()


{



area=3.14*r*r;


}

IT51 Java Programming Unit 1 Notes


A.Jegatheesan/HOD/IT/CIT

Page
30



void display()


{



System.out.println("Area of circle = "+area);


}


public void finalize()


{



System.out.println("");


}

}

class testfinalize

{


public static void main(String arg[])


{



double x;



input in=new input();



x=D
ouble.valueOf(arg[0]).doubleValue();



in.get(x);



in.cal();



in.display();


}

}


Instance or member variable hiding (this keyword)



In java, it is illegal to declare two local variable with the same name inside a
class.



But we can have local variable
name has the same as an instance variable name,
the local variable hides the instance variable.



“this” keyword can be used to indicate the current object.

Example:

class test

{


int red,green,blue,res;


void RGBcolor(int red,int blue,int green)


{



this.r
ed=red;



this.blue=blue;



this.green=green;

IT51 Java Programming Unit 1 Notes


A.Jegatheesan/HOD/IT/CIT

Page
31



}


void result()


{



res=red*green*blue;



System.out.println("RGB Color = "+res);


}

}

class thistest

{


public static void main(String a[])


{



test t=new test();



t.RGBcolor(100,100,2);



t.result();


}

}