• No results found

JAVA LANG FUNDAMENTALS

N/A
N/A
Protected

Academic year: 2021

Share "JAVA LANG FUNDAMENTALS"

Copied!
80
0
0

Loading.... (view fulltext now)

Full text

(1)

Java Language Fundamentals Java Language Fundamentals This qui

This quick tutck tutorial contains bulorial contains bullet points useful for interviews or quick referlet points useful for interviews or quick reference. For a detailedence. For a detailed  java tut

 java tutorialorial click hereclick here.. 1.

1. Identifiers arIdentifiers are names of vare names of variabliables, fes, functions, classes etc. unctions, classes etc. The name used as an ideThe name used as an identifier ntifier  must

must follow the followifollow the following rules in JavaTM technology.ng rules in JavaTM technology. Each character is

Each character is either a deither a digit, letter, underscore(igit, letter, underscore(_) or currency symbol ($,¢, £ or _) or currency symbol ($,¢, £ or ¥)¥) First character cannot be a digi

First character cannot be a digit.t. The ide

The identifier name must ntifier name must not be a reserved word.not be a reserved word. 2.

2. A keyword or rA keyword or reserved word in Java eserved word in Java technology has special meaning and cannot be technology has special meaning and cannot be usedused as a user defined identifier. The list of keywords in Java technology is gi

as a user defined identifier. The list of keywords in Java technology is gi ven below. It isven below. It is important t

important to completely remember to completely remember this lihis list as you can expect a question ist as you can expect a question in Javan Java Certification exam related to this.

Certification exam related to this.

a

abbssttrraacctt bboooolleeaan bn brreeaakk bbyyttee ccaassee ccaattcchh cchhaarr ccllaassss ccoonnsstt ccoonnttiinnuuee ddeeffaauulltt ddoo d

doouubbllee eellssee eexxtteennddss ffiinnaall ffiinnaallllyy ffllooaatt

ffoorr ggoottoo iiff iimmpplleemmeennttss iimmppoorrtt iinnssttaanncceeoof  f   iinntt iinntteerrffaaccee lloonngg nnaattiivvee nneeww nnuullll

p

paacckkaagge pe prriivvaattee pprrootteecctteed pd puubblliicc rreettuurrnn sshhoorrtt ssttaattiicc ssttrriiccttffpp ssuuppeerr sswwiittcchh ssyynncchhrroonniizzeed td thhiiss tthhrrooww tthhrroowwss ttrraannssiieenntt ttrryy vvooiidd vvoollaattiillee while

while

It is important t

It is important to note the followo note the followinging 1.

1. const and gotconst and goto are not o are not currentcurrently in use.ly in use. 2.

2. null, true, and false are rnull, true, and false are reserved literals but can be considered as reserved words for teserved literals but can be considered as reserved words for thehe purpose of exam.

purpose of exam. 3.

3. It It is important is important to understto understand that and that Java language is case-sensitive. So even though super isJava language is case-sensitive. So even though super is a keyword, Super is n

a keyword, Super is not.ot. 4.

4. All the Java All the Java technology keywords technology keywords are in are in lower case.lower case. 5.

5. strictstrictfp is fp is a new keyword a new keyword added in Java 2.added in Java 2. 6.

6. The list of The list of keywords as keywords as defined by Sun is defined by Sun is presentpresent here.here. 1.

1. A literal in Java technology denotes a A literal in Java technology denotes a constant constant value. So for value. So for example 0 is an integer example 0 is an integer literal,literal, and 'c' is a

and 'c' is a character literal. The reserved literals true and false are used to representcharacter literal. The reserved literals true and false are used to represent boolean l

boolean literals. "This is a string" is a string literal.iterals. "This is a string" is a string literal. 2. Integer 

2. Integer literalsliterals can also be can also be specified as octal (base 8), or hexadecimal (base 1specified as octal (base 8), or hexadecimal (base 16). O6). Octal andctal and hexadecimal have

hexadecimal have 0 and 0x prefix respectively. So 03 0 and 0x prefix respectively. So 03 and 0x3 are representation of integer and 0x3 are representation of integer  three in octal and hexa-decimal respectively.

three in octal and hexa-decimal respectively.

5.

5. Java technoloJava technology supports gy supports three three type of type of commentscomments 1.

1. A single liA single line commne comment stent starting with /arting with /// 2.

2. A multi-line commA multi-line comment enclosed betent enclosed between /* ween /* and */and */ 3.

3. A documentatA documentation or javadoc comment ion or javadoc comment is enclosed between /** and */is enclosed between /** and */. These. These comment

comments can be used to generate HTML documents using the js can be used to generate HTML documents using the j avadoc utility, whichavadoc utility, which is part of Java language.

(2)
(3)

6.

6. Java technology supports Java technology supports the fthe followollowing primitive types - boolean (fing primitive types - boolean (for represor representing true or enting true or  false), a character t

false), a character type callype called char, four integer types (byted char, four integer types (byte, short, int and long) and e, short, int and long) and twotwo floating point types (float and double). The detail

floating point types (float and double). The details of these types are given below s of these types are given below

--Data typ

Data typeses Width (in bytWidth (in bytes)es)MinimuMinimum valuem value MaximMaximum Valueum Value b byyttee 11 --2277 2277--11 sshhoorrtt 22 --221155 221155--11 iinntt 44 --223311 223311-- 11 lloonngg 88 --226633 226633-- 11 cchhaarr 22 00xx00 00xxffffffff   

ffllooaatt 44 11..440011229988ee--4455 33..440022882233ee++3388 d

doouubbllee 88 44..994400665566ee--332244 11..779977669933ee++330088 7.

7. Corresponding to all the prCorresponding to all the primitive type timitive type there is a wrapper here is a wrapper class defined. These classesclass defined. These classes provide useful methods for manipulating primitive data value

provide useful methods for manipulating primitive data values and objs and objects.ects.

Data typesWrapper class Data typesWrapper class iinntt IInntteeggeer  r  

sshhoorrtt SShhoorrtt lloonngg LLoonngg b

byyttee BByyttee

cchhaarr CChhaarraacctteer  r   ffllooaatt FFllooaatt

d

doouubbllee DDoouubbllee

8.

8. Instance Instance variables (data memvariables (data members of a bers of a class) and statclass) and static variables are iniic variables are initialized to defaulttialized to default values. Local variabl

values. Local variables (i.e. vares (i.e. variableiables defined in bls defined in blocks or inside member functocks or inside member functions) are notions) are not initial

initialized to default values. Local varized to default values. Local variabliables must es must be explicibe explicitly initialitly initialized before tzed before they arehey are used. If local variables are used

used. If local variables are used before initialibefore initialization, compilation error gets generatzation, compilation error gets generated. Theed. The defaults for

defaults for statstatic and iic and instance variables are given in the table belnstance variables are given in the table below.ow.

D

Daatta a ttyyppeess DDeeffaauullt t VaValluueess b

boooolleeaann ffaallssee cchhaarr ''\\uu00000000'' Integer ty

Integer types (byte, short, int, long)pes (byte, short, int, long) 00 F

Floloaattining tg tyyppees (s (ffloloaatt, , ddoouubblele)) 00..00F oF or r 00..0 D0 D O

Obbjjeecct t RReeffeerreenncceess nnuullll

public

