You are on page 1of 33

Beginning Java 2 JDK 5

1. Introducing Java
What is Java All about? Use for applets to be embedded in web pages, JSP applications, Stand Alone Applications and XML data acceptance. Features Of Java? - Portable, OO P without the usual pitfalls, support National Language Set. Learning Java : Language is compact , however the API i.e. libraries are vast. Java Programs: Applets and Applications (Console/ Window based) Learning Java Road Ahead : 1) Basics: structure, environment, OO 2) Statements, data type, storing, calculations , decisions 3) OO Classes 4) Threads 5) GUI Java Environment: Java programs can run in any hardware because of Java 2 platform which comprises the JVM (which is the Virtual machine software) and API. Java compiler generates byte codes of the program for the JVM. Java Interpreter, either standalone or a plug-in for Web browser, deciphers, checks (no unauthorized access to the h/w resources) and executes the byte code within JVM. Java Program Development: Download J2SE version x.y JDK, earlier called as SDK. A normal text editor like JCreator is also needed. Commercial development environments will be complicated for a beginner Java and tied to a version. Installing the JDK: Instructions are available in the Sun Site. JDK for different OS and the documentation is available separately. JDK for Windows is available in 2 versions a web install where components are downloaded incrementally and as a full download exe. The documentation consists of a zipped archive of lot many HTML files arranged in a hierarchy. The installation of JDK will create directories as follows: JDK.ver: Root dir (contains a zip file of source code of the standard library class src ) Bin: Compiler, Interpreter and executables. This path should be added to PATH var.

Demo: Subdirectories with demo code. Include: C header files Sample: JNLP Java Network Launching Protocol for running the samples from
network server without a browser or local machine download.

JRE:

Java Runtime

Bin: Executables for runtime Lib: Class Libraries which are packed in rt.jar archive Lib: Files used by executables Docs: Documentation- access thru index.html Its preferable not to use commercial development software and if used PATH, CLASSPATH to be handled properly. Newer versions dont need CLASSPATH. Extracting the Source Code for Class Libraries: Library classes are zipped in src.zip and placed in root dir. Unzip using winzip or jar in the root dir to create a src directory, within the root having all the source code for the classes. It takes a long time though. Compiling a Java Program: Java program is stored in .java files which can be in a different version 1.2 or 1.4 and in a different directory than JDK. Compile using javac source 1.4 file1.java. If needed add classpath . or -cp . parameter. The compiler generates a byte code file with name file1.class in the same directory as the source .java file. Javac help will give all available options. Executing a Java Program: Java interpreter will execute the .class file which contains the file1 class. It expects the name of a class and not a file. Hence use java ea file1. Its good to include -ea which expands to enableassertations. Executing an Applet : Use a browser to view the applet embedded in a html page or use appletviewer with the name of the html file embedding the applet . HyperText Markup Language : html,head,title,body,hr,B etc are some tags used in html page. Adding an applet to an HTML Doc: <applet code=xxx.class height=xx width=yy></applet>

In IE Tools -> Advanced-> use JREV1.5 for applet should be checked if the applet is not displayed when executed. OOP in JAVA: In non OO Programming environment the solution to a problem is necessarily expressed in terms of numbers and characters which are the primitive data types. However in OO its possible to represents in term of objects/entities which in turn are composed of primitives. Because of this the program structure and solution method differs from the procedural languages. So what are objects: Anything can be thought of as an object. Class is a specification/blue print expressed as a program codecollecting objects with common properties. Subclass inherits all the properties of the parent class or the super class and includes some specialization. So for any object a class is always defined in a program. An instance of a class is an existing object of the class. What defines a class of objects: Class definition identifies all the parameters/ attributes/ fields/ instance variables that define an object of the class to the extent required by the application program. This is called as Data Abstraction. (Class is a reserved word, //are comments.) There are attributes which are fixed and attributes which change. Operating on objects: To have the objects do some work it is necessary to have a way to operate on the objects. For that it is necessary to have methods -a self-contained piece of code- which gets executed working with the variables of the objects. It may return some value. Private specifies the variables as well as the method cannot be accessed from outside. This helps both in security and easy modifications to the code. Even public methods can be modified as long as the type it returns and the variable details are the same. Constructor is a method with the same name as the class, which gets executed automatically whenever an object is instantiated. Class xyz { Private datatype var1; Private datatype var2; .. private/public datatype xyz(datatype varx,datatype vary){

:; : : } private/public datatype function1(datatype varx,datatype vary){ : : : } : : : } Java Program statements: All statements have to end with a semicolon. Free spaces are allowed except in Variable names / literals and keywords. Encapsulation: As seen earlier because some are declared private they can be accessed only from within which helps in the security and integrity of the class. Also it helps in revamping the implementation as they are not visible outside the class. Classes and Data Types: Classes are similar to primitive data types as it allows programs to work on it. Java has a library of standard classes which offers programming tools and facilities. However in java there are corresponding classes for primitive data types also. Classes and Subclasses: It is possible that there may be objects belonging to a class having some special attributes and they form a subclass of the main class. This is possible in java with the help of inheritance which allows classes to be derived form the main class.

