md03 - part3

55
eywords, and Types

Upload: rakesh-madugula

Post on 24-Dec-2014

192 views

Category:

Education


8 download

DESCRIPTION

 

TRANSCRIPT

Page 1: Md03 - part3

Module 3

Identifiers, Keywords, and Types

 

Page 2: Md03 - part3

Objectives

• Using comments in a source program • Distinguish between valid and invalid identifiers • Recognize Java technology keywords • List the eight primitive types • Declare variables of class type • Construct an object using new • Describe default initialization • Describe the significance of a reference variable• State the consequences of assigning variables of class type • Using Modifiers

Page 3: Md03 - part3

Comments

Three permissible style of comment in a Java technology program are:

// comment on one line.

/* comment on one ormore line */

/** documentation comment */

Page 4: Md03 - part3

Identifiers

• Are names given to a variable, class, or method • Can start with a Unicode letter, underscore(_), or dollar sign($) • Are case sensitive and have no maximum length • Keywords cannot be used as identifiers. • Identifiers in Java are case sensitive, foo and Foo are two different identifiers.Examples: Illegal identifiers legal identifierint :b; userNameint -d; user_nameint e#; _sys_var1int .f; $change int 7g;

Page 5: Md03 - part3

Java Keywords

Page 6: Md03 - part3

DataType

Every variable must have a data type.

A variable's data type determines the values that the variable can contain and the operations that can be performed on it.

There are two categories of data types:

primitive and reference.

Page 7: Md03 - part3

Primitive Types

• The Java programming language defines eight primitive types:

Logical boolean Textual char

Integral byte, short, int, and long

Floating double and float

Page 8: Md03 - part3

Logical – boolean

• The boolean data type has two literals, true and false.

For example, the statement:boolean truth = true;declares the variable truth as boolean type and assigns it a value of true.

Page 9: Md03 - part3

Textual – char and String

char• Represents a 16-bit Unicode character • Must have its literal enclosed in single quotes(’ ’)• Uses the following notations: 'a' The letter a • It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).

Page 10: Md03 - part3

Textual – char and String

String• Is not a primitive data type; it is a class• Has its literal enclosed in double quotes (" ") "The quick brown fox jumps over the lazy dog." • Can be used as follows:String greeting = "Good Morning !! \n"; String errorMessage = "Record Not Found !";

 

Page 11: Md03 - part3

Integral – byte, short, int, and long

• Uses three forms – Decimal, octal, or hexadecimal 2 The decimal value is two077 The leading zero indicates an octal value 0xBAAC The leading 0x indicates a hexadecimal value

• Has a default int

• Defines long by using the letter L or l

Page 12: Md03 - part3

Integral – byte, short, int, and long

Integral data types have the following ranges:

Integer Length Name or Type Range 8 bits byte -2^7 to 2^7-1 16 bits short -2^15 to 2^15 -1 32 bits int -2^31 to 2^31 -1 64 bits long -2^63 to 2^63 -1

Page 13: Md03 - part3

Floating Point – float and double

• Default is double• Floating point literal includes either a decimal point or one of the following: E or e (add exponential value) F or f (float) D or d (double) 3.14 A simple floating-point value (a double) 6.02E23 A large floating-point value 2.718F A simple float size value 123.4E+306D A large double value with redundant D

Page 14: Md03 - part3

Floating Point – float and double

• Floating point data types have the following ranges:

Float Length Name or Type 32 bits float 64 bits double

 

Page 15: Md03 - part3

Variables, Declarations, and Assignments

