Introduction to java by priti sajja

Post on 28-Nov-2014

955 Views

Category:

Technology

0 Downloads

Preview:

Click to see full reader

DESCRIPTION

java programming history and fundamentals

Transcript

1 pritisajja.info

Unlocking the World of Java Programming…..

Priti Srinivas SajjaJune, 2011

Visit pritisajja.info for detail

Introduction to Java Programming

A n introduction and history as specified in Unit 1, MCA 302:Object Oriented

Programming Using Java, S P University.

2 pritisajja.info

Unit 1: Course Content

• The Java programming language: history, evolution• Introduction to the Java programming environment

– source programs organization, – compilation to byte code, – loading by the class loader, – interpretation by the Java Virtual Machine, – just-in-time compilation using HotSpot technology, tools

3 pritisajja.info

Unit 1: Course Content

• Key features of the Java platform: – platform independence at source and byte code level, – use of UNICODE character set, – extensive use of reference types, – automatic garbage collection, generics, – assertions, collections and iterating over collections, – event-driven programming for the GUI, – security, – out of box multithreading and networking, – dynamic loading and linking of classes, – interfaces, designed with the Internet in mind

• Packages, jar files, CLASSPATH, javadoc• Different technologies under the Java umbrella• The Java Development Kit, the Java Runtime Environment and

IDEs

4 pritisajja.info

Unit 2: Java Programming - I

• Using the command line tools v/s an IDE, features of the IDE• Syntax of the Java programming language• An anatomy of a Java program• Data types: primitive v/s reference types, wrapper classes,

automatic boxing and unboxing• Interfaces, inheritance and polymorphism• Exception handling• Arrays• Generics, assertions, enumerations• The Java standard API• String handling• Java tools

5 pritisajja.info

Reference Book

• Schildt H. : The Complete Reference Java 2, 5th Edition, McGraw-Hill / Osborne, 2002

6 pritisajja.info

What is Java?

• Java is object-oriented with built in Application Programming Interface (API)

• It has borrowed its syntax from C/C++• Java does not have pointers directly. • Applications and applets are available.

7 pritisajja.info

Ideal Programming Language for Internet -- the objective was to share data and documents across WWW invented in 1989.

To share interactive executable programs on WWW -- in 1990 Sun Micro system has started project called Green using C++ for consumer electronic. The

team developed new programming language called ‘OAK’ .

OAK avoids dangerous things such as -- pointers and operator overloading. Also they have added architecture neutrality and automatic memory management. The first web

browser called ‘WebRunner’ was developed using OAK. Afterword it is named as HotJava

OAK was renamed as java in 1995 --A common story is that the name Java relates to the place from where the development team got its coffee.

8 pritisajja.info

Platform independence of Java

• Java is both compiled and interpreted.• Source code is compiled to bytecode.• The Java Virtual Machine (JVM) loads and

links parts of the code dynamically at run time.

• Hence it carries substantial run time type information on objects and supports late binding.

9 pritisajja.info

Platform independence of Java

Java instruction

code …

Byte Code …

compiler

Java virtual Machine• it has an instruction

set• it manipulates

various memory areas at run time.

Byte code• Byte codes are the machine

language of the Java virtual machine.

• When a JVM loads a class file, it gets one stream of byte codes for each method in the class.

• The byte codes streams are stored in the method area of the JVM.

• The byte codes for a method are executed when that method is invoked during the course of running the program.

• They can be executed by interpretation, just-in-time compiling, or any other technique that was chosen by the designer of a particular JVM.

Host system …

10 pritisajja.info

Features of Java:

•To follow

Simple

•Remote applets are not trusted and not allowed to use local resources

Secure

•Supports advantages of OOA

Object-oriented

•Independent form hardware and software platforms

Platform independent and Architecture Neural

•It is complied also and interpreted also.

Interpreted

•Java is strong, replacing pointer by reference and provides automatic memory management

Robust

•Supports concurrent procedures

Multi threaded

•Supports dynamic binding and links parts of code at the time of execution.

Distributed and Dynamic

•Java provides native language support

High performance

11 pritisajja.info

JDK : Java Development Kit

• The JDK is the Java Development Kit.