public statstatic voiic void main(String args[]) {d main(String args[]) { int i;

int i;

System.out.println(i); System.out.println(i); }}

In this example printing of i generates a compilation error because local variable i

In this example printing of i generates a compilation error because local variable i is usedis used before being initiali

(4)

concept both for underst

concept both for understanding anding of Java languaof Java language, and for Java Certification exam.ge, and for Java Certification exam. 9.

9. A Java source fA Java source file has the following eleile has the following elements ments in this specific orderin this specific order..  An optional package st

 An optional package statementatement. . All clAll classes and asses and interfaces interfaces defined in the defined in the file belong tofile belong to this package. If the package statem

this package. If the package statement is not specient is not specified, the classes defined fied, the classes defined in the filin the filee belong to a d

belong to a default package. An example of a package statement is -efault package. An example of a package statement is -package

package testtestpackage;package; Zero or more i

Zero or more import stmport statementatements. The is. The import stmport statement matement makes any akes any classes defined classes defined inin the specified package directly availa

the specified package directly available. For example if a Java source file has able. For example if a Java source file has a stat

statement importement importing the cling the class "jass "java.class.Buttava.class.Button", then a clon", then a class in ass in the file may usethe file may use Button class directly without providing

Button class directly without providing the names of the package which defines thethe names of the package which defines the Button class. Some examples of import statement are

Button class. Some examples of import statement are -import java.awt.

import java.awt.*; // All cl*; // All classes in asses in the awt package are ithe awt package are i mportmported.ed. import java.applet.Applet;

import java.applet.Applet;  Any number

 Any number of cof class and interflass and interface definitions mace definitions may follow the ay follow the optional package andoptional package and import statements.

import statements. If a file has

If a file has all all three of the above constructthree of the above constructs, they must coms, they must come in e in the specific order of the specific order of  package statement

package statement, one or , one or more import statmore import statements, fements, followollowed by ed by any number of clany number of class or ass or  interface def

interface definitions. Alinitions. Also all so all the above three constrthe above three constructs are optional. So an eucts are optional. So an empty fmpty file ile is ais a legal Java file.

legal Java file.

10.

10. The Java interpretThe Java interpreter executes er executes a method called main, defa method called main, defined in the class specified inined in the class specified in command line

command line argumentarguments. The main s. The main method is the entry point for execution of a clmethod is the entry point for execution of a class. Inass. In Java technology the main method must have the following

Java technology the main method must have the following signature -signature -publi

public static void main(String args[]c static void main(String args[])) The ja

The java interpreter is invoked with the name of the class as an va interpreter is invoked with the name of the class as an argument. argument. The class The class namename is follo

is followed by possiwed by possible set of arguments fble set of arguments for the main function of the class. When a Javaor the main function of the class. When a Java program is invoked then the Java interpreter name "java" and

program is invoked then the Java interpreter name "java" and the class name are notthe class name are not passed to the main() method of the class. The rest of the command line arguments are passed to the main() method of the class. The rest of the command line arguments are passed as an array of String. For example invoki

passed as an array of String. For example invokingng  java Sky blue gray

 java Sky blue gray would i

would invoke main method of Sky class with an array of tnvoke main method of Sky class with an array of two elements - blue and gray.wo elements - blue and gray.

Operat

Operators and ors and assignmentsassignments

Commonly used

Commonly used operatorsoperators Foll

Following owing are some of the comare some of the commonly used JavaTM technology operators - Multiplicationmonly used JavaTM technology operators - Multiplication (*), Addition (+), Subtract

(*), Addition (+), Subtraction ion (-), logical (-), logical and (&&and (&&) Condi) Conditional tional OperatOperator ?:, Assignment (=),or ?:, Assignment (=), left shift (<<), right shift (>> and >>>), Equality comparison (==), Non-equality comparison left shift (<<), right shift (>> and >>>), Equality comparison (==), Non-equality comparison (!=).

(!=).

Conversion rules in Assi

(5)

In the description below, I am giving

In the description below, I am giving basic conversion rules basic conversion rules for assignment when sourcefor assignment when source and destination

and destination are of different types.are of different types. I.

I. If sIf source and destination are of the samource and destination are of the same type, assignment e type, assignment happens without any issues.happens without any issues. II.

II. If sIf source is of smaller size than destination but source and destination are of comource is of smaller size than destination but source and destination are of compatiblepatible types, t

types, then no casting is required. Implicit widenihen no casting is required. Implicit widening takes place in this case. An example ing takes place in this case. An example iss assigning an i

assigning an int tnt to a long.o a long. II

III. I. If sIf source and destination are of compatource and destination are of compatible ible types, types, but source is of larger size thanbut source is of larger size than destination, explici

destination, explicit casting is required. In this case, if no casting is provided t casting is required. In this case, if no casting is provided then thethen the program does not compile.

program does not compile. Floating poi

Floating point numbernt numberss Decimal

Decimal numbers (fnumbers (for example 1.3) are of type doublor example 1.3) are of type double by default. To make them of typee by default. To make them of type float they must be followed

float they must be followed by F (say, 1.3F).by F (say, 1.3F). The equali

The equality operatty operator or  The equal

The equality operator (=ity operator (==) when appl=) when applied to objied to objects retects return true if two objurn true if two objects have sameects have same refer

reference value, false otherwise. The example ence value, false otherwise. The example below below illillustratustrates this --es this --String str1 = "first string";

String str1 = "first string"; String str2 = new

String str2 = new String("first stString("first string");ring"); String str3 = "first string";

String str3 = "first string"; bool

boolean test1 = (str1 == str2);ean test1 = (str1 == str2); bool

boolean test2 = (str1 == str3);ean test2 = (str1 == str3);

In the example above, test1 is set to false because

In the example above, test1 is set to false because strstr1 and 1 and str2 point to differentstr2 point to different references. As str1 and str3 point to the same reference, test2 gets set to true. When a references. As str1 and str3 point to the same reference, test2 gets set to true. When a string is initial

string is initialized wiized without using the new operator, thout using the new operator, and with an exiand with an existing string, tsting string, then thehen the new string also

new string also points to the first spoints to the first string's location. So in tring's location. So in the example above, str1 and strthe example above, str1 and str33 point to the same pool of memory and hence test2 gets set to true. The string str2 on the point to the same pool of memory and hence test2 gets set to true. The string str2 on the other hand is created using the new

other hand is created using the new operator and hence points to a different block of operator and hence points to a different block of  memory. Hence test1 gets set to false.

memory. Hence test1 gets set to false.

The conditional o

The conditional operatorperators && and ||s && and ||

Operator && returns true if both operands are true, false otherwise. Operator || returns false Operator && returns true if both operands are true, false otherwise. Operator || returns false if both operands are false, true otherwise. The

if both operands are false, true otherwise. The important timportant thing to nohing to note about thesete about these operators is that they are short

operators is that they are short-circuited. This means that the left operand is -circuited. This means that the left operand is evaluatedevaluated before the right operator. If the result of the operation can be evaluated after computing the before the right operator. If the result of the operation can be evaluated after computing the left operand, then the right si

left operand, then the right side ide is not computed. In this respect these operators ares not computed. In this respect these operators are different f

different from their bit-wise counterpartrom their bit-wise counterparts - bit-wise s - bit-wise and (&), and biand (&), and bit-wise or (|). The bit-wiset-wise or (|). The bit-wise operators are not

