Learning JAVA. Understanding Salient features of JAVA. Implementing JAVA PROGRAMS on your own. ...

42
WORKSHOP JAVA

Transcript of Learning JAVA. Understanding Salient features of JAVA. Implementing JAVA PROGRAMS on your own. ...

WORKSHOP

JAVA

Author

OBJECTIVES

Learning JAVA. Understanding Salient features of JAVA. Implementing JAVA PROGRAMS on your

own. Development of JAVA PROJECTS on your

own.

About JAVA language.Program structuresSimple program JVMOOP principles.keywordsData typesOperationsArrays

INDEX

Java History

Computer language innovation and development occurs for two fundamental reasons:1) to adapt to changing environments and uses2) to implement improvements in the art of programming

The development of Java was driven by both in equal measures.

Many Java features are inherited from the earlier languages:

B C C++ Java

C language designed by Dennis Ritchie in 1970s.

C++ designed by Bjarne Stroustrup in 1979.

In 1990, Sun Microsystems started a project called Green.Objective: to develop software for consumer electronics.Project was assigned to James Gosling, a veteran of

classic network software design. Others included Patrick Naughton, ChrisWarth, Ed Frank, and Mike Sheridan.

In 1994, an early web browser called WebRunner was written in Oak. WebRunner was later renamed HotJava.

In 1995, Oak was renamed Java.

Java Buzzwords

Simple Secure Portable Object-oriented Robust Multithreaded Architecture-neutral Interpreted High performance Distributed Dynamic

Structure of CDocument section

Link section

Definition section

Global declaration section

Main(){ declaration part Functional section executable part}

Sub program section function 1 function 2 User defined functions ------------ function n

Structure of JAVADocument section

Package section

Import statements

Class definitions{VariablesMethods}

Main Class{ Main Method Definition}

/*A program to add two numbers*/ package mypack; import java.lang.*; import java. util.*;

class Addition{ int a,b,c;

void sum(int a, int b){c=a+b;System.out.println(“sum is +c”);}

}class Additionop

{public static void main(String args[])

{Addition ad=new Additon();ad.sum(3,5)

}}

JAVA WORLD

class Welcome{ public static void main(String args[]) { System.out.println(“WELCOME TO

JAVA WORLD”); } }

Naming conventions specify the rules to be followed by a Java programmer while writing the names of packages, classes, methods etc.• Package names are written in small letters. ex: java.io, java.lang, java.awt etc• Each word of class name and interface name starts with a capitalex: Sample, AddTwoNumbers•Method names start with small letters then each word start with a capitalex: sum (), sumTwoNumbers (), minValue ()· Variable names also follow the same above method ruleex: sum, count, totalCount· Constants should be written using all capital lettersex: PI, COUNT· Keywords are reserved words and are written in small letters.ex: int, short, float, public, void

Compiling the Program

To compile the program, execute the compiler, javac, specifying the name of the source file on the command line.

C:\>javac Welcome.javaTo actually run the program, you must use

the Java interpreter, called java. To doC:\>java Welcome

When the program is run, the following output is displayed:“WELCOME TO JAVA WORLD”.

Java Virtual Machine(JVM)Java compiler translate source code into

machine code.java compilers produces an intermediate

code known as Byte code for a machine.this machine is called Java Virtual Machine,

and it exists only inside the computer memory.

the virtual machine code is not machine specific, the machine code is generated by Java interpreter.

source code Byte code Process of compilation

virtual machine real machine Process of converting byte code into machine code

Java program

Byte code Java interpreter

Machine code

Java compiler

Virtual machine

OOP Vs POPObject oriented programing Procedural oriented programing

The unit in object-oriented programming is class .

The unit in procedural programming is function.

It is concerned to develop an application based on real time .

POP are more concerned with the processing of procedures and functions.

It providing more security to data . It providing less security to data .

In OOP the Objects communicate with each other via Functions.

There is no communication in POP rather its simply a passing values to the Arguments to the Functions and or procedures.

OOP follows Bottom Up Approach of Program Execution.

POP follows Top Down Approach of Program Execution .

OOP includes Inheritance, Encapsulation and Data Abstraction, Late Binding, Polymorphism, Multithreading, and Message Passing.

POP is simply a programming in a traditional way of calling functions and returning values.

The list of OOL languages :- JAVA, VB.NET, C#.NET

The list of PPL languages :- C, VB, Perl, Basic, FORTRAN.

PRINCIPLESEncapsulation: It is the mechanism

that binds together code and the data it manipulates.

info. in info. out

Data &Method

Inheritance: It is the process by which objects of one class acquire the properties of objects of another class. Bird

attributes

Flying birds Nonflying

birds

RobinSwallo

wPengui

nKiwi

Polymorphism: It means the ability to take more than one form.

Shape Draw()

Circle object Draw(circle)

Box object Draw(box)

Triangle object