Advantage of using objects: Because of an application depends on objects, it is easier to understand, program and extend. Java Program Structure: A java program typically consists of classes, with each class in a file of its own with the same name as the class and with the .java extension place in a source directory. However the program may also need classes from Java Standard Class library. Java Standard Class Library: The java standard class library consists of a related set of files each containing a class, stored in a single directory called as packages (rt.jar in jre/lib). A class in a package may or may not access the classes in other packages. For example: java.lang. The classes in this package can be used by default, however to use other classes in other packages it has to be imported as import java.awt.* in the start of the program code or the fully qualified name of the class has to be used. Java Application : Every Java application will have a program with a class stored in a file containing a function main which will be having modifiers like public(globally accessible), void(does not return value), static(accessible even though no objects of this class exists) . It may be the single method with a simple System.out.println statement where System is a class and out is an attribute/object and println is a method. This System class again is a static class which means its accessible even though no objects are instantiated. This program can be compiled with javac along with cp or source options and executed with java with ea option. Java and Unicode: An 8 bit (256) character set is not enough to include all the major language character sets like those of Japanese characters. Unicode which usually uses 16 bits (65535) is able to accommodate many more languages character set. Also its 3 encoding scheme allows it to represent more than a million characters. Unicode may use 32bits (surrogates) to represent the million characters set.

2. Programs, Data, Variables and Calculations


Data and Variables: A named piece of memory is a variable which can be used to store data of a particular type only as per its declaration. Explicit Data value is called as a literal when used in programs. Naming Variables: A name we choose for anything in Java is called as identifier. It can be any length but can start with a letter, underscore or a $. It can be followed by any other characters except for operators. Keywords and constants cannot be used as identifiers. Identifiers are case sensitive and conventionally supposed to be meaningful. Variable Names and Unicode: The source code is internally converted into Unicode before compiling. Variable names and data can be in other languages. Variables and Types: When a variable is declared with the type its supposed to reference, it can be used to store only that type of data. A variable can store three types of data (numeric includes integer and floating point, Unicode character representation, Boolean value) which are the primitive types and also can reference objects. Integer Data Types: 4 types which can store signed values. Byte (1 byte), short (2 bytes), int(4 bytes), long(8 bytes). Mostly int and long are used and the number is stored in binary signed form with the sign bit 0 for positive numbers and 1 with 2 complement form for negative number. Integer Literals: Normally any literal representing an integer is stored as int. L is used as a suffix for Long integers. 0X and 0 are used for hexadecimal and octal numbers. Declaring Integer Variables: Declare a variable at least just before using it and initialize it. Its convention to declare each in its own line except in cases like (x,y) coordinates and with comments thrown in between with //. Initialize it with appropriate values. Also use int whenever required instead of short or byte.

3. Loops

4. Arrays and Strings: Overview:


Arrays: Object which is a named set of variables of the same type. (Terms: Array element, index [integer or integer expression] from zero for the first element). Array variable is the location of memory holding the reference for the array object stored in a different area of memory. Declaring an array use [ ] to indicate an array and should specify the type of values that can be stored in an array referred by the variable name. Example: int [ ] array_variable ; this declares a variable which will refer to an array storing integer values. Till the new keyword is used (or initial values are set within braces) no array is created and no reference is stored in the variable. For example: int[ ] array_variable = new int[10]. Here the array_variable stores the reference of the memory location of the array storing 10 integer values. Default initial values will be 0 for numbers, /u000 for char, null for objects, false for Boolean. And the index value will range from 0 to 9 to access the array elements. If wrong index is used IndexOutOfBound exception is thrown. The length of an array can be found by using the data member length ex: array_variable.length Multidimensional arrays are also possible to be defined in Java. It is possible to use the array variable to reference another array, in which case the older array gets discarded. However, the array should be used to hold the same type as defined for the array variable. There are different methods of initializing an array: Creating an array at the time of declaration will set all the elements to be filled with default values. It is possible to set some of the elements to a specific value by assignment statement or to set all the values with a for loop. (Composite for loop can be used only for accessing the elements and not setting them.) The Arrays.fill method from java.util after importing them (to avoid using fully qualified names) can be used to fill an array with a value. An array variable can be initialized directly with the values in braces. Assigning another array variable and point to the same array referenced by it. This is useful in flipping over arrays. This can be used in place of any non array variables. Composite for loops can be used to access the array values.