short-operators are not short-circuited. This circuited. This means both the operands means both the operands of bit-wise of bit-wise operator areoperator are always eval

always evaluated independent of result of evaluations.uated independent of result of evaluations. Storing integral types

Storing integral types  All the integer t

 All the integer types in Java ypes in Java technology are technology are internally stored internally stored in two's comin two's complement. plement. In tIn two'swo's complement, positive numbers have their corresponding bin

complement, positive numbers have their corresponding binary representary representation. Two'sation. Two's complement repr

complement representation of negative numbers is generated using the followesentation of negative numbers is generated using the follow ing threeing three step process

step process -First get the bi

First get the binary representatnary representation ion of the number.of the number. Then i

Then interchange zeros and ones in the binterchange zeros and ones in the binary representnary representation.ation. Final

(6)

one byte representation)

-Converting 18 to binary -- 0001 0010 Interchanging 0s and 1s -- 1110 1101  Adding 1 -- 1110 1110

So 1110 1110 would be binary representation of -18 using two bytes and using two's complement representation.

The shift operators

The shift left operator in Java technology is "<<". There are two operators for doing the right shift - signed right shift (>>) and zero fill right shift (>>>).

The left shift operator fills the right bits by zero. The effect of each left shift is multiplying the number by two. The example below illustrates this

-int i = 13; // i is 00000000 00000000 00000000 0000 1101 i = i << 2; // i is 00000000 00000000 00000000 0011 0100

 After this left shift, i becomes 52 which is same as multiplying i by 4

Zero fill shift right is represented by the symbol >>>. This operator fills the l eftmost bits by zeros. So the result of applying the operator >>> is always positive. (In two's complement representation the leftmost bit is the sign bit. If sign bit is zero, the number is positive, negative otherwise.) The example below illustrates applying the operator >>> on a number.

int b = 13; // 00000000 00000000 00000000 0000 1101

b = b >>> 2; // b is now 00000000 00000000 00000000 0000 0011

So the result of doing a zero fill right shift by 2 on 13 is 3. The next example explai ns the effect of applying the operator >>> on a negative number.

int b = -11; //11111111 11111111 11111111 1111 0101

b = b >>> 2; // b now becomes 00111111 11111111 11111111 1111 1101 So the result of applying zero fill right shift operator with operand two on -11 is 1073741821.

Signed right shift operator (>>) fills the left most bit by the sign bit. The result of applying the signed shift bit has the same sign as the left operand. For positive numbers the signed right shift operator and the zero fill right shift operator both give the same results. For 

negative numbers, their results are different. The example below illustrates the signed right shift.

int b = -11; // 11111111 11111111 11111111 1111 0101

b = b >> 2; // 11111111 11111111 11111111 1111 1101 (2's complement of -3) // Here the sign bit 1 gets filled in the two most significant bits.

The new value of b becomes -3.

Declaration and Access Control  Array Fundamentals

(7)

 Arrays are used to represent fixed number of elements of the same type. The following are legal syntax for declaring one-dimensional arrays.

int anArray[]; int[] anArray; int []anArray;

It is important to note that the size of the array is not included in the declaration. Memory is allocated for an array using the new operator as shown below.

anArray = new int[10];

The declaration and memory allocation may be combined together as shown below. int anArray[] = new int[10];

The elements of the array are implicitly initialized to default values based on array types (0 for integral types, null for objects etc.). This is true for both local arrays as well as arrays which are data members. In this respect arrays are different from normal variables.

Variable defined inside a method are not implicitly initialized, where as array elements are implicitly initialized.

 Array Initializations

 Arrays are initialized using the syntax below int intArray[] = {1,2,3,4};

The length operator can be used to access the number of elements in an array (for  example - intArray.length).

Multidimensional Arrays

The following are legal examples of declaration of a two dimensional array. int[] arr[];

int[][] arr; int arr[][]; int []arr[];

When creating multi-dimensional arrays the initial index must be created before a later  index. The following examples are legal.

int arr[][] = new int[5][5]; int arr[][] = new int[5][];

The following example will not compile; int arr[][] = new int[][5];

Class Fundamentals

 A class defines a new type and contains methods and variables. The example below illustrates a simple class.

class City {

String name; // member variable String getName() // member method {

return name; }

(8)

} }

Method overloading

JavaTM technology allows two methods to have the same name as long as they have different signatures. The signature of a method consists of name of the method, and count and type of arguments of the method. Thus as long as the argument types of two methods are different, they may be over-loaded (have the same name).

Class constructors

Constructors are member methods that have same name as the class name. The

constructor is invoked using the new operator when a class is created. If a class does not have any constructors then Java language compiler provides an implicit default

constructor. The implicit default constructor does not have any arguments and is of the type

-class_name() { }

If a class defines one or more constructors, an implicit constructor is not provided. The example below gives a compilation error.

class Test { int temp; Test(int x) {

temp = x; }

public static void main() {

Test t = new Test(); /* This would generate a compilation error, as there is no constructor  without any arguments. */

} }

Classes in JavaTM technology The Object class

 All classes in JavaTM technology are directly or indirectly derived from the Object class. Some of the subclasses of Object class are - Boolean, Number, Void, Math, String,

(9)

Some of the important methods defined in the Object class are given below. These methods are available to all Java classes.

I. boolean equals(Object obj) - The equals method in Object class returns true if two

references point to the same object. Some classes like String and Boolean overload this method. The difference between the equals function and the equality operator is covered here.

II. String toString() - The function is used to convert objects to String. If a subclass does not override this method, the method returns a textual representation of the object, which has the following format : <name of the class>@<hash code value of the object>".

III. The following methods related to threads are also defined in Object class -void notify()

void notifyall()

void wait(long timeout) throws InteruptedException

void wait(long timeout, int nanosec) throws InteruptedException void wait() throws InteruptedException

Wrapper classes

Corresponding to all the primitive types Java technology defines wrapper classes. Some examples of these wrapper classes are - Character, Boolean, Integer, Double.

Important methods in the Math class

Some of the methods defined in the Math class are used frequently. These are explained below. Besides the functionality, it is important to understand the arguments and return type of these functions.

static double ceil(double(d)) : The method ceil returns the smallest double value equal to a mathematical integer, that is not less than the argument. For example,

ceil(3.4) returns 4.0 ceil(-2.3) returns -2.0 ceil(3.0) returns 3.0

static double floor(double(d)) : The method floor returns the largest double value equal to a mathematical integer, that is not greater than the argument. For example,

floor(3.4) returns 3.0 floor(-2.3) returns -3.0 floor(3.0) returns 3.0

(10)

static int round (float f) and static long round(double d) : The method round returns the integer closest to the argument.

round(3.7) returns 4 round(3.2) returns 3 round(3.0) returns 3 round(-3.1) returns -3

String class

The String class is used to implement immutable character strings. This means that the character string cannot be changed once it has been created. Some of the important methods are explained below.

int length() - The number of characters in the String class are returned by the length() method.

String substring(int startIndex)

String substring(int startIndex, int endIndex)

The method substring extracts a substring from a string. The method extracts a string from the startIndex to the index endIndex - 1. If endIndex is not specified then string till the end of input string is returned. The example below illustrates this

String str = "I am a string"; int len = str.length();

String str2 = str.substring(2,5);

 After the above statements str2 contains the string "am ". The string str still has the same value "I am a string". The variable len has value 13.