public class Assign { public static void main(String args []) { int x, y; // declare int variables float z = 3.414f; // declare and assign float double w = 3.1415; // declare and assign double boolean truth = true; // declare and assign boolean char c; // declare character variable String str; // declare String String str1 = "bye"; // declare and assign String variable c = 'A'; // assign value to char variable str = "Hi out there!"; // assign value to String variable x = 6; y = 1000; // assign values to int variables ... }

}

Page 16: Md03 - part3

Java Reference Types

• Beyond primitive types all others are reference types• A reference variable contains a "handle" to an object

Example: public class MyDate {

private int day = 1; private int month = 1; private int year = 2000;

} public class TestMyDate {

public static void main(String[] args) { MyDate my_birth = new MyDate(22, 7, 1964); }

}

Page 17: Md03 - part3

Constructing and Initializing Objects

• Calling new Xxx() to allocate space for the new object results in: * Space for the new object is allocated and instance variables are initialized to their default values * Explicit attribute initialization is performed * A constructor is executed * Variable assignment is made to reference the object

Example: MyDate my_birth = new MyDate(22, 7, 1964);

Page 18: Md03 - part3
Page 19: Md03 - part3
Page 20: Md03 - part3

Example OverloadCons.java

Page 21: Md03 - part3
Page 22: Md03 - part3
Page 23: Md03 - part3
Page 24: Md03 - part3
Page 25: Md03 - part3

The this Reference

Here are a few uses of the this keyword:

• this is used to disambiguate a local method or constructor variable from an instance variable

• To pass the current object as a parameter to another method or constructor

Page 26: Md03 - part3

The this Reference

public class MyDate { private int day = 1; private int month = 1; private int year = 2000; public MyDate(int day, int month, int year) { this.day = day; this.month = month; this.year = year; }

Page 27: Md03 - part3

Java Coding Conventions

• Packages: package banking.domain;

• Classes: The first letter should be capitalized and if several words are linked together , the first letter of inner word should be uppercase,class name should typically be noun. For example Dog, Account, PrintWriter

• Interfaces: The first letter should be capitalized and if several words are

linked together , the first letter of inner word should be uppercase,interface name should typically be adjective For example Runnable, Serializable

Page 28: Md03 - part3

Java Coding Conventions

• Methods: The first letter should be lowercase, and then normal, the name should typically be verb-noun pairs. For example getBalance, doCalculation, setCustomerName

• Variables: The first letter should be lowercase, and then normal For example currentCustomer

• Constants: Java constants are created by marking variables static and final. They should be named using uppercase letter with underscore as separator.

HEAD_COUNTMAXIMUM_SIZE

Page 29: Md03 - part3

Access Modifiers

Modifiers are Java Keywords that give the compiler information about the nature of code ,data or classes.

Access modifiers are public , private and protected .

Page 30: Md03 - part3

Public

Public feature is accessed by any class.

An applet(a subclass of java.applet.Applet)is declared as public so that it may be instantiated by browser.

An application declares its main() method to be public so that main() can be invoked from any Java runtime environment.

Example package p1,p2

Page 31: Md03 - part3

Private

The least generous access modifier is private. Private variable or method may only be used by an instance of class that declare the variable or method.

Page 32: Md03 - part3

Default

Default is the name given to access level that resultsfrom not specifying an access modifier.

Default means the features are accessible in the same package

Class outside the package may not access the default features.Classes outside the package may subclass the classes in the package however even the subclasses may not access the default features

Page 33: Md03 - part3

Protected

A protected feature of class is available to all classes in the same package , just like default.

Moverover a protected feature of class is available to all the subclasses of the class that own the protected feature.

This access is provided even to subclasses that resides in different package from the class that owns the protected feature.

Page 34: Md03 - part3

FinalFinal modifiers applies to classes,method and

variables.

Final class cannot be subclassed.

For example class SubMath extends java.lang.Math { } will give compiler error saying “cannot subclass final class”

In practice, avoid making a final class, unless you have security issues, as final class wipes out key benefit of OO- extensibility.

Final variable cannot be modified once it has been assigned a value

Page 35: Md03 - part3

Note Final method may not be overridden.

Will the following code compile.

Class Mammal{final void getAround(){}

}Class Dolphin extends Mammal{

void getAround(){}

}

Page 36: Md03 - part3

AbstractAbstract modifier can be applied to classes and methods.

A class that is abstract may not be instantiated.Abstract class provide a way to defer the implementation to subclass.

 abstract class animal void travel()