It is possible to define arrays of arrays either of fixed or variable lengths. Arrays can be more than 2 dimensions. And arrays can be used to store characters. As characters are stored in Unicode format in java it occupies 2 bytes. Fill and direct assignment of values are possible for character arrays too. Strings: Strings is a class defined in java.lang. So it is not needed to be imported. The String literal is stored within double quotes . That is they are constant objects of the string class. As with a class they are the data members and there are many methods of the String class which allows for manipulations of the data members. String constants may contain escape sequences like \n for a new line and \unnnn for a Unicode hexadecimal value. It is the same way to declare a string variable and to create string objects as seen before for arrays. Any string literal enclosed in quotes will be encapsulated as an object and keyword String (like int) declares a string variable. It can be initialized directly as in the case of primitive data types. In case the value is changed, the earlier string constant reference is discarded and the reference points to the new string constant. This is because the string objects are immutable. That is it is not possible to append or delete or modify from an existing string. It is always a new one with the reference pointing to the new one. String variables have to be initialized to null as they dont get initialized by default like our primitive data types. If it is required to remove the variable pointing to a string object then initialize the variable to null. It is possible to create arrays of strings and follow the same methods of initializing the array as of any other array type. There are different operations carried out on strings. Concatenate + operator , =+ follows left to right precedence. And uses toString() of the wrapper classes (Integer,Float etc) auto to concatenate other types. -> The String class has a valueOf() method which will create a string of any basic type. -> Comparing two string variables with == will make the comparisons of the references and not the string value stored. -> To compare the string value stored in the variable use equals() method.equalsIgnoreCase() for ignoring the case. Ie. Mystring1.equals(myString2). -> String interning by Mystring1.intern() will discard any value assigned to if it equals an already existing string and would refer to the already existing string. This is automatically donr by jave so any tow identical strings will not be created twice and different

variables will be made to point the same string memory location.-> startsWith() and endsWith() are 2 more methods of String classes. compareTo() (< = > zero) Eventhough Strings are similar to arrays it is not possible to access an individual character at a position using array syntax. charAt() method is to be used for extracting character at the position and may throw StringIndexOutOfBoundsException, so should use length() method to get the length of the string object. (unlike an array where the attribute length is used) Use Character.toLowerCase(), Character.isLetter(),Character.isWhitespace() to help in comparions. Searching for character uses indexOf() and lastIndexOf() which returns the position or -1 if not found or invalid index. Check for -1 in programs to avoid pitfalls. Both methods have a version with arguments for the position and also for strings for searching substrings in a string. To extract substring from a string, substring(index) or substring(index, numberofchar) can be used. Unlike indexOf which tolerates invalid index value by returning -1, substring will not and will throw error similar to charAt(). To extract all substrings, split() method of String class is used with delimiters and limits(0 or -1). Ie sample.split(delimit,limit) Other functions are sample.replace(toreplace,replacing) ,sample.trim() which modifies strings (as always creates new strings as strings are immutable) To create character arrays from string objects use sample.toCharArray() and assingn to a char[] csample. Its not needed to create as toChararray will create a new array of chars too. Its possible to extract substring and store it in an appropriate sized char array declared and created already using getChars() which takes 4 args (start-index, end-index+1,chararray-created,chararray-start-index). getBytes() like getChars() is used to extract strings to a byte array. Using static function copyValueOf() of String class, a string from a character array can be created. By passing the start-index and the number of characters of the character array as arguments, a string can be created. The same can be avhieved by using the String() function with the text array and the index and number pf char arguments. Its not possible to use collection based for loop with strings directly , however using toCharArray() its possible to use the for loop. (numerical for loop with charAt() can be used for the same purpose)

Mutable Strings: StringBuilder and StringBuffer are identical except that StringBuffer allows for multi threaded operations whereas StringBuilder objects will allow faster operations. All operations on strings like + etc internally create a StringBuffer object which can be modified and finally converted to a String object which is not modifiable. A String object is created directly by assigning the ext value I double quotes to a string variable. However for a StringBuffer object it is necessary to create using the new keyword with the text value in double quotes. It can be created from a string variable or an already created StringBuffer variable too or initialized to null. The StringBuffer stores the string however its capacity is always more and different from the length of the string stored. By default capacity is the string length stored plus extra 16 characters. The length of the string can be got from length() and the capacity from capacity() method. Its possible to set the capacity to value when creating a StringBuffer object to reduce overheads arising of allocating new storage when the default 16 characters is used. By using ensureCapacity(value) the initial capacity will be the value specified and whenever any string is stored it will be the max of the ensured capacity or twice the value of string length plus two. Its possible to modify the length of the string as opposed to the capacity using setLength(len). If the length is less then the string is truncated and if the length is more then the string is padded with null chars/u000. Only if the setLength modifies the length greater than the capacity, the capacity will also be modied to twice the length of the string plus 2. sampleStringBuffer.append(string/int/double/Boolean/char..etc[,startIdx,numChar ]) is used to append to the SB. To find position of a substring in a SB, use lastIndexOf(substring[,posindex]). To replace, bfs.replace(startindex, subsringendindex,replacementString). Insert bfs.insert(startndex,char[] text[,intoffset,intlength]). charAt(),getChars()(no getBytes equivalent) , deleteCharAt(),delete(start,end),setCharAt(),reverse() are other functions. Create a String form StringBuffer using sbf.toString()