StringBuffer class

The StringBuffer class implements mutable strings. This means that the characters stored in the string and the capacity of the string can be changed.

Garbage Collection

Java technology's Garbage collection is complex. In this section I am only giving a brief  overview of Garbage Collection. Java technology supports automatic garbage collection. This means that the programmer does not need to free the memory used by objects. Java technology's runtime environment can claim the memory from the objects that are no

longer in use. Objects that are not being referred become candidates for garbage

collection. It is important to note that these objects are candidates only. Java technology does not guarantee that Garbage collection would happen on these objects. Before actually freeing up the memory, garbage collector invokes the finalize() method of the Object being freed.

The System.gc() method can be invoked by the program to suggest to Java technology that the Garbage Collector be invoked. However there is no guarantee when the garbage collection would be invoked. There is also no guarantee on the order in which objects will be garbage collected.

The example illustrates when a string Object becomes available for Garbage Collection. public class GCTest {

public static void main(String args[]) { String a,b;

(11)

String c = new String("test"); a = c;

c = null; // The String "test" is not yet

//available for GC as a still points to "test" b = new String("xyz");

b = c; // String "xyz" is now available for GC. a = null;

//String "test" is now available for GC. }

}

 Abstract Windowing Toolkit This topic is part of SCJP 1.2 exam but not SCJP 1.4 exam.

 AWT class hierarchy

The JavaTM Foundation class (JFC) provides two frameworks for building GUI based applications - Abstract Windowing Toolkit (AWT) and swings. Sun's JavaTM Programmer  Certification exam only covers AWT.

 AWT's class hierarchy is explained below.

FIGURE AWTs class hierarchy Key Concepts

Some things to note here are

Component is an abstract class. All other classes shown above are non-abstract (concrete). Component class is superclass of all the non-menu related user interface classes. It

provides support for event handling, drawing of components etc. Some of the methods of  Component class are

-void setForeground(Color c) void setBackground(Color c)

 As the name indicates, these methods are used to set color of a component. The font of the text rendered can be changed using the setFont(Font f) method. By default all components except objects of type Window and its subclasses (Dialog and Frame) are visible. The visibility of a component can be changed using the setVisible method defined in the component class. The prototype of this method is

(12)

Panel class does not have a title, menu or border. Applet class is used to run programs that run in a web browser.

Window class represents a top-level window. Both Window and Panel classes do not have title, menus or borders. The Window class is rarely used directly and its subclasses Frame and Dialog are more common.

The pack method defined in Window class initiates the layout manager of sub-components of the window.

The Frame class is a subclass of the Window class. It is used to create a GUI application window. Frames have title bars, icons and menus.

 AWT Event Classes This topic is part of SCJP 1.2 exam but not SCJP 1.4 exam. Events

When the user interacts with a GUI application, an event is generated. Examples of user  events are clicking a button, selecting an item or closing a window. Events are

represented as Objects in JavaTM technology. The super class of all event classes is  java.util.EventObject. Some of the important classes and their hierarchy is shown below.

Some methods related to Events are Object getSource()

This method is defined in the Event Object class. It returns the object that originated the event. So if the user has clicked a Push button, the method getSource returns the object corresponding to Push button is generated.

int getID()

This method returns the integer value corresponding to the type of event. For example if  the user has clicked on the mouse, the method getID returns the integer defined as

MouseEvent.MOUSE_CLICKED.  AWT event classes

The subclasses of ATW Event can be categorized into two groups - Semantic events and low-level events. Semantic events directly correspond to high level user interactions with a GUI component. Clicking of a button is an example of a semantic event. Following event classes are semantic classes.

 ActionEvent

(13)

ItemEvent TextEvent

Multiple low-level events may get generated for each high level user event. Following event classes are low level event classes.

ComponentEvent ContainerEvent FocusEvent KeyEvent MouseEvent PaintEvent WindowEvent

Event classes for GUI controls

By GUI component I mean objects like Button, ListBox etc. For each Java GUI component a set of events of above type are generated. It is important to understand which events are generated for each component. This is explained below.

The GUI component that generate ActionEvent are Button : When the user clicks on a PushButton. List : When an item in list box is double clicked. MenuItem : When a MenuItem is selected.

TextField : When the user clicks the Enter key in a text box.

 AdjustmentEvent is generated when the user adjusts the position of a scrollbar. Scrollbar  is the only GUI control that receives the AdjustmentEvent.

ItemEvent is generated when an item is selected or deselected. Following components generate ItemEvents.

CheckBox : When the state of the CheckBox is changed.

CheckBoxMenuItem : When the state of a MenuItem is changed. Choice : When the state of a ChoiceBox is changed.

List : When an item in list is selected or deselected.

TextEvent is generated when the contents of text component are changed. The components that generate TextEvent are TextArea and TextField.

Now I will describe the GUI components corresponding to low level event classes. FocusEvent : This event is generated when a component gains or looses focus. Focus may be gained by bringing the mouse over a component (or by using the tab key). The component that has the focus receives all user keyboard events. Focus events are generated by objects of Component class and all its subclasses.

KeyEvent and MouseEvent are subclasses of abstract InputEvent class. Both these events are generated by objects of type Component class and its subclasses. The KeyEvent is generated when the user presses or releases a key on the keyboard. The MouseEvent is generated when the user presses the mouse or moves the mouse.

WindowEvent are generated for the Window class and its subclasses. These events are generated if an operation is performed on a window. The operation could be closing of  window, opening of window, activating a window etc.

PaintEvent is generated when a component needs to be repainted (for example when an application which is in front is closed and the component needs to be redrawn.)

(14)

you in the application.

ComponentEvent are also generated by objects of type Component class and i ts subclasses. This event is generated when a component is hidden, shown, moved or  resized.

ContainerEvents are generated when a component is added or removed from a container. ComponentEvent and ContainerEvent are handled by AWT and are not normally handled by the user.

Event Listeners

These are objects that define methods to handle certain type of events. An event source (for example a PushButton) can generate one or more type of events, and maintain a list of  event listeners for each type of event. An event source can register listeners by calling

addXListener type of methods. For example a Button may register an object for handling  ActionEvent by calling addActionListener. This object would then need to implement the

listener interface corresponding to ActionEvent, which is ActionListener. The example below illustrates this

-// A window with just an OK button.

public class exampleWindow extends Frame { Button OkButton;

OkHandler handler;

public exampleWindow() { //Constructor  .... /* Code to create a window, button and set a layout Manager. */

/* Now create and add listener */ handler = new OkHandler(this);

OkButton.addActionListener(handler); }

public static void main (String args []) { new exampleWindow();

} }

/* Now define a listener object. It must implement the interface ActionListener by defining the function actionPerformed. */

class OkHandler implements ActionListener { private exampleWindow win;

public OkHandler(exampleWindow window) { win=window;

}

public void actionPerformed(ActionEvent evt) { // Process clicking of button here.

} }

(15)

So to set up the processing of events the following tasks must be done.

I. For the GUI component (like pushbutton) associate a listener object class with the

component by calling a method of type addXListener (See table below for list of methods). II. Define this listener object. It must implement the corresponding interface. The name of 

interface is of type EventListener. Table below gives list of event listeners.

III. The object must define all the methods defined in the interface it is implementing. See table for the list of Event Listener methods defined in each Event Listener interface.

Table Event types and corresponding EventSource & EventListener 

Event Type Event Source Event Listener interface

 ActionEvent Button, List, MenuItem, TextField ActionListener 

 AdjustmentEvent Scrollbar AdjustmentListener 

ItemEvent Choice, Checkbox, CheckboxMenuItem,

List ItemListener 

TextEvent TextArea, TextField TextListener  

ComponentEventComponent ComponentListener  

ContainerEvent Container ContainerListener  

FocusEvent Component FocusListener  

KeyEvent Component KeyListener  

MouseEvent Component MouseListener,

MouseMotionListener 

WindowEvent Window WindowListener  

Table Event Listener Interfaces and corresponding methods which it defines Event Listener 

interface Event Listener Methods

 ActionListener actionPerformed(ActionEvent evt)

 AdjustmentListener adjustmentValueChanged(AjustmentEvent evt) ItemListener itemStateChanged(ItemEvent evt)

TextListener textValueChanged(TextEvent evt)

ComponentListener 

componentHidden(ComponentEvent evt), componentMoved(ComponentEvent evt), componentResized(ComponentEvent evt), componentShown(ComponentEvent evt) ContainerListener  componentAdded(ContainerEvent evt),

componentRemoved(ContainerEvent evt)

FocusListener focusGained(FocusEvent evt), focusLost(FocusEvent evt) KeyListener  keyPressed(KeyEvent evt), keyReleased(KeyEvent evt),

keyTyped(KeyEvent evt) MouseListener 

mouseClicked(MouseEvent evt), mouseEntered(MouseEvent evt), mouseExited(MouseEvent evt), mousePressed(MouseEvent evt), mouseReleased(MouseEvent evt)

MouseMotionListenermouseDragged(MouseEvent evt), mouseMoved(MouseEvent evt)

WindowListener 

windowActivated(WindowEvent evt), windowClosed(WindowEvent evt), windowClosing(WindowEvent evt), windowDeactivated(WindowEvent evt), windowDeiconified(WindowEvent evt),

(16)

 Adapter classes

Event adapters facilitate implementing listener interfaces. Many event listener interfaces have more than one event listener methods. For such interfaces, Java technology defines adapter classes. These have empty implementation (stubs) of all the event listener 

methods defined in the interface they implement. A listener can subclass the adapter and override only stub methods for handling events of interest. The table below lists the low level event listener interfaces and their adapters.

Table Event Listener Interfaces and their corresponding adapter classes. Event Listener interface Event Listener Adapter 

ComponentListener ComponentAdapter  ContainerListener ContainerAdapter  FocusListener FocusAdapter   KeyListener KeyAdapter   MouseListener MouseAdapter   MouseMotionListener MouseMotionAdapter  WindowListener WindowAdapter   Threads Threads

 A thread is in process in execution within a program. Within a program each thread defines a separate path of execution.

Creation of a thread

 A thread can be created in two ways

a) By implementing the Runnable interface. The Runnable interface consists of only one method - the run method. The run method has a prototype of 