 class Bird class Fish class Snakevoid travel() void travel() void travel()

Page 37: Md03 - part3

The class is declared abstract if any of the following conditions are true

• The class has one or more abstract methods.• The class inherits one or more abstract method for which it doesnot provide implementation.• The class declare that it implements an interface but doesnot provide implementation for every method of that interface. • Abstract is opposite to final

Final class may not be subclassed, an abstract class must be subclassed.

Page 38: Md03 - part3

Abstract class vs. Interface

Interface Abstract class

A class may implement A class may extend several interfaces. only one abstract class.

An interface cannot An abstract class can provide any code at all provide complete code,

default code

Static final constants only Both instance and static constants are possible.

Page 39: Md03 - part3

If you add a new method to If you add a new method to an an interface, you must track abstract class, you have the down all implementations option of providing a default of that interface in the universe implementation of it. Then all and provide them with a concrete existing code will continue to implementation of that method. work without change.

An interface implementation The existing class must be may be added to any existing rewritten to extend only from class. the abstract class.

Page 40: Md03 - part3

Static

This can be applied to variables , methods and a strange kind of code that is not part of method.

Static means belong to class rather that particular instance of class.

Page 41: Md03 - part3

Example Ecstatic.java

Class Ecstatic{

static{ System.out.println(“Hello”);}

static int x=0;

Ecstatic(){x++;

}}

Page 42: Md03 - part3

Reference a static variable via two ways ·        Via reference to instance of class·        Via the class name.

Via reference to instance of classEcstatic e1=new Ecstatic();Ecstatic e2=new Ecstatic();e1.x=100;e2.x=200;reallyImportantVariable=e1.x;

//you may think its set to 100 but really its 200.

Page 43: Md03 - part3

Via class nameEcstatic e1=new Ecstatic();Ecstatic e2=new Ecstatic();Ecstatic.x=100;Ecstatic.x=200;reallyImportantVariable=Ecstatic.x; //set to 200

Note• With static methods there is no this.If a static method need to access a non static variable it must specify the instance of the class that own the variable.

• Static method cannot be overridden to be non static. Example StaticOverride.java

Page 44: Md03 - part3

Native

This modifier can be applied only to methods.

Like the abstract keyword the native indicates the body of method is to be found elsewhere.

In the case of abstract method the body lies in a subclass

With native methods the body lies outside the JVM in a library.

Native code is written in Non Java language typically C or C++.

Page 45: Md03 - part3

When the native method is invoked the library that contain the native code is loaded and available to JVM, if it is not loaded there will be a delay.

Library is loaded by System.loadLibrary(“library_name”);

Page 46: Md03 - part3

Transient

This modifier applies only to variables.

The transient variable is not stored as a part of its object persistent state.

Sometimes object contain extremely sensitive information

class WealthyCustomer extends Customer implements Serializable{

private float $wealth;private String accessCode;

}

Page 47: Md03 - part3

Now if instance of this class is written to a file somebody could snoop the access code.

To avoid it write the code like this

class WealthyCustomer extends Customer implements Serializable{

private float $wealth;private transient String accessCode;

}

Now access code will not be written out during serialization.

Page 48: Md03 - part3

SynchronizedMethods can be declared synchronized.This is used to control access to critical code in multithreaded program. VolatileOnly variable may be volatile ,declaring a variable volatile means it can be modified asynchronously.For example, a variable that might be concurrently modified by multiple threads (without locks or a similar form of mutual exclusion) should be declared volatile.

Page 49: Md03 - part3

Strictfp

strictfp forces floating points to adhere to the IEEE 754 standard. With strictfp, you can predict how your floating points will behave regardless of the underlying platform the JVM is running on.

The downside is that if the underlying platform is capable of supporting greater precision, a strictfp method won't be able to take advantage of it.

Use strictfp as a class modifier , if donot declare a class as strictfp declare an individual method as strictfp.

Page 50: Md03 - part3

Summary Modifier Class Variable Method Constructorpublic yes yes yes yesprotected no yes yes yesdefault yes yes yes yesprivate no yes yes yesfinal yes yes yes noabstract yes no yes nostatic no yes yes nonative no no yes notransient no yes no novolatile no yes no nosynchronized no no yes no

Page 51: Md03 - part3
Page 52: Md03 - part3

Which of the following declarations are illegal? (Choose all that apply.)

A. default String s;B. transient int i = 41;C. public final static native int w();D. abstract double d;E. abstract final double hyperbolicCosine();

Which of the following statements is true?

A. An abstract class may not have any final methods.B. A final class may not have any abstract methods.

Page 53: Md03 - part3

Answer: A, D, E. A is illegal because “default” is not a keyword. B is a legal transient declaration. C is strangebut legal. D is illegal because only methods and classesmay be abstract. E is illegal because abstract and final are contradictory.

Answer: B

Page 54: Md03 - part3

Question. Which of the following statements is true?

A. Transient methods may not be overridden.B. Transient methods must be overridden.C. Transient classes may not be serialized.D. Transient variables must be static.E. Transient variables are not serialized.

Page 55: Md03 - part3

Answer: E. A, B, and C don’t mean anything, because only variables may be transient, not methods or classes.D is false because transient variables may never be static.E is a good one-sentence definition of transient.