5. Defining Classes
What is a Class: Classes are types defined for object creation. It will be defined with fields and methods. Fields: Are also called as data members. They may be of primitive data type, or another class type or even the same class. Methods: Operates on the objects of the class though not necessary (main method). Fields in a Class definition: 2 types of fields: Class variable which is static, Instance variable which is non static. Pi will be a static variable as its not needed to be having the value stored in every object.(PI is already defined in Math class as a static variables). Any data value which is to be stored as common between objects is also defined as static. Methods in a class definition:1) static methods (cannot refer instance variables as static methods can exist without objects and hence no instance variables can be used.) Like main () method. Also its useful for utility classes. 2) instance methods (The instance methods too will be shared between the objects in a unique way like the static methods.). Accessing Static and Instance variables: Static variables are accessed using the class name and the variable name with the dot in between. For Instance variables use the instance name with the variable name and the dot. Defining Classes: Class is the keyword and by convention class names start with Capital letters.(constants have to be declared with final keyword and generally written in capital letters. Default initial values by will be 0 for numbers, /u000 for char, null for objects.)And the fields are defined. Methods are also to be defined for the class. Defining methods: A method is similar to subroutine which may or may not have parameters defined and return a value like void, int, char etc. It has an access modifier. Returning from a method: A method should have at least one return statement unless it has specified return type as void. The Parameter List: A method will have its zero or more parameters enclosed in parentheses with the type and name of the

parameter separated by comma. When a method is called the values passed are called as arguments. (Variables declared In the method are local and cannot be accessed outside and have to be initialized when declared). How Argument Values Are passed to a Method: The argument value is copied and the copy is passed to the method for primitive data types ie pass by value. For Arrays and Strings and Objects, it is passed by reference ie the address of the array/object is passed. Hence the method can modify the object. Final Parameters: The parameters can be passed with final keyword and this holds good only for object variables passed. However still the object can be changed as the variable holding the location to the object only will be protected from being changed, not the object itself. Defining Class Methods: Class methods unlike Instance methods cannot access the instance variables. The class methods are defined by prefixing static keyword. Access Class Data Members in a Method: Class data members can be used directly in a method. Example Class sphere has radius as its data member and volume as its method. Inside the method volume radius is used as such in an expression to calculate volume. The Variable this: Every Instance method by default has a variable this which references the current object calling the method. Its not necessary to include the this variable in the statement with the dot and instance variable as its automatically done by the compiler. 4 sources of data is available inside a method: a) Arguments passed as parameters b)instance variables c)local variables d) values returned by other methods. However if the parameter is defined as the same name as the instance variable then its necessary to add this to the instance variable inside the method to differentiate it from the parameter used. Thats the reason like the static method only one copy of the instance method is held in the memory for all the instances, as its easy to find which instance has called the method using the this variable.

Initializing Data Members: Both static and instance variables can be initialized while declaring in a single expression. Using Initialization Blocks:- Whenever it is needed to initialize the variables through calculations, initialization blocks, ie block of code between braces before any object creation, are to be used. The 2 types are Static (to initialize only the static variables - executed once only when the class is loaded) and Non-static blocks (to initialize the static as well as instance variables). [print() does not go to a new line unlike println() ]. Static variables can be accessed by a static method without any object/instance creation. Constructors: Whenever a new object is created, a special method called as constructor is executed. If no constructor is defined then the compiler will supply a no-arg constructor which takes no arguments and does nothing. If defined it is primarily used to initialize variables. The constructor is run only after the initialization block. 2 main characteristics of constructor are 1) It does not return a value 2) It has the same name as the class (the number of parameter (zero or more) and types vary). The Default Constructor: The compiler provides a default constructor only if there is no constructor defined. Otherwise no default constructor is provided. If it is needed it is to be defined along with other constructors and methods. Create Objects of a Class: An instance variable declaration for an object type reserves memory to store the object reference and not the object itself. Only when an object is created with a new classname_n1 () statement then the memory is allotted for the object. If a variable of the same class type is assigned the earlier object, it does not create a new object. It only creates a new reference for the same object. Passing Objects to a Method: As seen above an object and the variable referencing it are different. Hence when an object is passed as an argument to a method the parameter is copied the same value as the variable referencing it and no object copy is passed to the method. This helps in efficiency as object copying to methods would have taken substantial time. (The primitive data types are always passed by value. ie a new copy is made when passing to a

method.). And by prefixing the final keyword when passing an object as a parameter, it is possible to prevent modifications to the reference stored by the instance variable pointing to an object. The Lifetime of an Object: An object exists as long as the variable referencing the object exists. (There may be multiple variables referencing an object. In that case the object exists as long any variable referencing the object exists.) The object variable referring to an object can be set to null removing the reference from that variable. Objects thus freed will be removed through garbage collection automatically by java. However calling the static gc() method from the System class as a best efforts deal to encourage the JVM to do garbage collection and try recovering the space the objects occupy. Defining and Using a Class: Define a class with its variables, any initialization blocks, constructors and methods. Create another class with the main method to use the class earlier defined. Method Overloading: Its possible to create methods with the same name in a class as long as the number of parameters and the type of parameters and their sequence are different. This is method overloading and the number and type/sequence of the parameter and the method name forms a part of signature. The return type does not matter. It is not valid if the parameters are identical and only the return type is different. Multiple Constructors: Constructors, the special type of methods can also be overloaded. The number of parameters should be different in each method and if the same at least any parameter pair should be having a different type. Calling a Constructor from a Constructor: There is a method called as this similar to the variable this (stores reference to the object calling the method). The this method is used to call a constructor from another constructor. The this method depending on the number of parameters passed will call the appropriate constructor method. Duplicating Objects Using a Constructor: Even though there is a method called as clone () to make a copy of an object, it is possible