public void run();

b) By extending the class Thread. Execution of a thread

To execute a thread, the thread is first created and then the start() method is invoked on the thread. Eventually the thread would execute and the run method would be invoked. The example below illustrates the two methods of thread creation. You should note that the run method should not be invoked directly.

public class ThreadExample extends Thread { public void run() {

System.out.println("Thread started"); }

public static void main(String args[]) {

ThreadExample t = new ThreadExample(); t.start();

} }

(17)

Thread class.

When the run method ends, the thread is supposed to "die". The next example shows the creation of thread by implementing the Runnable interface.

public class ThreadExample2 implements Runnable { public void run() {

.../* Code which gets executed when thread gets executed. */

}

public static void main(String args[]) {

ThreadExample2 Tt = new ThreadExample2(); Thread t = new Thread(Tt);

t.start(); }

}

Example - Creating thread by implementing Runnable States of thread

 A thread can be in one of the following states - ready, waiting for some action, running, and dead. These states are explained below.

Running State A thread is said to be in running state when it is bei ng executed. This thread has access to CPU.

Ready State A thread in this state is ready for execution, but is not being currently

executed. Once a thread in the ready state gets access to the CPU, it gets converted to running state.

Dead State A thread reaches "dead" state when the run method has finished execution. This thread cannot be executed now.

Waiting State In this state the thread is waiting for some action to happen. Once that action happens, the thread gets into the ready state. A waiting thread can be i n one of the

following states - sleeping, suspended, blocked, waiting for monitor. These are explained below.

Yielding to other processes

 A CPU intensive operation being executed may not allow other threads to be executed for  a "large" period of time. To prevent this it can allow other threads to execute by invoking the yield() method. The thread on which yield() is invoked would move from running state to ready state.

Sleep state of a thread

 A thread being executed can invoke the sleep() method to cease executing, and free up the CPU. This thread would go to the "sleep" state for the specified amount of time, after  which it would move to the "ready" state. The sleep method has the following prototypes. public static void sleep (long millisec)

(18)

public static void sleep (long millisec, int nanosec) throws InterruptedException;

Synchronized state

 A code within the synchronized block is "atomic". This means only one thread can

execute that block of code for a given object at a time. If a thread has started executing this block of code for an object, no other thread can execute this block of the code (or any other  block of synchronized code) for the same object.

public synchronized void synchExample() { /* A set of synchronized statements. Assume

here that x is a data member of this class. */ if(x == 0)

x = 1; }

Layout Managers in JavaTM technology Basics of Layout Managers

Java technology uses Layout Managers to define the location and size of Graphical User  Interface components. Java technology does not encourage programmers to use absolute location and size of components. Java technology instead places components based on specified Layout Manager. A Layout Manager implements a layout policy that defines constraints between components in a container.

Types of Layout Managers

Java technology provides the following Layout Managers, each of which implements the LayoutManager interface. FlowLayout GridLayout BorderLayout GridBagLayout CardLayout

The FlowLayout is the default Layout Manager for Panel, and hence the Applet class. The BorderLayout is the default Layout Manager for Window class and its subclasses (Frame and Dialog).

Setting Layout Managers

The following method defined in the Container class can be used for setting layout managers.

void setLayout(LayoutManager mgr);

So for example to set FlowLayout as the Layout Manager for a container C, the followi ng can be used

-C.setLayout(new FlowLayout());

The add method defined in the Container class can be used for adding components to a container. The following are the prototypes of the add method

(19)

-Component add(-Component comp);

Component add(Component comp, int index);

void add(Component comp, Object constraints, int index); void add(Component comp, Object constraint);

The order in which components are added to a container effects the placement of 

components. Also a component added to a container can itself be a container that holds other components.

FlowLayout Manager 

FlowLayout places component in rows from left to right. Components towards the end of  row are written on next row, if there is not enough space in the current row. The

FlowLayout honors the specified size of a component. The size of a component never  changes regardless of size of container. The following constructors of FlowLayout are provided by AWT

-FlowLayout();

FlowLayout(int alignment);

FlowLayout(int alignment, int hor_gap, int ver_gap);

 Alignment can take values of constants - LEFT, CENTER and RIGHT. The default

alignment for the components in a row is center. Default horizontal and vertical gaps are 5 pixels.

GridLayout Manager 

 A GridLayout Manager places the components in a rectangular grid. Each component's position is identified by a column and row. All the cells in the grid have same size and width. Each component is stretched to the cell size. So a GridLayout ignores the