• Major versions are 1.1 (Java 1) and 1.2 (Java 2). (Version 1.3 has just been released.)

• This can be downloaded free of cost from http://java.sun.com

• The JDK can be downloaded for different platforms: Windows, Unix (Solaris), MacOS.

• Comes as a self-extracting exe for Win95+, which extracts to c:\jdk1.2 directory.

• Certain environment variables, such as PATH and CLASSPATH need to be set/reset.

• Path must be set to include c:\jdk1.2\bin

12 pritisajja.info

Java Utilities

• Javac – The java compiler, that converts source code into byte

code stored in class files.

• Java– The java interpreter that executes byte code for a java

application from class files.

13 pritisajja.info

Using the JDK: Hello World Application

Step 1: Write java code

/**The HelloWorld class implements an application that

simply displays “Hello World!” to the standard output (console)

*/

public class HelloWorld

{

public static void main (String args[])

{

//required prototype for main function

System.out.println(“Hello world!”);

} // end of main …………………………………………..

}// end of class ………………………………………………...

14 pritisajja.info

Using the JDK: Hello World Application

Step 2: Save the source in a file

• The file MUST have the same name as the public class in the source, and must have a .java extension. That is, the above file should be saved as

HelloWorld.java

with the case maintained.

• A java source file cannot contain more than one public class according to the above restriction.

How many main methods can be there in a java program?

15 pritisajja.info

Using the JDK: Hello World Application

Step 3: Compile the source file using javac

• Use the following command line at the shell prompt

javac HelloWorld.java

• If the code is correct, compilation will produce the file HelloWorld.class

• If there are errors, repeat steps 1-3.

what javac does behind the scenes, use the following

command line javac -verbose HelloWorld.java.

16 pritisajja.info

Using the JDK: Hello World Application

Step 4: Run the compiled code.

• Invoke the java interpreter by the command line

java HelloWorld

• Output: Hello World!

17 pritisajja.info

Naming Conventions

• Java distinguishes between UPPER and lower case variables.

• The convention is to capitalize the first letter of a class name.

• If the class name consists of several words, they are run together with successive words capitalized within the name (instead of using underscores to separate the names).

• The name of the constructor is the same as the name of the class.

• All keywords (words that are part of the language and cannot

be redefined) are written in lower case.

18 pritisajja.info

Prototype of the main method

public static void main (String args[])

For the main method• public is the access specifier.• static is the storage class.• void is the return type.• String args[ ] is an array of strings

Check public static void main( ) ? Will it cause any error? If yes, what?

19 pritisajja.info

About main method…• Several main methods can be defined in a java class.

• The interpreter will look for a main method with the prescribed signature as the entry point.

• A method named main, which has some other signature is of

no particular significance. It is like any other method• in the class.• Therefore, if the main method is not declared correctly, the

application will not execute. There may not be any compilation problem.

• This class will compile correctly, but will not execute. The interpreter will say

In class NoMain: void main (String argv[]) is not defined

20 pritisajja.info

public class TwoMains

{/** This class has two main methods with * different signatures */

public static void main (String args[])

{

//required prototype for main method

System.out.println(“Hello world!”);

int i;

i = main(2);

System.out.println (“i = ” + i );

}

/**This is the additional main method*/

public static int main(int i)

{ return i*i; }

} // end of class

Try this….

Output will be….Hello World!i = 4PSS

21 pritisajja.info

Is it true?

• The argument to the mandatory main function

public static void main (String args[])

which is String args []

can also be written as

String [] args

22 pritisajja.info

Comments

There are three types of comments defined by Java.

1. Single-line comment :Java single line comment

starts from // and ends till the end of that line.

2. Multiline comment: Java multiline comment is

between /* and */. 3. Documentation comment : Documentation comment

is used to produce an HTML file that documents your program. The documentation comment begins with

a /** and ends with a */.

23 pritisajja.info

Identifiers

• Identifiers are used for class names, method names, and variable names.

• An identifier may be any sequence of uppercase and lowercase letters, numbers, or the underscore and dollar-sign characters.

• Identifiers must not begin with a number.

• Java Identifiers are case-sensitive.• Some valid identifiers are ATEST, count, i1, $Atest, and

this_is_a_test

• Some invalid identifiers are 2count, h-l, and a/b