to make a copy of an object by defining a constructor with an object created as a parameter and using new . Using Objects: Creating a Point from Two Lines: An example program Recursion: Just like a method calling another method, it is possible for a method to call itself. This is called as recursion. However, care has to be taken to code the logic for it to stop calling indefinitely. Also weigh the advantages of using recursion, as it involves lots of overhead. (Math.pow can be used to find the power of number.)It is generally used for traversing tree data structure. Understanding Packages: A package is a uniquely named collection of classes. Classes with the same name can exist in different packages. To call a class in another package it is necessary to prefix the class name with the package name or to import the package. All the standard classes in Java are grouped in packages. So to use any of the class defined in the package it is necessary to qualify the full name or to import the package. The java.lang is imported by default in all the programs, so it is not necessary to import it specifically. If no package name is specified in the program, it is a part of the default package which has no name. Packaging Up Your Classes: Adding a package pkg_name; statement at the very start of the program excepting comments or blank lines puts the classes in the package. Unless the class, constructors, methods are declared as public they cannot be accessed from outside of the package members. Packages and the Directory Structure: The files belonging to the same package is to be placed in the same directory as the package name. There can be subdirectories and the package name reflects it with the help of the dot notation. The compiled .class files can be placed in a different directory structure as long as the directory follows the package name. Compiling a Package: Use the javac command along with the classpath option which includes the path to the package directory. All the related files will be compiled or else use *.java to compile all the files in the directory.

Accessing a Package: Use -classpath option along with javac or set CLASSPATH environment variable with the directory path. Using Extensions: Another way to access the package is to make the package as an extension. That is to create a jar using jar cvf pkg_dir.jar pkg_dir\*.class in the Directory containing the pkg_dir directory and place it in the ext directory under jre/lib. This will enable all the programs to use classes from pkg_dir without using classpath or setting CLASSPATH. Adding Classes from a Package to Your Program: All the public classes/static members/methods in a package can be imported by using import pkg_dir.*. This however will not import any classes in a package (subdirectory) within this package (directory). Its is possible to import only a single class using the import statement which is efficient too and les confusing as there will be no conflicts with conflicts with classes of the same name in the imported package. Packages and Names in Your Programs: It is sometimes necessary to use fully qualified names to classes as they may be existing in different packages which is been imported into the program. Importing Static Class Members: Even all the public static members of a class in a package can be imported and used using * in import statement. Standard Packages: There are lot many standard packages provided by Java which can be imported. Awt,swing,util,applet,io Standard Classes Encapsulating the Primitive Data Types: As mentioned earlier there are classes for every primitive data type called as wrapper classes and generally they start with a capital letter example integer will have a corresponding Integer class which encapsulates the data type integer. Short, Byte, Float, Double, Boolean, Character, Long (apart from String, StringBuffer etc ) are some. In each of these classes there is a method toString() to convert to String. Conversely each has a method like parseInt, parseByte etc to parse the string and get a value. If the string cannot be parsed NumberFormatException error is thrown.

The Boolean class has valueOf() returns the string true as Boolean true else false for other string values. Each class also has a value method which returns the encapsulated value as a primitive type. The numerical wrapper classes contains static constants MAX_VALUE, MIN_VALUE and the floating point class has constants POSITIVE_INFINITY, NEGATIVE_INFINITY, NaN (Not a Number) and static method isInfinite() and isNaN(). Character class has also lots many static methods. It is worthwhile to see the JDK doc. Autoboxing Conversions: Conversions from a primitive type to a class type is called Boxing conversions and automatic conversions are called as Autoboxing. The converse also is done by the compiler by using value (). This is useful for inserting primitive types for collections. Controlling Access to Class Members: The static variables can be accessed inside a static method and non-static as well as static variable can be accessed inside a nonstatic method. However the access of the variables and methods in another class from a class depends on the access attributes specified for the members in the other class, whether the other class is in the same package and whether the other class is defined as public. Using Access Attributes: For classes in the same package, any other class is accessible in a class for defining object variables and parameter types. Any variable and method defined in the other class is accessible depending on the access attribute. For classes in different packages unless the other class is declared as public, it is not possible to access the members and methods even if they are declared public. 4 types of access attributes: no attribute (can be accessed by all the methods in the same package), public (can be accessed by any method in any class in any package as long as the class is declared as public), private (can be accessed only by the methods of the same class), protected (can be accessed by the methods in any class in same package and any subclass in any package)