Draw(triangle)

CLASS

A class is a blueprint ,that defines the variables and methods common to all objects of a certain kind.

An object holds values for the variables defines in the class.

“Object” is an instance of a class. Each object has a class which defines its data and behavior.

An object is called an instance of the Class

Structure of Class

A class is declared by use of the class keyword. class classname {

type instance-variable1;type instance-variable2;// ...type instance-variableN;

type methodname1(parameter-list) {// body of method

}type methodname2(parameter-list}// ...type methodnameN(parameter-list) {// body of method}

}

The Java Keywordsabstract continue goto package synchroni

zed

assert default if private this

boolean do implements protected throw

break double import public throws

byte else instanceof return transient

case extends int short try

catch final interface static void

char finally long strictfip volatile

class float native super while

const For new switch

Data Types

Java defines eight simple types:1)byte – 8-bit integer type2)short – 16-bit integer type3)int – 32-bit integer type4)long – 64-bit integer type5)float – 32-bit floating-point type6)double – 64-bit floating-point type7)char – symbols in a character set8)boolean – logical values true and false

Variables

Java uses variables to store data.To allocate memory space for a variable JVM

requires:1) to specify the data type of the variable2) to associate an identifier with the variable3) the variable may be assigned an initial value

All done as part of variable declaration.

Variable Declaration

datatype identifier [=value];datatype must be

A simple datatypeUser defined datatype (class type)

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 scope2) variables defined by a method have a local scopeA scope is defined by a block:{…}A variable declared inside the scope is not visible outside:{int n;}n = 1;// this is illegal

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) declared2) created3) initialized4) used

Also, arrays can have one or several dimensions.

Array Declaration

Array declaration involves:1) declaring an array identifier2) declaring the number of dimensions3) declaring the data type of the array

elementsTwo styles of array declaration:

type array-variable[];or

type [] array-variable;

Array CreationAfter 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 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 operator2) the array is created large enough to hold all

specified elements

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.

int[] abc, xyz;

abc = new int[5]; // Instantiate an array of 5 integers

xyz = abc; // xyz and abc refer to the same array

xyz[3] = 100; // Changing xyz changes abc as well.

System.out.println (abc[3]); // 100 is displayed

Multidimensional Arrays

Multidimensional arrays are arrays of arrays:1) declaration: int array[][];2) creation: int array = new int[2][3];3) initialization

int array[][] = { {1, 2, 3}, {4, 5, 6} };

Two-dimensional array

Average an array of values

class Average {public static void main(String args[]) {double nums[] = {10.1, 11.2, 12.3, 13.4, 14.5};double result = 0;int i;for(i=0; i<5; i++)result = result + nums[i];System.out.println("Average is " + result / 5);}}

Two-dimensional arrayclass TwoDArray {public static void main(String args[]) {int twoD[][]= new int[4][5];int i, j, k = 0;for(i=0; i<4; i++)for(j=0; j<5; j++) {twoD[i][j] = k;k++;}for(i=0; i<4; i++) {for(j=0; j<5; j++)System.out.print(twoD[i][j] + " ");System.out.println();}}}

Output

0 1 2 3 45 6 7 8 910 11 12 13 1415 16 17 18 19

Operators Types

Java operators are used to build value expressions.

Java provides a rich set of operators:1) assignment2) arithmetic3) relational4) logical5) bitwise

Arithmetic assignments

+= v += expr; v = v + expr ;

-= v -=expr; v = v - expr ;

*= v *= expr; v = v * expr ;

/= v /= expr; v = v / expr ;

%= v %= expr; v = v % expr ;

Basic Arithmetic Operators

+ op1 + op2 ADD

- op1 - op2 SUBSTRACT

* op1 * op2 MULTIPLY

/ op1 / op2 DIVISION

% op1 % op2 REMAINDER

Relational operator

== Equals to Apply to any type

!= Not equals to Apply to any type

> Greater than Apply to numerical type

< Less than Apply to numerical type

>= Greater than or equal Apply to numerical type

<= Less than or equal Apply to numerical type

Logical operators

& op1 & op2 Logical AND

| op1 | op2 Logical OR

&& op1 && op2 Short-circuit AND

|| op1 || op2 Short-circuit OR

! ! op Logical NOT

^ op1 ^ op2 Logical XOR

Bitwise operators program

class Bits { public static void main(String args[]) { byte x,y; x=10; y=11; System.out.println("~x="+(~x)); -> -11 System.out.println("x&y="+(x&y)); -> 10 System.out.println("x/y="+(x/y)); -> 11 System.out.println("x^y="+(x^y)); -> 1 System.out.println("x<<2="+(x<<2)); -> 40 System.out.println("x>>2="+(x>>2)); -> 22 System.out.println("x>>>2="+(x>>2)); -> 22 }}

presented by U. LOVARAJU Assoc. Professor

IT-Department