24 pritisajja.info

Operators

Java operators can be grouped into the following four groups:

• Arithmetic, • Bitwise, • Relational, • Logical.

25 pritisajja.info

Arithmetic Operators

Operator Result • + Addition • - Subtraction (unary minus) • * Multiplication • / Division • % Modulus • ++ Increment • += Addition assignment • -= Subtraction assignment • *= Multiplication assignment • /= Division assignment • %= Modulus assignment • -- Decrement

The operands of the arithmetic

operators must be of a numeric type.

You cannot use arithmetic operators on

boolean types, but you can use them on char types

26 pritisajja.info

Bitwise OperatorsOperator Result • ~ Bitwise unary NOT • & Bitwise AND • | Bitwise OR • ^ Bitwise exclusive OR • >> Shift right • >>> Shift right zero fill • << Shift left • &= Bitwise AND assignment • |= Bitwise OR assignment • ^= Bitwise exclusive OR assignment • >>= Shift right assignment • >>>= Shift right zero fill assignment • <<= Shift left assignment

Java bitwise operators can be applied to

the integer types: long, int, short, char,

byte. Bitwise Operators act upon the

individual bits of their operands.

27 pritisajja.info

Relational Operators

Operator Result • == Equal to • != Not equal to • > Greater than • < Less than • >= Greater than or equal to • <= Less than or equal to

The relational operators determine the

relationship between two operands.

28 pritisajja.info

Boolean Logical Operators

Operator Result • & Logical AND • | Logical OR • ^ Logical XOR (exclusive OR) • || Short-circuit OR • && Short-circuit AND • ! Logical unary NOT • &= AND assignment • |= OR assignment • ^= XOR assignment • == Equal to • != Not equal to • ? : Ternary if-then-else

The relational operators determine the

relationship between two operands.

29 pritisajja.info

Boolean Logical Operators

Operator Result • & Logical AND • | Logical OR • ^ Logical XOR (exclusive OR) • || Short-circuit OR • && Short-circuit AND • ! Logical unary NOT • &= AND assignment • |= OR assignment • ^= XOR assignment • == Equal to • != Not equal to • ? : Ternary if-then-else

The relational operators determine the

relationship between two operands.

30 pritisajja.info

Data Types

• Three kinds of data types in Java.– primitive data types– reference data types– the special null data type, also the type of

the expression null. (only possible value is null) We may write if (obj!= null).

31 pritisajja.info

Primitive Data Types in Java

type kind memory rangebyte integer 1 byte -128 to 127

short integer 2 bytes -32768 to 32767

int integer 4 bytes -2147483648 to 2147483647

long integer 8 bytes-9223372036854775808 to-9223372036854775807    

float floating point 4 bytes±3.40282347 x 1038 to±3.40282347 x 10-45  

double floating point 8 bytes±1.76769313486231570 x 10308 to ±4.94065645841246544 x 10-324     

char single character

2 bytes all Unicode characters

boolean true or false 1 bit  

There is no unsigned integer in java.

32 pritisajja.info

/** This program demonstrates how Java

* adds two integers. */

public class BigInt

{

public static void main(String args[])

{

int a = 2000000000; //(9 zeros)

int b = 2000000000;

System.out.println ( “This is how Java adds integers”);

System.out.println ( a + “+” + b + “ = ” + (a+b) );

} // end of main

}// end of class

Try this….

Output:This is how Java adds integers

2000000000 + 2000000000 = -294967296

33 pritisajja.info

public class Significant

{

public static void main (String args[]){

final float PI = 3.141519265359f;

float radius = 1.0f;

float area;

area = PI * radius * radius;

System.out.println (“The area of the circle = ” + area);

}// end of main

}// end of class

Try this….

Output:area of the circle = 3.1415193

34 pritisajja.info

Declaration of variable

• A variable is defined by an identifier, a type, and an optional initializer.

• The variables also have a scope(visibility / lifetime).

• In Java, all variables must be declared before they can be used. The basic form of a variable declaration is :

type identifier [ = value][, identifier [= value] ...] ;

• Java allows variables to be initialized dynamically. For

example: double c = 2 * 2;

35 pritisajja.info

Scope and life of a variable:

• Variables declared inside a scope are not accessible to code outside.

• Scopes can be nested. The outer scope encloses the inner scope.

• Variables declared in the outer scope are visible to the inner scope.

• Variables declared in the inner scope are not visible to the outside scope.

36 pritisajja.info

public class Main

{ public static void main(String args[])

{ int x; // known within main

x = 10;

if (x == 10)

{ int y = 20;

System.out.println("x and y: " + x + " " + y);

x = y + 2; }

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

}// end of main

}// end of class

Try this….

Output:x and y: 10 20

x is 22

PSS

37 pritisajja.info

public class Main2

{ public static void main(String args[])

{ if (true)

{ int y = 20;

System.out.println("y: " + y);

} // end of if

y = 100;

}// end of main

}// end of class

Try this….

Output:

D:\>javac Main.java Main.java:9: cannot find symbol

symbol : variable y location: class Main y = 100; // Error! y not known here

^ 1 error

PSS

38 pritisajja.info

public class Main3

{ public static void main(String args[])

{ int i = 1;

{int i = 2;

}

}

}

Try this….

Output:Results in compilation error.‘i‘ is already defined……

PSS

39 pritisajja.info

Flow Control: if:

• if(condition) statement;• Note: Write a java program that compares two

variables and print appropriate message.• The condition can be expression that result in a

value.• Expression may return boolean value.

• if (b) is equivalent to if (b== true).

40 pritisajja.info

Flow Control: if else:

if (condition) statement1;

else statement2;

• Each statement may be a single statement or a compound statement enclosed in curly braces (a block).

• The condition is any expression that returns a boolean value.

• Nested if statements are possible

41 pritisajja.info

Flow Control: if else ladder:

if(condition) statement; Example

else if(condition) statement;

else if(condition) statement;

else statement;

public class Main4{ public static void main(String args[]) { int month = 4; String value; if (month == 1) value = "A"; else if (month == 2) value = "B"; else if (month == 3) value = "C"; else if (month == 4) value = "D"; else value = "Error"; System.out.println("value = " + value); } }

PSS

42 pritisajja.info

Switch statement:

switch (expression)

{ case value1: statement sequence

break;

case value2 : statement sequence break;

. . .

case valueN: statement sequence

break;

default: default statement sequence }

. Switch statement can be nested

43 pritisajja.info

Command Line arguments

public class LeapYear

{ public static void main(String[] args)

{ int year = Integer.parseInt(args[0]);

boolean Leap;

Leap= (year % 4 == 0);

if ((Leap) && (year!=100)) System.out.println(Leap);

}

}

Execution

java LeapYear 2000

true

PSS

44 pritisajja.info

Command Line arguments

public class PowersOfTwo

{ public static void main(String[] args)

{ int N = Integer.parseInt(args[0]);

int i = 0;

int powerOfTwo = 1;

while (i <= N)

{ System.out.println(i + " " + powerOfTwo);

powerOfTwo = 2 * powerOfTwo;

i = i + 1; }

}

}

Execution

java PowersOfTwo 4

????

PSS

45 pritisajja.info

Command Line arguments

public class Sqrt