When a class in a package is defined as public, only the variables and methods defined with public are allowed to access by a class in another package, whereas a class in the same package can access all the public, protected and no attribute variables and methods. A subclass in another package can access both the protected variables and methods too when a class is declared as public, whereas a subclass in the same package can access all the public, protected and the no attribute variables and methods. . Specifying Access Attributes: By adding keyword public, protected, private in front of the declaration, the access attributes are specified.(Generally all the public members are declared and then the protected and then the private. It can be any order as long as it is consistently maintained.) To get the value of private members, methods can be written which are called accessor(getXXX) and to set the values, methods can be written called as mutators (setXXX). This mutator helps in performing validity checks. Choosing Access Attributes: It is always necessary to specify the access attributes to members and methods. Generally members are made private or protected and methods are declared public. There are exceptions like (without considering subclass): 1) When a class is not defined public, all the members can be public to allow access from other class in the same package. 2) Also if the members are defined as final then also as it anyways cannot be changed, it can be declared public to be made useful to other classes in other packages 3) If the class is like Math class as a utility the entire standard data members and methods can be declared public. 4) If some methods need not be accessed from outside they can be made private. Using Package and Access Attributes: Example program Nested Classes: It is not necessary to define classes in its own program file. Classes can be defined within a class too. These are called as the Nested classes. It also may have an access attribute similar to the other

members and methods. The class which is containing another class and is not within any other class is called the top-level class. If the nested class is created without the keyword static, it can be accessed only by an object created in the class in which it is nested. However, creating an object in the top level class will not create an object of the inner nested class unless a constructor specifically does that by creating an object of the top level class and declaring a variable with the top level class and the inside class joined by dot notation and using the new keyword with the object of the top level class. ie outside.inside tempVar = outObj.new inside() . Inside the outside class methods, it is not necessary to prefix the outside class name and the object name. ex : inside tempVar = new inside(). Automatically it will be called with the object which has called the method using the this variable. However as it is not defined as a static class it cannot be called by a static method and it cannot contain static variable or constants. Static Nested Classes: To make the nested class type independent of the enclosing class objects they can be declared as static. However to declare variables of the nested class type it is necessary to prefix the enclosing class with the dot notation in the main class. It is possible to use any static variable in the enclosed class directly in the nested class but no non static variable of the enclosed class is allowed to be accessed.( There is a Random object in Util class which has multiple methods like nextInt associated with it to generate random numbers.)A nested class after compilation will be saved as follows: EnclosingClass$NestedClass.class Using a Non-Static Nested Class: Non Static nested class cannot have static variables. This can access all the instance variables of the enclosing class as well as the instance objects of the enclosing class. Using a Nested Class Outside the Top-Level Class: As said earlier when using a nested class variable outside the top level class it has to be used with top level class context and also with an object instance of the top level class. Local Nested Classes: When a class is written within a method it is called as local nested class or local inner class. It is useful in listener for events coding.

The finalize () Method: This method if included in the program will be called when the JVM releases the non used objects in memory. For example, any file opened like images special media files can be closed in the finalize(). However, it is not advisable to leave time based actions to JVM and the finalize method as the finalize method will run only when the JVM decides to recover the space from out of scope objects. It is possible to use the runFinalization() method to compel the JVM to run the finalize method. But again its only a best deal and cannot be relied on. Native Methods: It is possible to run methods written in other languages in java. The native keyword is to be used when declaring a native method and it will end with a semicolon as the body of the method is coded elsewhere. JNI (Java Native Interface) is the standard API used to implement native methods as an interface to the java environment is required to implement the native method. Drawbacks are the java programs lose portability and may cause security concerns.

6. Extending Classes and Inheritance


OOP allows to reuse classes defined earlier or in standard class or in a specialized package. Interfaces are used Using Existing Classes: Defining a new class based on an existing class

is called as a derived class or a subclass of the base class or the superclass. This will be the direct subclass of the base class and if any class is derived further from this that will be the indirect subclass of the superclass. Keyword extends is used to define a subclass.

Class Inheritance: When a subclass is defined with some extra data members and methods, it is possible to access some members and methods of the base class in the subclass methods. The inclusion of members of the base class in a derived class so that they are accessible in the derived class is called class inheritance. The members accessible are called as the inherited members. Even though some members of the base class are not accessible or inherited, they still form part of the subclass and also in the object created from the subclass. Inheriting Data Members: The members declared as private are never inherited in the subclass either in the same package or in a different package. Protected and public specified members are accessible to subclass in the same as well as in a different package. The members without any attribute are accessed only in the subclass of the same package and not from another package subclass. (Unless a class is declared as public, a class in another package cannot derive from this class). If a member is defined as static and if it is not private, then the objects of the subclass (of the same package) also share the value along with the base class. The same (exception is here the no access modifier variables and private variables will be taken) applies for subclass from a different package. Hidden Data Members: The base class data members will be hidden in the derived class if the names are the same. Any reference to the data member name in the subclass will point to the subclass variable and not the base class. To refer to the base class variable super is to be used along with dot notation. This helps in modifying the super class without breaking the code.