Component's preferred size.

The GridLayout class provides the following constructors. GridLayout();

GridLayout(int rows, int columns);

GridLayout(int rows, int columns, int hor_gap, int ver_gap);

This creates a row*col grid layout with the specified horizontal and vertical gaps. In the constructor, either rows or cols can be zero, but not both. The first constructor is equivalent to one row with any number of components. The default gap between components is zero pixels.

BorderLayout Manager 

 A BorderLayout Manager divides the window into five regions - North, East, West, South and Center. A component can be explicitly added to one of the regions using the add() method of the Container class. Any space left over by the component in North, East, South and West is occupied by the component in Center. Only the last component added to a region is shown, and not all regions need to be occupied by a component. So a container  that uses BorderLayout may have up-to 5 components.

The BorderLayout class defines the following constructors -BorderLayout();

(20)

 As illustrated below, components can be added to the container using add() method defined in the Container class.

Component add(Component comp);

void add(Component comp, Object constraints);

Here constraints can be NORTH, SOUTH, EAST, WEST and CENTER. These constants correspond to strings "North", "South", East", "West", and "Center" respectively. They describe the region where the component should be placed. The default region is CENTER.

GridBagLayout

GridBagLayout is the most advanced LayoutManager in Java technology. Refer to Sun site for details of GridBag layout.

Collections Collections

 A Collection allows a group of objects to be treated as a single unit. Collections define a set of core interfaces. These are

-Collection Set List SortedSet Map SortedMap

Collections also provide implementation for these interfaces. Core Interfaces

The Object hierarchy of Core Interfaces defined in Collections is given below.

Figure: Core Interfaces of Collections

Collection Interface

The Collection interface is the root of Collection hierarchy, and is used for common functionality across all collections. There is no direct implementation of Collection interface.

(21)

Set Interface

The Set interface is used to represent a group of unique elements. It extends the Collection interface. The class HashSet implements the Set interface.

SortedSet Interface

The SortedSet interface extends the Set interface. It provides extra functionality of keeping the elements sorted. So SortedSet interface is used to represent collections consisting of  unique, sorted elements. The class TreeSet is an implementation of interface SortedSet.

List Interface

The list interface extends the Collection interface to represent sequence of numbers in a fixed order. Classes ArrayList, Vector and LinkedList are implementation of List interface.

Map Interface

The Map Interface is a basic interface that is used to represent mapping of keys to values. Classes HashMap and Hashtable are implementations of Map interface.

SortedMap Interface

The SortedMap Interface extends Map interface and maintains their mappings in key order. The class TreeMap implements SortedMap interface.

The table below gives the list of Collection interfaces and the classes that implement them.

Interface Class Implementation

Set HashSet

SortedSet TreeSet

List ArrayList, Vector, LinkedList Map HashMap, Hashtable

SortedMapTreeMap

File Handling and Input/Output This topic is part of SCJP 1.2 exam but not SCJP 1.4 exam.

 java.io package

Classes related to input and output are present in the JavaTM language package java.io . Java technology uses "streams" as a general mechanism of handling data. Input streams act as a source of data. Output streams act as a destination of data.

(22)

The file class is used to store the path and name of a directory or file. The file object can be used to create, rename, or delete the file or directory it represents. The File class has the following constructors

-File(String pathname); // pathname could be file or a directory name File(String dirPathname, String filename);

File(File directory, String filename);

The File class provides the getName() method which returns the name of the file excluding the directory name.

String getName(); Byte Streams

The package java.io provides two set of class hierarchies - one for handling reading and writing of bytes, and another for handling reading and writing of characters. The abstract classes InputStream and OutputStream are the root of inheritance hierarchies handling reading and writing of bytes respectively.

Figure : InputStream class hierarchy (partial)

Figure : OutputStream class hierarchy (partial)

read and write methods

InputStream class defines the following methods for reading bytes -int read() throws IOException

(23)

int read(byte b[], int offset, int length) throws IOException

Subclasses of InputStream implement the above mentioned methods. OutputStream class defines the following methods for writing bytes -void write(int b) throws IOException

void write(byte b[]) throws IOException

void write(byte b[], int offset, int length) throws IOException

Subclasses of OutputStream implement the above mentioned methods. The example below illustrates code to read a character.

//First create an object of type FileInputStream type using the name of the file. FileInputStream inp = new FileInputStream("filename.ext");

//Create an object of type DataInputStream using inp. DataInputStream dataInp = new DataInputStream(inp); int i = dataInp.readInt();

Reader and Writer classes

Similar to the InputStream and OutputStream class hierarchies for reading and writing bytes, Java technology provides class hierarchies rooted at Reader and Writer classes for  reading and writing characters.

 A character encoding is a scheme for internal representation of characters. Java programs use 16 bit Unicode character encoding to represent characters internally. Other platforms may use a different character set (for example ASCII) to represent characters. The reader  classes support conversions of Unicode characters to internal character shortage. Every platform has a default character encoding. Besides using default encoding, Reader and Writer classes can also specify which encoding scheme to use.

The Reader class hierarchy is illustrated below.

The Writer class hierarchy is illustrated below.

The table below gives a brief overview of key Reader classes.

CharArrayReader The class supports reading of characters from a character array. InputStreamReader The class supports reading of characters from a byte input stream. A

character encoding may also be specified.

FileReader  The class supports reading of characters from a file using default character  encoding.

(24)

The table below gives a brief overview of key Writer classes.

CharArrayWriter The class supports writing of characters from a character array.

OutputStreamReader The class supports writing of characters from a byte output stream. A character encoding may also be specified.

FileWriter  The class supports writing of characters from a file using default character  encoding.

The example below illustrates reading of characters using the FileReader class. //Create a FileReader class from the file name.

FileReader fr = new FileReader("filename.txt"); int i = fr.read(); //Read a character 

(25)

Chapter 2 Operators and assignments

1. Unary operators.

1.1 Increment and Decrement operators ++

--We have postfix and prefix notation. In post-fix notation value of the

variable/expression is modified after the value is taken for the execution of statement. In prefix notation, value of the variable/expression is modified before the value is taken for the execution of statement.

x = 5; y = 0; y = x++; Result will be x = 6, y = 5 x = 5; y = 0; y = ++x; Result will be x = 6, y = 6

Implicit narrowing conversion is done, when applied to byte, short or char. 1.2 Unary minus and unary plus +

-+ has no effect than to stress positivity.

- negates an expression’s value. (2’s complement for integral expressions) 1.3 Negation !

Inverts the value of a boolean expression. 1.4 Complement ~

Inverts the bit pattern of an integral expression. (1’s complement – 0s to 1s and 1s to 0s)

Cannot be applied to non-integral types. 1.5 Cast ()

Persuades compiler to allow certain assignments. Extensive checking is done at compile and runtime to ensure type-safety.

2. Arithmetic operators *, /, %, +,

-· Can be applied to all numeric types.

· Can be applied to only the numeric types, except ‘+’ – it can be applied to Strings as well.

· All arithmetic operations are done at least with ‘int’. (If types are smaller, promotion happens. Result will be of a type at least as wide as the wide type of operands)

· Accuracy is lost silently when arithmetic overflow/error occurs. Result is a nonsense value.

(26)

· Integer division by zero throws an exception.