{ public static void main(String[] args)

{ double c = Double.parseDouble(args[0]);

double epsilon = 1e-15;

double t = c; // relative error tolerance

while (Math.abs(t - c/t) > epsilon*t)

{ t = (c/t + t) / 2.0; }

// print out the estimate of the square root of System.out.println(t); }

}

Executionjava Sqrt 4.5

????

PSS

46 pritisajja.info

Recursion

class factorial{int fact(int n){

if (n==1) return 1; else return (n*fact(n-1));}

}class factdemo{

public static void main (String args[]){int a = 4; int fa=0;factorial f = new factorial ();fa=f.fact(a);System.out.println(fa);

}}

PSS

47 pritisajja.info

Fibonacciclass fibonacci {

int fibo(int n){

if (n==1) return 1;

else return ( fibo(n-1) + fibo(n-2) ); }

}

class fibodemo{

public static void main (String args[]){

int a = 3; int fa=0;

fibonacci f = new fibonacci ();

fa=f.fibo(a);

System.out.println(fa);

}

}

PSS

48 pritisajja.info

Arrays

• General form of one dim array declaration is

type array-name[size];• Examples are:• int a[10];

– Defines 10 integers such as a[0], a[1], … a[9]

• char let[26];– Defines 26 alphabets let[1]=‘B’;

• float x[20];• Employee e[100]; //Employee is a class definition

• Tree t[15]; // Tree is a class

49 pritisajja.info

Array Definition with Initialization

• int maxmarks[6]= {71,56,67,65,43,66}• char let[5]= {‘a’, ‘e’, ‘I’, ’o’, ’u’};• Initialization of an array can be done using

new statement as follows:– int a[j]; // defines a as an array contains j integrs

– a=new int [10] // assigns 10 integers to the array a

• This can also be written as – int [] a = new int [10];

50 pritisajja.info

Example of array

class array{

public static void main (String args[ ]){

int score [] = { 66,76,45,88,55,60};

for (int i=0; i<6; i++)

System.out.println(score[i]);

System.out.println(“==============”);

}

}

PSS

51 pritisajja.info

Example of array

public class Main4 {

public static void main(String[] args)

{ int[] intArray = new int[] { 1, 2, 3, 4, 5 }; // calculate sum

int sum = 0;

for (int i = 0; i < intArray.length; i++)

{ sum = sum + intArray[i]; } // calculate average

double average = sum / intArray.length; System.out.println("average: " + average);

}

}

PSS

52 pritisajja.info

Example of array

public class Main6

{ public static void main(String args[])

{ int a1[] = new int[10];

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

int a3[] = {4, 3, 2, 1};

System.out.println("length of a1 is " + a1.length); System.out.println("length of a2 is " + a2.length); System.out.println("length of a3 is " + a3.length);

}

}

PSS

53 pritisajja.info

Example of array with functions

class ArrayPass {

void printing(int s[]){

int i=0;

for (i=0; i<6; i++)

System.out.println(s[i]);

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

}

}

class arraydemo{

public static void main (String args[ ]){

ArrayPass student = new ArrayPass();

int score[] = {66,76,45,88,55,60};

student.printing(score);

}

}

PSS

54 pritisajja.info

import java.util.*;public class  array{  public static void main(String[] args){   int num[] = {50,20,45,82,25,63};   int l = 6; // you may use l= num.length;   int i,j,t;   System.out.print("Given number : ");  

for (i = 0;i < l;i++ ) { System.out.print("  " + num[i]); }  

System.out.println("\n");   System.out.print("Accending order number : ");  

Arrays.sort(num);     

for(i = 0;i < l;i++){   System.out.print("  " + num[i]);   }  }

}

55 pritisajja.info

Two Dimensional Arrays

Declaration of a two dimensional array called twoD with size 4*5

• int twoD[][] = new int[4][5];

(0,0) (0,3) (0,4)

(1,0) (1,1) (1,4)

(2,0) (2,2) (2,4)

(3,0) (3,3) (3,4)

56 pritisajja.info

Matrix

public class Main {

public static void main(String args[]) {

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

for (int i = 0; i < 4; i++)

{ for (int j = 0; j < 5; j++)

{ twoD[i][j] = i*j; } }

//--------------------------------------------------------------------------------

for (int i = 0; i < 4; i++)

{ for (int j = 0; j < 5; j++)

{ System.out.print(twoD[i][j] + " "); }

System.out.println(); }

}

}

57 pritisajja.info

Initialization of Two Dimensional Array

public class Main{

public static void main(String args[]) {

double m[][] = { { 0, 1, 2, 3 },

{ 0, 1, 2, 3 },

{ 0, 1, 2, 3 },

{ 0, 1, 2, 3 } };

for(int i=0; i<4; i++)

{ for(int j=0; j<4; j++)

{ System.out.print(m[i][j] + " "); }

System.out.println(); }

}

}

58 pritisajja.info

Three Dimensional Arraypublic class Main {

public static void main(String args[]) {

int threeD[][][] = new int[3][4][5]; for (int i = 0; i < 3; i++)

for (int j = 0; j < 4; j++)

for (int k = 0; k < 5; k++)

threeD[i][j][k] = i * j * k;

for (int i = 0; i < 3; i++)

{ for (int j = 0; j < 4; j++)

{ for (int k = 0; k < 5; k++)

System.out.print(threeD[i][j][k] + " ");

System.out.println(); }

System.out.println(); }

} }

59 pritisajja.info

Jagged array

• When you allocate memory for a multidimensional array, you can allocate the remaining dimensions separately. For example, the following code allocates the second dimension manually.

public class Main {

public static void main(String[] argv)

{ int twoD[][] = new int[4][];

twoD[0] = new int[5];

twoD[1] = new int[5];

twoD[2] = new int[5];

twoD[3] = new int[5]; } }

60 pritisajja.info

public class Main {

public static void main(String args[]) {

int twoD[][] = new int[4][];

twoD[0] = new int[1];

twoD[1] = new int[2];

twoD[2] = new int[3];

twoD[3] = new int[4];

61 pritisajja.info

for (int i = 0; i < 4; i++)

{ for (int j = 0; j < i + 1; j++)

{ twoD[i][j] = i + j; } }

//---------------------------------------------

for (int i = 0; i < 4; i++)

{ for (int j = 0; j < i + 1; j++)

System.out.print(twoD[i][j] + " ");

System.out.println(); }

}

}

62 pritisajja.info

63 pritisajja.info

Bank constructorclass Bank {

int accno;

String accname;

float accbal;

Bank()

{accno=999;

accname= "XXX";

accbal= 0;}

Bank(int x, String y, float z)

{accno=x;

accname= y;

accbal= z;}

Bank(int x, String y)// default t constructor

{accno=x;

accname= y;

accbal= 1000;}

void printbal()

{ System.out.println (accno);

System.out.println ( accname );

System.out.println (accbal);

}

}// end of class

64 pritisajja.info

Bank constructor

class BankDemo {

public static void main (String args[ ]){

Bank b1= new Bank();

Bank b2 = new Bank(123, "PSS");

Bank b3 = new Bank (124, "XYZ", 5000);

b1.printbal();

b2.printbal();

b3.printbal();

}

}

65 pritisajja.info

Bank with methods and array

class Bank {

int accno;

String accname;

float accbal;

Bank()

{accno=999;

accname= "XXX";

accbal= 0;}

Bank(int x, String y, float z)

{accno=x;

accname= y;

accbal= z;}

Bank(int x, String y)

{accno=x;

accname= y;

accbal= 1000;}

void printbal(){ System.out.println (accno);

System.out.println ( accname );

System.out.println (accbal);

System.out.println("----------------------------------");

}

void deposit(float Amt)

{ System.out.println("Depositing ....."+ Amt);

accbal=accbal + Amt; }

void withdraw(float Amt)

{ System.out.println("Withdrwing ....."+ Amt);

accbal=accbal - Amt; }

}// end of class

66 pritisajja.info

Bank Calling Class

class BankDemo3 {

public static void main (String args[ ]){

Bank [] b = new Bank[3];

b[0]= new Bank();

b[0].printbal();

b[1]= new Bank(111, "PPP", 5000);

b[1].printbal();

b[2]= new Bank(222,"SSS", 10000);

b[2].printbal();

b[2].deposit (10000);

b[2].printbal();

b[2].withdraw(15000);

b[2].printbal();

}

}

67 pritisajja.info

Home Assignment

• Consider students class as follows:– Sno integer– Sname String– Marks 6 integers

• Write java class having the above Student structure. Define method for total, average and result printing in this class. Define a main class, having an array of 3 students. Use the developed utilities for these 3 students.

68 pritisajja.info

Strings

• Strings in java are not primitive data types but members of String class.

• + operator can be used to join two strings.

69 pritisajja.info

• http://www.javaworld.com/javaworld/jw-09-1996/jw-09-bytecodes.html

• pctechs.biz

• Java2s.com

• http://introcs.cs.princeton.edu/java/code/

THANKS!

Other References …!

To the GDCST famliy

70 pritisajja.info

Strings

• Strings in java are not primitive data types but members of String class.

• + operator can be used to join two strings.

71 pritisajja.info

• http://www.javaworld.com/javaworld/jw-09-1996/jw-09-bytecodes.html

• pctechs.biz

• Java2s.com

THANKS!

Other References …!

To the GDCST famliy

top related