Inherited Methods: Methods other than constructors in the base class behave the same way as the data members in the base class. Objects of a Derived Class: The objects of a derived class contain all the base class members though some of them may not have been inherited and so not accessible in the subclass. The methods of the base class inherited can always access all the noninherited methods too. Constructors are not inherited, however whenever an derived class object is created, the base class constructor to initialize the base class data member part is automatically supplied by the compiler if a call to the base class constructor is not coded. Deriving a Class: Derived Class Constructors Calling the Base Class Constructor Overriding a Base Class Method Choosing Base Class Access Attributes Polymorphism 279 Using Polymorphism 282 Multiple Levels of Inheritance 286 Abstract Classes 287 The Universal Superclass 288 The toString() Method 289 Determining the Type of an Object 289 Copying Objects 291 Methods Accepting a Variable Number of Arguments 295 Limiting the Types in a Variable Argument List 297 Casting Objects 298 When to Cast Objects 300 Identifying Objects 301 More on Enumerations 302 Adding Members to an Enumeration Class 303 Designing Classes 307 A Classy Example 307 Designing the PolyLine Class 309 A General-Purpose Linked List 313

Using the final Modifier: Data members are declared as static to prevent modifications. Similarly methods can be declared as static to prevent overwritten in the subclasses. Classes too can be declared as final to avoid being inherited from. So any class or method defined as abstract cannot be made final as they are mutually exclusive. Interfaces: An interface is essentially a collection of related constants (especially before java5) and /or abstract methods. As the methods are abstract, there is no definition, only the form of the method indicating the type and number of parameters and the return type. To use the interface, the class declares that it implements the interface and defines the methods in the interface. It can use the static constants in the interface as if they are declared in a base class. The methods are always abstract and the constants are always static and final and both are public. It is not needed to define them with these attributes as this is the default. Interfaces, like base classes, will be saved in a file with the same name as the interface name. Encapsulating Constants in a Program: There are 2 ways of encapsulating constants depending on the java version. Constants in an Interface: Prior to Java5, the constants will be put in an interface file. The class needing the constants will implement the interface and use the constants as if declared in the same class without using the fully qualified names. Constants Defined in a Class: From Java5 onwards, the static constants can be declared in classes within packages (as it is not possible to import from an unnamed package) and can be static imported in the class needing the constants to avoid prefixing the constants with the package name and class name. Interfaces Declaring Methods: Interfaces are used to define an external form for a set of methods, as seen earlier. A class can implement one or more interfaces using the keyword implements and the interfaces separated by commas. A Partial Interface Implementation: When a class does not define all the methods in an interface, it has to be declared as abstract and cannot be used to instantiate an object. Its

subclass if defines all the methods of the interface then can instantiate an object (If it is needed to clone an object, it is necessary to implement the cloneable interface even if a clone () method is existing. Unless the class implements cloneable interface, the clone method will not work.) Extending Interfaces: An interface can extend another interface, like a class, using extends keyword. Similar to the class concept, the interface which allows an interface to extend is called as superinterface. Interfaces and Multiple Inheritance: Unlike a class, an interface can extend multiple interfaces. The only care to be taken is any method with the same name and signature should have the same return type in all interfaces being extended. Using Interfaces: An example program Interfaces and Polymorphism Using Multiple Interfaces Method Parameters of Interface Types: Nesting Classes in an Interface Definition: Interfaces and the Real World: Anonymous Classes

7. Exceptions: Overview: Java uses exceptions as a way of signaling


serious problems or unusual events when executing a program. They allow separating the normal flow from the abnormal exception condition flow. And also to respond to the exceptional flow. The overhead of exceptions execution is high so to be used judiciously. The exception is an object storing the relevant details of the error and is thrown as a parameter to the program which handles the exception which is the catch. There are generally 4 types of exception errors - code or data error, standard method exceptions, throwing own exceptions, java errors. An exception object is always from a subclass of throwable class. It may either belong to error or exception class where only objects of the exception class can be caught in the program. Error has three subclass: ThreadDeath, LinkageError, VirtualMachineError. The ThreadDeath exception may be caught but has to be thrown again. The remaining cannot be caught. Exception has lot many subclasses where RuntimeException is one of them. Generally this class is an exception,, in that not all of them has to be caught. Still the very many classes belonging to this class which is caught often in program are
ArithmeticException, IndexOutOfBoundsException- ArrayIndexOutOfBoundsException, StringIndexOutOfBoundsException,