· % - reduce the magnitude of LHS by the magnitude of RHS. (continuous subtraction) · % - sign of the result entirely determined by sign of LHS

· 5 % 0 throws an ArithmeticException.

· Floating point calculations can produce NaN (square root of a negative no) or Infinity ( division by zero). Float and Double wrapper classes have named constants for NaN and infinities.

· NaN’s are non-ordinal for comparisons. x == Float.NaN won’t work. Use

Float.IsNaN(x) But equals method on wrapper objects(Double or Float) with NaN values compares Nan’s correctly.

· Infinities are ordinal. X == Double.POSITIVE_INFINITY will give expected result. · + also performs String concatenation (when any operand in an expression is a

String). The language itself overloads this operator. toString method of non-String object operands are called to perform concatenation. In case of primitives, a wrapper obj ect is created with the primitive value and toString method of that object is called. (“Vel” + 3 will work.)

· Be aware of associativity when multiple operands are involved. System.out.println( 1 + 2 + “3” ); // Prints 33

System.out.println( “1” + 2 + 3 ); // Prints 123 3. Shift operators - <<, >>, >>>

· << performs a signed left shift. 0 bits are brought in from the right. Sign bit (MSB) is preserved. Value becomes old value * 2 ^ x where x is no of bits shifted.

· >> performs a signed right shift. Sign bit is brought in from the left. (0 if positive, 1 if  negative. Value becomes old value / 2 ^ x where x is no of bits shifted. Also called

arithmetic right shift.

· >>> performs an unsigned logical right shift. 0 bits are brought in from the left. This operator exists since Java doesn’t provide an unsigned data type (except char). >>> changes the sign of a negative number to be positive. So don’t use it with negative numbers, if you want to preserve the sign. Also don’t use it with types smaller than int. (Since types smaller than int are promoted to an int before any shift operation and the result is cast down again, so the end result is unpredictable.)

· Shift operators can be applied to only integral types.

· -1 >> 1 is –1, not 0. This differs from simple division by 2. We can think of it as shift operation rounding down.

· 1 << 31 will become the minimum value that an int can represent. (Value becomes negative, after this operation, if you do a signed right shift sign bit is brought in from the left and the value remains negative.)

· Negative numbers are represented in two’s complement notation. (Take one’s complement and add 1 to get two’s complement)

(27)

i.e. int 32, long 64) RHS operand is reduced to RHS % x where x is no of bits in type of  result.

int x;

x = x >> 33; // Here actually what happens is x >> 1 4. Comparison operators – all return boolean type.

4.1 Ordinal comparisons - <, <=, > , >=

· Only operate on numeric types. Test the relative value of the numeric operands.

· Arithmetic promotions apply. char can be compared to float. 4.2 Object type comparison – instanceof 

· Tests the class of an object at runtime. Checking is done at compile and runtime same as the cast operator.

· Returns true if the object denoted by LHS reference can be cast to RHS type. · LHS should be an object reference expression, variable or an array reference. · RHS should be a class (abstract classes are fine), an interface or an array type, castable to LHS object reference. Compiler error if LHS & RHS are unrelated. · Can’t use java.lang.Class or its String name as RHS.

· Returns true if LHS is a class or subclass of RHS class · Returns true if LHS implements RHS interface.

· Returns true if LHS is an array reference and of type RHS. · x instanceof Component[] – legal.

· x instanceof [] – illegal. Can’t test for ‘any array of any type’ · Returns false if LHS is null, no exceptions are thrown.

· If x instanceof Y is not allowed by compiler, then Y y = (Y) x is not a valid cast expression. If x instanceof Y is allowed and returns false, the above cast is valid but throws a ClassCastException at runtime. If x instanceof Y returns true, the above cast is valid and runs fine.

4.3 Equality comparisons - ==, !=

· For primitives it’s a straightforward value comparison. (promotions apply) · For object references, this doesn’t make much sense. Use equals method for  meaningful comparisons. (Make sure that the class implements equals in a

meaningful way, like for X.equals(Y) to be true, Y instance of X must be true as well)

· For String literals, == will return true, this is because of compiler optimization. 5. Bit-wise operators - &, ^, |

(28)

· Operate on numeric and boolean operands.

· & - AND operator, both bits must be 1 to produce 1. · | - OR operator, any one bit can be 1 to produce 1.

· ^ - XOR operator, any one bit can be 1, but not both, to produce 1. · In case of booleans true is 1, false is 0.

· Can’t cast any other type to boolean. 6. Short-circuit logical operators - &&, ||

· Operate only on boolean types.

· RHS might not be evaluated (hence the name short-circuit), if the result can be determined only by looking at LHS.

· false && X is always false. · true || X is always true.

· RHS is evaluated only if the result is not certain from the LHS.

· That’s why there’s no logical XOR operator. Both bits need to be known to calculate the result.

· Short-circuiting doesn’t change the result of the operation. But side effects might be changed. (i.e. some statements in RHS might not be executed, if short-circuit happens. Be careful)

7. Ternary operator 

· Format a = x ? b : c ;

· x should be a boolean expression.

· Based on x, either b or c is evaluated. Both are never evaluated. · b will be assigned to a if x is true, else c is assigned to a.

· b and c should be assignment compatible to a.

· b and c are made identical during the operation according to promotions. 8. Assignment operators.

· Simple assignment =.

· op= calculate and assign operators(extended assignment operators) · *=, /=, %=, +=, -=

· x += y means x = x + y. But x is evaluated only once. Be aware.

· Assignment of reference variables copies the reference value, not the object body. · Assi nment has value, value of LHS after assi nment. So a = b = c = 0 is le al. c = 0

(29)

is executed first, and the value of the assignment (0) assigned to b, then the value of that assignment (again 0) is assigned to a.

· Extended assignment operators do an implicit cast. (Useful when applied to byte, short or char)

byte b = 10;

b = b + 10; // Won’t compile, explicit cast required since the expression evaluates to an int

b += 10; // OK, += does an implicit cast from int to byte 9. General

· In Java, No overflow or underflow of integers happens. i.e. The values wrap around.  Adding 1 to the maximum int value results in the minimum value.

· Always keep in mind that operands are evaluated from left to right, and the operations are executed in the order of precedence and associativity.

· Unary Postfix operators and all binary operators (except assignment operators) have left to right assoiciativity.

· All unary operators (except postfix operators), assignment operators, ternary operator, object creation and cast operators have right to left assoiciativity.

· Inspect the following code. public class Precedence {

final public static void main(String args[]) { int i = 0;

i = i++; i = i++; i = i++;

System.out.println(i);

// prints 0, since = operator has the lowest precedence. int array[] = new int[5];

int index = 0;

array[index] = index = 3;

// 1st element gets assigned to 3, not the 4thelement for (int c = 0; c < array.length; c++)

System.out.println(array[c]);

(30)

} }

Type of Operators Operators Associativity

Postfix operators [] . (parameters) ++ -- Left to Right Prefix Unary operators ++ -- + - ~ ! Right to Left Object creation and cast new (type) Right to Left Multiplication/Division/Modulus* / % Left to Right

 Addition/Subtraction + - Left to Right

Shift >>>>><< Left toRight

Relational < <= > >= instanceof Left to Right

Equality ==!= Leftto Right

Bit-wise/Boolean AND & Left to Right

Bit-wise/Boolean XOR ^ Left to Right

