core java lecture 4-5. what we will cover today what are methods scope and life time of variables...

33
Core Java Lecture 4-5

Upload: brett-gist

Post on 14-Dec-2015

214 views

Category:

Documents


1 download

TRANSCRIPT

Core Java

Lecture 4-5

What We Will Cover Today

• What Are Methods

• Scope and Life Time of Variables

• Command Line Arguments

• Use of static keyword in Java

• Shift Operators (>>,<<,>>>)

• Use of final keyword in Java

Methods

• Fulfills the operational responsibilities of the class.

• Handles Operation part of Class

• Partial General Syntax<scope> [static] [final] <return type> method-name(<Para-1>,….<Para-n>)

{

…………………………….

……………………………..

} BODY OF METHOD

<scope> public , protected, private or default package private

Method Components• Method-Name• Return Type• Signatures [Type & Number of Parameters]• Scope

Examples:

1. public void display() Signature: (), Return Type: void , Scope : public

2. private int show() Signature: (), Return Type: int, Scope : private

3. int sum(int x, int y) Signature: (int,int) , Return Type: int , Scope : default

4. float computeSum(double a, char b, int c) Signature : (double,char, int)

Return Type : float, Scope default

Method Example 1class Test{

public static double sum(double a, double b){

return (a+b);}// End of sumpublic static void main(String x[]){

double d = sum(10.6,4.5);System.out.println(d);System.out.println(sum(20,10));

}// End of main}// End of Test Class

Call to sum Method from main() Method

Method OverLoading

• Two Methods in the Same Class are said to be overloaded if and only if they have same name BUT Different Signature

• Overloaded Methods may have same return type or different return type

• Overloaded Methods may have same return scope or different scope

Method Overloading Examples

1. void sum(int a, int b)2. int sum(float a, float b)3. float sum(double a, double b)4. float sum(int x, float y)5. void sum(float a, int b)

SIGNATURES

(int,int)(float,float)

(int,float)(float,int)

(double,double)

class Test{

public static double sum( double a, double b){

System.out.println("Sum: Double Double Called"); return (a+b);

}// End of sumpublic static int sum( int a, int b){

System.out.println("Sum: int int Called"); return (a+b);

}// End of sumpublic static void main(String x[]){

System.out.println(sum(20,10));System.out.println(sum(20.5,10.7));System.out.println(sum(20.5f,10));System.out.println(sum(20.0,10));

byte b = 10;short s = 8;System.out.println(sum(b,s));

}// End of main}// End of class Test

Sum: int int Called30Sum: Double Double Called31.2Sum: Double Double Called30.5Sum: Double Double Called30.0Sum: int int Called18

class Test{

public static double sum( double a, float b){

System.out.println("Sum: Double Float Called"); return (a+b);

}// End of sumpublic static double sum( float a, double b){

System.out.println("Sum: Float Double Called"); return (a+b);

}// End of sumpublic static void main(String x[]){

System.out.println(sum(20.5,10.5f));System.out.println(sum(20.5f,10.7));System.out.println(sum(20.0,10));

}// End of main}// End of class Test Sum: Double Float Called

31.0Sum: Float Double Called31.2Sum: Double Float Called30.0

class Test{

public static double sum( double a, float b){

System.out.println("Sum: Double Float Called"); return (a+b);

}// End of sumpublic static double sum( float a, double b){

System.out.println("Sum: Float Double Called"); return (a+b);

}// End of sumpublic static void main(String x[]){

System.out.println(sum(5.6f,4.5f));System.out.println(sum(5.6,4.5));

}// End of main}// End of class Test

Test.java:15: error: reference to sum is ambiguous, both method sum(double,floa) in Test and method sum(float,double) in Test match System.out.println(sum(20.5f,10.7f)); ^Test.java:16: error: no suitable method found for sum(double,double) System.out.println(sum(20.0,10.5)); ^ method Test.sum(float,double) is not applicable (actual argument double cannot be converted to float by method invocationconversion) method Test.sum(double,float) is not applicable (actual argument double cannot be converted to float by method invocationconversion)2 errors

Scope and Life Time of Variables

1. Block scope

2. Method Scope

// Test.javaclass Test{int x;public static void main(String args[]){int y = 0;

{int y1 =10;System.out.println(y); System.out.println(y1);}

}// End of main() Method}// End of class

