Professional Documents
Culture Documents
Arrays
An array is a collection of variables of the same type. A variable declared in brackets, [], is an array reference. Three steps Declaration - tell the compiler what the name is and the type of its elements. Construction Initialization
int numbers[]; // declaration numbers = new int[100]; // construction for (int i=0; i<100; i++) { numbers[i] = i; }
Arrays
Components of an array are accessed by a simple integer index. Element indexing begins with the number 0.
username[0] = "Fred"; username[1] = "Barney";
Indexing past the end of an array throws an exception. Multidimensional arrays can be created.
3
Extending Classes
It is easy for one Java class to extend the behavior of another Java class. This capability is usually referred to as polymorphism, which means that an object of a given class can have multiple forms.
Objectives
Extend existing classes. Define the terms subclass, superclass, overloading, and overriding. Define how constructors of subclasses operate. Define the implications of marking a class or method as final. Discuss the considerations of cloning classes.
5
An Extended Class
An extended class can be used wherever the original class was legal. Polymorphism - an object of a given class can have multiple forms. The extended class is a subclass. The class it extends is the superclass. If a class does not explicitly extend a class then it implicitly extends Object. Object declares methods that are implemented by all objects.
6
Constructor Phases
Invoke a superclass's constructor. Initialize the fields using their initializers and any initialization blocks. Execute the body of the constructor.
10
11
12
13
Anonymous classes
Use these when the weight of a full class seems too much for your needs. Extend a class or implement an interface. Defined at the same time they are created with new. Defined in the new expression. Cannot have their own constructors. Can easily become hard to read. Avoid anonymous classes longer than six lines. Use them only in the simplest of expressions.
14
Cloning objects
A clone method returns a new object whose initial state is a copy of the current state of the object on which clone was invoked. Subsequent changes to the clone will not affect the state of the original. Object.clone() Three major considerations in writing a clone method
Empty Cloneable interface. Object.clone() method. CloneNotSupportedException.
Choose the access for each part of a class design carefully: public, protected, private. If your design will have subclasses, design your protected parts carefully. Bad effects of public fields
Fields can be modified at any time by a programmer. No way to add functionality.
17
Interfaces
Interfaces are a way to declare a type consisting only of abstract methods and related constants, classes, and interfaces. An interface in Java is an expression of pure design, whereas a class is a mix of design and implementation.
18
Objectives
Describe an interface. Define the differences between single and multiple inheritance. Show how to implement an interface. Describe the differences between interfaces and abstract classes.
19
21
Extending Interfaces
Interfaces can be extended using the extends keyword. Interfaces can extend more than one interface:
interface Shimmer extends FloorWax, DessertTopping {
All methods and constants defined by FloorWax and DessertTopping are part of Shimmer.
22
Exceptions
Applications can run into many kinds of errors during execution. Java exceptions provide a clean way to check for errors without cluttering code, and provide a mechanism to signal errors directly. Exceptions are also part of a method's contract. An exception is thrown when an unexpected error condition is encountered. The exception is then caught be an encompassing clause further up the method invocation stack.
24
Objectives
Create their own Exception class. Throw an exception. Define the three choices you have when a method throws an exception. Use try/catch/finally to run a method that may throw an exception. Describe the purpose of the finally clause, and when it is run. Make better decisions about when to throw exceptions in your code.
25
throw
Exceptions are thrown using the throw statement. Exceptions are objects, so they must be created (with new) before being thrown.
27
finally
A mechanism for executing a section of code whether or not an exception is thrown. Usually used to clean up internal state or to release non-object resources, such as open files stored in local variables. Can also be used to cleanup for break, continue, and return. No way to leave a try block without executing its finally clause. A finally clause is always entered with a reason; that reason is remembered when the finally clause exits.
30
Concept of Packages
Reusability of code is one of the most important requirements in the software industry. Reusability saves time, effort and also ensures consistency. In Java, the codes which can be reused by other programs is put into a Package. A Package is a collection of classes, interfaces and/or other packages. Packages are essentially a means of organizing classes together as groups.
31
Features of Packages
Packages are useful for the following purposes: Packages allow you to organize your classes into smaller units ( such as folders ) and make it easy to locate and use the appropriate class file. It helps to avoid naming conflicts. When you are working with a number of classes, it becomes difficult to decide on names of the classes & methods. At times you would want to use the same name, which belongs to an another class. Package, basically hides the classes and avoids conflicts in names. Packages allow you to protect your classes, data and methods in a larger way than on a class-to-class basis. 32 Package names can be used to identify your classes.
More on Packages
A package name should be unique. A good way to ensure unique package names is to use an Internet domain name (reversed):
package COM.missiondata.utils;
A public class or interface is accessible to code outside that package. Types that are not public have package scope; they are available to all other code in the same package, but are hidden outside the package and even from code in nested packages. Package scope is the default if public/protected/private are not declared.
33
Importing a Package
In Java, the Packages (where the required method is already created) can be imported into any program where the method is to be used. We can import a Package in the following manner : import package_name . class_name ; Suppose you wish to use a class say My_Class whose location is as follows: This class can be imported as follows :
34
Creating a Package
In Java Packages are created in the following manner : package package_name ;
35
36
java.lang package
37
38
java.io package
39
java.io package
The classes derived in Inputstream and Outputstream can only read from or write to the respective files. We cannot use the same class for both reading and writing operations. An exception to this rule is the class RandomAccessFile. This is the class used to handle files that allow random access and is capable of mixed reading and writing operations on a file. There are two additional interface to this package :
Data input Data output
These classes are used to transfer data other than bytes or characters
40
java.util package
One of the most important package in this package is the class Date, which can be used to represent or manipulate date and time information. In addition, the class also enable us to account for time zones . Java helps us to change the size of an array which is usually fixed, by making use of the class Vector. This class also enable us to add, remove and search for items in the array.
41
42
java.io
This package consists of classes that help you for all the Input and Output operations.
java.applet
This package consists of classes that you need, to execute an applet in the browser or an appletviewer.
java.awt
This package is useful to create GUI applications.
java.util
This package provides a variety of classes and interfaces for creating lists, calendar, date, etc.
java.net
This package provides classes and interfaces for TCP/IP network programming.
43
IO Streams
Objectives
IO Streams in Java Understanding some fundamental streams Creating streams for required functionality Some advanced streams
44
Streams
Streams are channels of communication Provide a good abstraction between the source and destination Could also act as a shield to lower transport implementation Most of Javas IO is based on streams
Byte-oriented streams Character-oriented streams
Concatenating Streams
45
Streams which carries primitive data types are called high level streams.
Examples are DataInputStream and DataOutputStream.
InputStreams are used for reading the data from the source. OutputStreams are used for writing the data to the 46 destination.
How it works?
47
48
Filter Streams
Filter contents as they pass through the stream Filters can be concatenated as seen before Some filter streams
Buffered Streams LineNumberInputStream PushBackInputStream PrintStream
49
Conversion Streams
InputStreamReader: bridge from byte streams to character streams
BufferedReader in = new BufferedReader( new InputStreamReader(System.in));
50
51
Properties Click
// Read properties file. Properties properties = new Properties(); try { properties.load(new FileInputStream("filename.properties")); } catch (IOException e) { } // Write properties file. try { properties.store(new FileOutputStream("filename.properties"), null); } catch (IOException e) { }
52
Properties File
Sample properties file
name=Shiv job=trainner
53
Using Wrappers
The wrapper classes correlate to the primitive types. Wrappers have two main functions:
To wrap primitives so that they can be handled like objects To provide utility methods for primitives (usually conversions)
Other than Character and Integer, wrapper class names are the primitives name, capitalized. Wrapper constructors can take a String or a primitive, except for Character, which can only take a char. A Boolean object cant be used like a boolean primitive. The three most important method families are
xxxValue() Takes no arguments, returns a primitive parseXxx() Takes a String, returns a primitive, is static, throws NFE valueOf() Takes a String, returns a wrapped object, is static, throws NFE
54
Assertions
Assertions give you a way to test your assumptions during development and debugging. Assertions are typically enabled during testing but disabled during deployment. You can use assert as a keyword (as of version 1.4) or an identifier, but not both together. To compile older code that uses assert as an identifier (for example, a method name), use the -source 1.3 command-line flag to javac. Assertions are disabled at runtime by default. To enable them, use a commandline flag -ea or -enableassertions. You can selectively disable assertions using the -da or -disableassertions flag. You can enable or disable assertions in the system classes with the -esa or -dsa flags. You can enable and disable assertions on a class-by-class basis, using the following syntax: java -ea -da:MyClass TestClass You can enable and disable assertions on a package basis, and any package you specify also includes any subpackages (packages further down the directory hierarchy).
55
Use == to determine if two reference variables refer to the same object. Use equals() to determine if two objects are meaningfully equivalent. If you dont override equals(), your objects wont be useful hashtable/ hashmap keys. If you dont override equals(), two different objects cant be considered the same. Strings and wrappers override equals() and make good hashtable/hashmap keys. When overriding equals(), use the instanceof operator to be sure youre evaluating an appropriate class. When overriding equals(), compare the objects significant attributes.
57
Collections
Common collection activities include adding objects, removing objects, verifying object inclusion, retrieving objects, and iterating. Three meanings for "collection":
collection - Represents the data structure in which objects are stored Collection - java.util.CollectionInterface from which Set and List extend Collections - A class that holds static collection utility methods
59
Subflavors of Collections
Four basic subflavors of collections include Sorted, Unsorted, Ordered, Unordered.
Ordered means iterating through a collection in a specific, nonrandom order. Sorted means iterating through a collection in a natural sorted order.
61
More on Collections
Key attributes of common collection classes:
ArrayList: Fast iteration and fast random access Vector: Like a somewhat slower ArrayList, mainly due to its synchronized methods LinkedList: Good for adding elements to the ends, i.e., stacks and queues HashSet: Assures no duplicates, provides no ordering LinkedHashSet: No duplicates; iterates by insertion order or last accessed TreeSet: No duplicates; iterates in natural sorted order HashMap: Fastest updates (key/value pairs); allows one null key, many null values Hashtable: Like a slower HashMap (as with Vector, due to its synchronized methods). No null values or null keys allowed LinkedHashMap: Faster iterations; iterates by insertion order or last accessed, allows one null key, many null values (new with 1.4) 62 TreeMap: A sorted map, in natural order
Object Serialization
Need for Serialization Persistence:
The capability of an object to exist beyond the execution of the program which created it.
In other words :
saving the state of the program in some permanent storage device, such as file
63
Use of Serialization
Lightweight persistence communication via sockets Remote Method Invocation(RMI)
64
Serialization Mechanism
Serializable objects are converted into stream of bytes and are stored in a file (in other words objects are stored in encoded form). Serializable objects implements java.io.Serializable interface.
65
De-Serialization Mechanism
Serialized object is restored into its original form. Information for restoring kept in Serialized form of object itself.
66
Object Serialization
import java.io.*; public class SerializationDemo{ public static void main(String args[]){ try{ //Object Seriliazation MyClass object1 = new MyClass ("hello",-7, 2.7); System.out.println("object1:" + object1); FileOutputStream fos = new FileOutputStream("seril"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(object1); oos.flush(); fos.close(); }catch(Exception e) { System.exit(0); } } }
67
Object Deserialization
try{ MyClass object2; FileInputStream fis = new FileInputStream("serial"); ObjectInputStream ois = new ObjectInputStream(fis); object2 = (MyClass)ois.readObject(); ois.close(); System.out.println("Object2: " + object2); }catch(Exception e) { System.exit(0); }
68
Object Serialization
class MyClass implements Serializable{ String s; int i; double d; public MyClass (String s, int i, double d){ this.s = s; this.i = i; this.d = d; } public String toString(){ return "s=" + s + ";i=" + i + ";d= " + d ; } }
69
Solution
Encrypt the object during serialization using Security API Ensure that sensitive objects do not implement Serialializable or Externalizable
70