Bit-wise/Boolean OR | Left to Right

Logical AND (Short-circuit or 

Conditional) && Leftto Right

Logical OR (Short-circuit or 

Conditional) || Leftto Right

Ternary ? : RighttoLeft

 Assignment = += -= *= /= %= <<= >>= >>>= &= ^=

|= Right to Left

Chapter 3 Modifiers

1. Modifiers are Java keywords that provide information to compiler about the nature of the code, data and classes.

2. Access modifiers – public, protected, private

· Only applied to class level variables. Method variables are visible only inside the method.

· Can be applied to class itself (only to inner classes declared at class level, no such thing as protected or private top level class)

· Can be applied to methods and constructors.

· If a class is accessible, it doesn’t mean, the members are also accessible. Members’ accessibility determines what is accessible and what is not. But if the class is not

accessible, the members are not accessible, even though they are declared public. · If no access modifier is specified, then the accessibility is default package visibility.  All classes in the same package can access the feature. It’s called as friendly access. But

friendly is not a Java keyword. Same directory is same package in Java’s consideration. · ‘private’ means only the class can access it, not even sub-classes. So, it’ll cause access denial to a sub-class’s own variable/method.

(31)

class can access the private features of anotherinstance of the same class.

· ‘protected’ means all classes in the same package (like default) and sub-classes in any package can access the features. But a subclass in another package can a ccess the protected members in the super-class via only the references of subclass or its

subclasses. A subclass in the same package doesn’t have this restriction. This ensures that classes from other packages are accessing only the members that are part of their  inheritance hierarchy.

· Methods cannot be overridden to be more private. Only the direction shown in following figure is permitted from parent classes to sub-classes.

private à friendly (default) à protected à public

Parent classes Sub-classes

3. final

· final features cannot be changed. · final classes cannot be sub-classed.

· final variables cannot be changed. (Either a value has to be specified at declaration or an assignment statement can appear only once).

· final methods cannot be overridden.

· Method arguments marked final are read-only. Compiler error, if trying to assign values to final arguments inside the method.

· Member variables marked final are not initialized by default. They have to be explicitly assigned a value at declaration or in an initializer block. Static finals must be assigned to a value in a static initializer block, instance finals must be assigned a value in an instance initializer or in every constructor. Otherwise the compiler will complain.

· Final variables that are not assigned a value at the declaration and method

arguments that are marked final are called blank final variables. They can be assigned a value at most once.

· Local variables can be declared final as well. 4. abstract

· Can be applied to classes and methods. · For deferring implementation to sub-classes.

· Opposite of final, final can’t be sub-classed, abstract must be sub-classed. · A class should be declared abstract,

1. if it has any abstract methods.

2. if it doesn’t provide implementation to any of the abstract methods it inherited 3. if it doesn’t provide implementation to any of the methods in an interface that it says implementing.

(32)

compiler error.

· A class can be abstract even if it doesn’t have any abstract methods. 5. static

· Can be applied to nested classes, methods, variables, free floating code-block (static initializer)

· Static variables are initialized at class load time. A class has only one copy of these variables.

· Static methods can access only static variables. (They have no this)

· Access by class name is a recommended way to access static methods/variables. · Static initializer code is run at class load time.

· Static methods may not be overridden to be non-static. · Non-static methods may not be overridden to be static. · Abstract methods may not be static.

· Local variables cannot be declared as static.

· Actually, static methods are not participating in the usual overriding mechanism of  invoking the methods based on the class of the object at runtime. Static method binding is done at compile time, so the method to be invoked is determined by the type of reference variable rather than the actual type of the object it holds at runtime.

Let’s say a sub-class has a static method which ‘overrides’ a static method in a parent class. If you have a reference variable of parent class type and you assign a child class object to that variable and invoke the static method, the method invoked will be the parent class method, not the child class method. The following code explains this.

public class StaticOverridingTest { public static void main(String s[]) {

Child c = new Child();

c.doStuff(); // This will invoke Child.doStuff() Parent p = new Parent();

p.doStuff(); // This will invoke Parent.doStuff() p = c;

p.doStuff();

// This will invoke Parent.doStuff(), rather than Child.doStuff() }

}

(33)

static int x = 100;

public static void doStuff() {

System.out.println("In Parent..doStuff"); System.out.println(x);

} }

class Child extends Parent { static int x = 200;

public static void doStuff() {

System.out.println("In Child..doStuff"); System.out.println(x);

} } 6. native

· Can be applied to methods only. (static methods also)

· Written in a non-Java language, compiled for a single machine target type.

· Java classes use lot of native methods for performance and for accessing hardware Java is not aware of.

· Native method signature should be terminated by a ‘;’, curly braces will provide a compiler error.

· native doesn’t affect access qualifiers. Native methods can be private. · Can pass/return Java objects from native methods.

· System.loadLibrary is used in static initializer code to load native libraries. If the library is not loaded when the static method is called, an UnsatisfiedLinkError is thrown. 7. transient

· Can be applied to class level variables only.(Local variables cannot be declared transient)

· Transient variables may not be final or static.(But compiler allows the declaration, since it doesn’t do any harm. Variables marked transient are never serialized. Static variables are not serialized anyway.)

· Not stored as part of object’s persistent state, i.e. not written out during serialization. · Can be used for security.

(34)

· Can be applied to methods or parts of methods only.

· Used to control access to critical code in multi-threaded programs. 9. volatile

· Can be applied to variables only. · Can be applied to static variables. · Cannot be applied to final variables.

· Declaring a variable volatile indicates that it might be modified asynchronously, so that all threads will get the correct value of the variable.

· Used in multi-processor environments.

Modifier Class Inner classes (Except local and anonymous classes)

VariableMethod Constructor Free floating Code block public Y Y Y Y Y N protected N Y Y Y Y N (friendly) No access modifier 

Y Y (OK for all) Y Y Y N

private N Y Y Y Y N final Y Y (Except anonymous classes) Y Y N N abstract Y Y (Except anonymous classes) N Y N N

static N Y Y Y N Y (static initializer)

native N N N Y N N

transient N N Y N N N

synchronizedN N N Y N

Y (part of method, also need to specify an object on which a lock should be obtained)

volatile N N Y N N N

Chapter 4 Converting and Casting

Unary Numeric Promotion Contexts:

References

Related documents

 If there is an inheritance relationship, the child class object is also. identified as an object of the

3.2 Probability Distributions for Discrete Random Variables 101 3.3 Expected Values of Discrete Random Variables 112 3.4 Moments and Moment Generating Functions 121 3.5 The

The present work evaluates the nutritional and feed value of fermented sweet potato meal (ProEn-K TM ) to replace soybean meal in the diet of juvenileP.

Transmission or copying of this document is not permitted without prior written authorization. The wording &#34;Document Alcatel Business Systems&#34; must appear on all

This study has examined how indigenous student migrants from the Chittagong Hill Tracts who live in Dhaka experience increased mobility and how access to new lifestyles and global

The ABC Program uses an automated self-service-based border clearance kiosk solution (the “ABC System”) to partially automate the processing of eligible travellers

Our model gives two important characterisations of bubbles in economics: firstly, a rapid super-exponential growth; secondly, an illusion of certainty as described by a

Mercer county records search new jersey police arrest order for law for individuals in camden county nj public records in court and available.. Looking for sure your favorite