block { }

Example 1Method Variables and Block Variables

class Test{int x;public static void main(String args[]){int y = 0;

// BLOCK 1{

int y1 =10;System.out.println(y); System.out.println(y1);

} // BLOCK 2{

int y1 =100;System.out.println(y); System.out.println(y1);

}}// End of main() Method}// End of class

010

0100

Example 2Method Variables and Block Variables

class Test{int x;public static void main(String args[]){int y1 = 0;

// BLOCK 1{

int y1 =10;System.out.println(y); System.out.println(y1);

} // BLOCK 2{

int y1 =100;System.out.println(y); System.out.println(y1);

}}// End of main() Method}// End of class

Test.java:8: error: y1 is already defined in main(String[]) int y1 =10;Test.java:9: error: cannot find symbol System.out.println(y);symbol: variable y location: class TestTest.java:13: error: y1 is already defined in main(String[]) int y1 =100;Test.java:14: error: cannot find symbol System.out.println(y); symbol: variable y location: class Test4 errors

Example 3Method Variables and Block Variables

class Test{int x;public static void main(String args[]){int y = 0;

// BLOCK 1{

int y1 =10;System.out.println(y); System.out.println(y1);

}// End of BlockSystem.out.println(y1);}// End of main() Method}// End of class

C:\Program Files\Java\jdk1.7.0\bin>javac Test.javaTest.java:12: error: cannot find symbolSystem.out.println(y1); ^ symbol: variable y1 location: class Test1 error

Command Line Arguments

• General Form of main

public static void main(String[] args)

String array[] is used to store command line arguments that are passed when program is being executed

Assume Name of Source Java file is Test.java and name of Driver class is Driver

java Driver ----- No command line arguments. args.length = 0

Command Line Arguments cont…

• If Execution is as follows:

java Driver Hello I am fine 10 20

args.length = 6 [Number of Arguments Passed]

args[0] = “Hello”

args[1] = “I”;

args[2] = “am” ….. and so on

Converts String to int if String contains an integer in String form

ExercisePrint prime numbers from the list of numbers passed

as command Line argumentsclass commandPrime{public static void main(String x[ ]){for(int i=0; i<x.length;i++){int number = Integer.parseInt(x[i]);boolean flag = true;for (int j=2; j< number/2 ;j++){if( number % j ==0) {flag = false;break;}} // End of inner forif(flag) System.out.println(" "+number);} // End of outer for} // End of main} // End of CommandPrime

String[ ] x

Tutorial Q1……Running of CommandPrime

D:\java\bin>java commandPrime 10 20 30 13 13D:\java\bin>java commandPrime x y 30 13Exception in thread "main" java.lang.NumberFormatException:For input string: "x “ at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48) at java.lang.Integer.parseInt(Integer.java:447) at java.lang.Integer.parseInt(Integer.java:497) at commandPrime.main(prime.java:9)D:\java\bin>java commandPrime 30 13 x y 13Exception in thread "main" java.lang.NumberFormatException: For input string: "x"at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48) at java.lang.Integer.parseInt(Integer.java:447) at java.lang.Integer.parseInt(Integer.java:497) at commandPrime.main(prime.java:9)

There are Four different uses of static keyword in java.1. static instance variables2. static methods3. static classes4. static blocks

Use of static keyword in Java

Note :static field/methods of a class can be accessed/referenced even withoutcreating the objects of that class [ Provided They are not static].

Syntax : <classname> . <fieldname> OR

<classname> . <methodname>

static instance variables/fields

• Static field/instance variables are allocated space in the heap area.

• Static field is just like a global variable for a class that is allocated memory once and all objects of that class share that common copy.

• For a static fields of any class, all the objects of that class share a common copy.

• Declaring an instance field as static makes it class variable that belongs to a whole class not an individual object.

• Any Field/Attribute/instance field of a class can be declared as static.

Example (Static Fields)

class circle{static double PI=3.14156; double radius; double area(){return PI * radius * radius;} double perimeter(){return 2*PI*radius;}} // End of circle class

Static Member

Non-static instance field

circle c1 = new circle();circle c2 = new circle();

c1 c2radius radius

PI = 3.14156

Memory Map

Example (Static Fields)

class A{static int a = 10; double b , c; ……….}

A a1 = new A();

A a2 = new A();

Memory Map

a1 a2b c b c

a=10

Static Methods

• static methods can use only static data• static methods can be called/accessed/referenced even

without creating the objects that class.• Syntax

<class name> . < method name(parameter list)>• static method can not call non static methods.• Examples: Math.sqrt (all math functions)• Static method can declare local variables but from outside it

can access only static data(fields/methods)

class num{int a,b,c;static int d = 10;static double e = 20.56;num(int a,int b,int c){ this.a = a; this.b =b; this.c =c; }static int sum(int a1 , int b1){//System.out.println(“a=”+a+”b=”+b+”c=”+c);

System.out.println(“d=”+d+”e=”+e);return 40;}

static Method Example

a,b,c are non static fields and can not be accessed from a static method

non static instance fields

static instance fields

static method

static double sum(double a , double b){System.out.println(“d=”+d+”e=”+e);return 40.56;}static void pr(){System.out.println(“This is method pr”);}void print(){System.out.println(“This is method print”);pr(); // call to static method from a non static method ---- Vaild

System.out.println(“a=”+a+”b=”+b+”c=”+c);System.out.println(“d=”+d+”e=”+e);}}

class BOX{private double l,b,h; // Instance FieldsBOX(double a,double b,double c) { l=a;this.b=b;h=c;}// Constructorboolean isEqual(BOX other){if (this.l == other.l && this.b == other.b && this.h == other.h)return true;elsereturn false;}static boolean isEqual(BOX b1, BOX b2){if (b1.l == b2.l && b1.b == b2.b && b1.h == b2.h)return true;elsereturn false;}} // End of BOX class

class statictest{public static void main(String args[]){BOX b1 = new BOX(10,6,8);BOX b2 = new BOX(10,6,8);BOX b3 = new BOX(1,16,18);BOX b4 = new BOX(2,6,8);

System.out.println(b1.isEqual(b2));System.out.println(BOX.isEqual(b1,b2));System.out.println(b3.isEqual(b1,b2));System.out.println(b4.isEqual(b2));System.out.println(b4.isEqual(b4,b2));}}

D:\Java1>java statictesttruetruetruefalsefalse

Explain How You view the Following class

// Test.javaclass A{private int a,b,c;private static intd=10;public void show() // An Instance Method{System.out.println("a="+a+"b="+b+"c="+c+"d="+d);System.out.println("a="+this.a+"b="+this.b+"c="+this.c+"d="+A.d);//System.out.println("a="+this.a+"b="+this.b+"c="+this.c+"d="+this.d);display(); //A.display(); Call to a static method from non-static method}// End of show() Methodpublic static void display(){

//System.out.println("a="+a+"b="+b+"c="+c+"d="+d);A a1 = new A();System.out.println("a="+a1.a+"b="+a1.b+"c="+a1.c+"d="+a1.d);

}// End of display() Method}// End of class A

class Test{public static void main(String args[]){

// What features of class A can be accessed here and How?

A a1 = new A();A a2 = new A();

// System.out.println(a1.a);

a1.show();A.display();a1.display();

}// End of main() Method}// End of class Test

Use >>, <<, >>> Operators

• >> Right Shift Operator [Preserve Sign Bit]

• << Left Shift [ Left Shift via SignBit]

• >>> Unsigned Right Shift [ Fill 0 to Sign bit for each move]

Right Shift [>>]

• Each Right Shift will divide the number by 2

• Preserve the Sign Bit

• Syntax :num >> k ;

Where k is number of positions shifted .k = k % 32 ( if num is int, char, short or byte type)

K = k % 64 (if num is long type)

Left Shift [<<]

• Each Left Shift will multiply the number by 2

• May Change the Sign bit [ If Sign bit occurs then overflow has occurred]

• Syntax :num << k ;

Where k is number of positions shifted .k = k % 32 ( if num is int, char, short or byte type) K = k % 64 (if num is long type)

Unsigned Right Shift [>>>]

• Each Right Shift will fill 0 in the sign bit and then number is shifted along with sign bit.

• If number is +ive then both >> & >>> will work the same way

• Negative numbers sign will change and also its value after single right shift.

• For int type after 32 shifting 0 will be filled in all places.• Syntax :

num >>> k ;Where k is number of positions shifted .k = k % 32 ( if num is int, char, short or byte type) K = k % 64 (if num is long type)