NegativeArraySizeException, NullPointerException, When baseclass objects call derived class methods -ArrayStoreException, ClassCastException, IllegalArgumentException SecurityException, 3 not met in normal course of operation: IllegalMonitorStateException, IllegalStateException (IllegalThreadStateException(when an operation is
illegal in the current thread state) and NumberFormatException(valueof(),parseXX,decode()),

UnsupportedOperationException.

For other subclass of exceptions it is required to be declared and/or caught otherwise the code will not compile. (This is true for user defined exceptions as the compiler will check for the methods which may raise the user defined exceptions and if they are not dealt with, the compiler will not compile the code.)

For exceptions other than Error and Runtime exceptions, it is needed to be declared as to what exceptions may be thrown (only if they are not dealt in the method). To declare, use the keyword throws along with the exception names after the method. If other methods call this method, then even those methods should either handle the exception or at least declare that it throws the exception. To deal with the exception, it is needed to use try (the code which may throw the exceptions should be in this block), catch (after the try block, the catch along with the exception parameter in parentheses is coded) and finally keywords. If the parameter to the catch keyword is RuntimeException then all the exceptions which its are subclass are also handled by this catch block. Hence it is necessary to send appropriate parameter to the catch block which should have type of either of throwable class or subclass of throwable. The variable scoping in the try and catch blocks are similar to that of any other blocks. Hence any variable declared in a try block is local and will not be available to the catch block. The try and catch block are always bonded and hence should be treated as one in loops. There can be multiple catch statements for a try block handling different exception parameters. However, the parameters in each catch should be in increasing order, that is, the most derived type should be the parameter in the first catch block and the superclass in the last catch block. Exception class type can also be a parameter in which case any exception will be handled by this catch block. As the statements in the try block following the statement raising an exception are never executed in case of an exception raised it is possible that some code like closing an opened file etc will not be executed. To avoid this, it is required to put these statements in a finally block. And similar to the catch statement the finally is attached to the try and cannot be written separately. (Even without catch statements the try and finally can be written. This helps in executing some code (in the finally block) in the event of the try block having multiple exit (break / return) points. The return values from the finally block supersedes any other return value.) If no return statement is there in the try/catch/finally block, execution continues after the finally block.

There may be one or more try bocks within a method. If an exception is thrown which is not dealt with in the method, it is passed on to the higher levels where it may be dealt with. If even after reaching main method, it is not dealt, then the program will terminate with a message. A try block can be nested within another try block and the outer catch block can catch any exceptions thrown from within the outer try block including the exceptions thrown from within the inner try block. The exception caught within a catch block can be re-thrown using the throw e (where e is the exception object passed as a parameter to the catch statement.) The exception object e derives from throwable class. It contains 2 pieces of information as per the throwable class it inherits. 1) a string message about the problem and 2) the record of the execution stack at the time of object creation. The throwable class has 2 constructors: 1. the default constructor and 2.the constructor which takes a string specifying the error message as an argument (which is stored in the exception object, the first piece of information). The public methods in throwable class are: getmessage(), printStackTrace(), printStackTrace(PrintStreams) and fillInStackTrace(). These standard exception objects dont provide much of other info. As it is possible to generate user defined exceptions, it should be done in programs to be user friendly and provide customized user messages. Also it may be required to raise some special exceptions for some error conditions arising in the particular application which warrants introducing user defined exception class. The overheads are high for user defined exception class. A user defined exception class extends either the throwable class or any of its subclass. Mostly it may extend the Exception class. It consists of the default constructor and the constructor with a string parameter which will store the user exception class name along with the message. It may consist other instance apart from what has been inherited from throwable class and corresponding constructors and also any other methods. To throw a user defined exception, create a new object of the user defined exception and use the throw statement as for the standard exceptions. A string argument may be passed to the constructor in which case the

default constructor of throwable will be bypassed and the string passed as argument will be appended to the user defined exception name. And whenever a throw statement is executed, the control passes to the calling program where the method ahs been called unless this throw statement has been written within a try block and a catch and finally block exists. Exception handling strategy may be formulated as to handle the exception in the calling program or in the called program or in both by giving detailed exception from the called program to the calling program. (Point to be noted: There may be some statements after the statement which raised exception which may never get executed. To avoid this it is possible to put all the statements in a loop which will by default execute once, but a flag set in the catch block can make it to execute once again.)

8. UNDERSTANDING STREAMS : java.io is a very vast package consisting


of more than 70 classes and interfaces, wherein each has lot many methods. It is required to read data from keyboard as well write data to the console. Apart from that it is necessary to read and write files in disk. Depending upon whether the file contains primitive data types (which may be binary or character based) or objects which may be or may not be strings, appropriate classes from java.io are to be used. From java 1.4 onwards there are 2 packages java.nio and java.nio.channels packages which supersede the original java.io package for stream handling except for files containing objects. Stream is an abstract representation of an input or output device for data. Output to display screen is sent as a character not as a graphic. Output to other devices like disk file to another computer on a remote network thru telephone lines may be sent as bytes. Data is read from an input stream which not only represents serial data but also disk files, keyboard or a remote computer. The input and output stream may have a buffer a buffered stream- which will be used to increase efficiency. It is possible to flush the buffer even if the buffer is not full with help of methods in java.io classes. This is applicable in normal circumstances only to applications and not applets. The applet may have all the rights in the directory and subdirectory where they exist and may be by giving explicit rights will be able to access some other files/dir. Java.io supports 2 types of streams: binary, character. In binary streams no transformation of data takes place. Binary data in bytes, int as 4 bytes, long as 8 bytes, characters which are stored as 16bit Unicode characters or 2 * 16 bit for surrogate character sets, the high end byte is written first followed by the low end byte. Character streams, the tokens have to be identified properly as the data is represented in terms of characters. Here Unicode to local machine code and vice versa happens while writing and reading data. (charsets is the named mapping between character codes and set of bytes which can be used to enforce a particular method instead of the local machine code.) InputStream and OutputStream are abstract classes (cannot be instantiated as objects, only subclass can be derived) implementing closeable interface (It has a single method close) mostly used for Bytestream.

Printf method for formatted output, String.format(), Formatter object method format are 3 types in use for sending the output instead of println.

You might also like