Core Java-Zulfikar Ali
Core Java-Zulfikar Ali
Objects
An object is a unique programming entity that has attributes to describe it (like adjectives in grammar) and methods to retrieve or set attribute values (like verbs in grammar). Components of a program: A real world object Behavioural responsibilities (methods) Informational responsibilities (attributes) Behaviors (methods): Things an object can do like procedures and functions in other languages. Attributes (fields): Information an object knows (has-a) like data and variables in other languages (records).
Class
A class is a blueprint of an object. A class contains attributes and behavior. To access the attributes and behavior, create an object of the class. This process is called instantiation. The created object is called an instance. Example: Automobile is a class Car is an instance of class Automobile
NIIT
Java Handout 1
OOP Features
Abstraction
A programmer should focus on the overall working of an object and ignore specific details regarding the inner-workings of an object. This concept is called abstraction.
Encapsulation
Abstraction in OOP is closely related to a concept called encapsulation. The OOP offers two major benefits as flexibility and maintainability. A programmer should write the classes and code in a way that supports flexibility and maintainability. To have maintainability, flexibility and extensibility in the design, a programmer should incorporate the encapsulation. Ways to include encapsulation: Declare instance variables protected (with an access modifier, often private). Declare methods as public accessor, and force calling code to use those methods rather than directly accessing the instance variable. Encapsulation keeps code safe from outside interference and misuse. Encapsulation: Example Bank machine Hidden data: Account balance, Personal information Interface: Deposit, Withdraw, Transfer, Display account information
Inheritance
One of the main features of OOP is inheritance. A process to inherit the properties of its superclasses is called inheritance. A child class inherits its properties and attributes from its parent class. Inheritance is the process by which one object acquires the properties of another object. While implementation of inheritance define all the general properties and methods in the superclass; and general properties and methods in the subclass.
Polymorphism
Polymorphism is a Greek word and its meaning many forms. In this case subclasses can define their own unique behaviours; they share some of the similar functionality of the parent class. It changes the behavior according to what object instance is holding it.
2 Java Handout NIIT
For example, in the base class a method is defined as shape and in subclasses polymorphism enables the programmer to define different area methods as per requirement in various classes, such as circles, rectangles and triangles. In this case create an object of shape and instantiate with various classes as circles, rectangles and triangles.
Method Overloading
In this case functions share the same name, having different signature. The signature includes return type and parameter list. For example:
Method overriding:
A method defined in a superclass is redefined in a subclass with an identical method signature. As the signatures are identical, rather than overloading the method, it is instead overriding the method. For subclass objects, the definition in the subclass replaces the version in the superclass.
NIIT
It makes Java language to be platform independent. JVM is implemented in a Java technology development tool or in a Web browser. Bytecode: Bytecode is a highly optimized set of instructions designed to be executed by the JVM. Java compiler converts the java code in bytecode at the time of compilation which enforces the security. J2SE stands for Java 2 Standard Edition. From Java SDK API version 1.5 onwards, this is referred to as Java SE (Java Standard Edition). The JRE provides the libraries, JVM, Java Interpreter, and other components necessarily for you to run applets and applications written in Java. JRE is responsible for loading, verifying, and executing the bytecodes. The JDK includes the JRE and command-line development tools, such as compilers and debuggers which are necessary for developing applets and applications. The Java API is a code that is written earlier, organized into packages of similar topics, and it is a part of JDK libraries. It allows reusability.
Defining a Class
A class is a basic building block of an object oriented language. A class is a template that contains the data and the methods. Methods are used to manipulate the class data. Examples of class: Car The following Java program defines a class Car with data member brand:
class Car { private String brand; public void setBrand(String a Brand) { brand = aBrand; } public String getBrand() { return brand;
4 Java Handout NIIT
} }
The data members in a class can be defined as follows: Instance variable: An instance variable scope is confined to the object where it is declared. Two different objects, even if they belong to the same class, can have different values for each instance variable. Class variable: The data that is shared by all the objects are declared as class variables. One copy of each variable is maintained with one object. So multiple objects will have their own copy of class variables with respective values. These variables exist even if no object of the class is created. Data members of the class are normally declared as instance variables using the keyword private.
Creating Objects
An object is created for a class to access the defined methods. The following statement creates an object: Car BMW= new Car();
Packages
In Java library all the classes belong to a package. In the Java API, classes are grouped into packages. A class has a full name, which is a combination of the package name and the class name. For example, the class Checkbox is actually java.awt.Checkbox. To use a class in a package other than java.lang (default package), you must tell Java the full name of the class. To add a class in a package, add a package statement at the top of the source code file, before any import statement like package com.myPackage. To be in a package, a class must be in a directory structure that exactly matches the package structure. For a class, com.myPackage.Book, the Book class must be in a folder named myPackage, which is in a folder named com. Organizing your classes into packages prevents naming collisions with other classes.
Java Handout 5
NIIT
Import Statement
A set of import statements look like the following: import java.io.*; import java.util.ArrayList; import java.util.Date; import java.util.Properties; The import statements must come immediately after the package statement and before the class statement.
Object Class
Object class is the superclass. All the classes are extended from Object class. Any class that does not explicitly extend another class, implicitly extends Object class. Few of the important methods of the Object class are as follows: equals(Object obj) : Indicates whether some other object is "equal to" this one and it returns a boolean value as true or false toString() : Returns a string representation of the object hashCode() : Returns a hash code value (of integer type) for the object
6 Java Handout
After successfully compiling the earlier source file, the compiler generates MyFirstProgram.class file, which is made up of bytecodes. The compiled bytecode is platform independent. Run: To run the earlier Java program in a MS-DOS prompt, give the following command:
java MyFirstProgram
The JVM translates the bytecode into something that the underlying platform understands, and runs your program. The following output will be displayed in the command prompt after running the earlier command:
NIIT Java Handout 7
Java Keywords
Keywords are predefined identifiers reserved by Java for a specific purpose. You cannot use keywords as names for your variables, classes, methods, and so on.
Java Literals
Literals are tokens that do not change. They are constant in value. The different types of literals in Java are: Integer Literals Floating-Point Literals Boolean Literals Character Literals String Literals
Unicode character: A 16-bit character set that replaces the 8-bit ASCII character set. Unicode allows the inclusion of symbols and special characters from other languages.
Coding Guidelines: In defining a long value, a lowercase L is not recommended because it is hard to distinguish from the digit 1.
10 Java Handout
NIIT
Variables
A variable is an item of data used to store the state of objects. A variable consist of data type and name. Data type determines what type of value it will hold.
Suppose you have two variables with data types int and String. int num = 20; // primitive type String name = "Welcome"; // reference type
Type Casting
Type Casting is the mapping type of an object to another. Casting Primitive Types
NIIT Java Handout 11
Casting between primitive types enables you to convert the value of one data from one type to another primitive type. Commonly occurs between numeric types. Boolean data type data cannot be typecast. Types of Casting are: Implicit Casting Explicit Casting Implicit Casting Suppose you want to store a value of int data type to a variable of data type double. int numIntVar = 20; double numDoubleVar = numIntVar; //implicit cast In this example, as the data type (double) of the destination variable holds a larger value than the data type (int) of the value, the data is implicitly casted to the data type double of the destination variable.
12 Java Handout
NIIT
Example of implicit casting: int numInt1 = 1; int numInt2 = 2; //result is implicitly cast to type double double numDouble = numInt1/numInt2; Explicit Casting When you convert a data that has a large type to a smaller type, you must use an explicit cast. Explicit casts take the following form: (Type) value where, Type is the name of the type you are converting to value. It is an expression that results in the value of the source type.
Explicit Casting Examples
double valDouble = 20.12; int valInt = (int)valDouble; //convert valDouble to int type double x = 20.2; int y = 4; int result = (int)(x/y); //typecast result of operation to int
Operators
Different types of operators are: Arithmetic operators Relational operators Logical operators Conditional operators Binary operator These operators follow a certain kind of precedence so that the compiler will know which operator to evaluate first, in case multiple operators are used in one statement. Arithmetic Operators + -- add - -- Subtract * - Multiply
NIIT Java Handout 13
/ - Divide Increment and Decrement Operators There are two unary increment operator (++) and unary decrement operator (--). Logical Operators Logical operators have one or two boolean operands that yield a boolean result. There are six logical operators: && (logical AND) & (boolean logical AND) || (logical OR) | (boolean logical inclusive OR) ^ (boolean logical exclusive OR) ! (logical NOT) Logical Operators: || (logical) and | (boolean logical) inclusive OR Logical Operators: ^ (boolean logical exclusive OR) Logical Operators: Conditional Operator (?:) The instanceof Operator The instanceof operator is a binary operator that determines whether an object reference (the left operand) is an instance of the class, interface, or array type specified by the right operand. The instanceof operator cannot be used with primitive types (this results in a compilation error).
14 Java Handout
NIIT
Array Instantiation
Once array is created specify its length with a constructor statement.
Constructor:
A constructor is a method that is called to initialize the object and variable. To instantiate (or create) an array, use the new keyword, followed by the square brackets containing the number of elements you want the array to have. For example,
//declaration int grade[]; //instantiate object grade = new int[50]; or, can also be written as, //declare and instantiate object int grade[] = new int[50];
You can also instantiate an array by directly initializing it with data. For example,
int arr_no[] = {1, 2, 3, 4, 5};
Multidimensional Arrays
Multidimensional arrays are implemented as arrays of arrays. Multidimensional arrays are declared by appending the appropriate number of bracket pairs after the array name. For example:
// integer array 200 x 300 elements int[][] twoDim = new int[200][300]; // character array 16 x 32 x 48 char[][][] threeDim = new char[16][32][48]; // String array 4 rows x 2 columns String[][] breed_color = {{ "terry", "brown" }, { "kristin", "white" }, { "toby", "gray"}, { "fido", "black"} };
NIIT
Java Handout 15
Definition: Object representations of simple variables that are not object variables. An instance of a wrapper contains, or wraps, a primitive value of the corresponding type. The wrappers are normal classes in the java.lang package that extend the Object superclass like all Java classes. Other than for the primitive type int, the wrappers come with the same name as the corresponding primitive type except that the first letter is capitalized: o Integer is a wrapper class of the primitive int o Character is a wrapper class of the primitive char o Double is a wrapper class of the primitive double
Autoboxing
The autoboxing feature added to Java 5.0 does the conversion (wrapping) from primitive to wrapper object.
16 Java Handout NIIT
This "wrapping" is called "autoboxing" in the sense that the primitive value is automatically "boxed up" into the wrapper object. Autoboxing is available for all the primitive or wrapper types.
Method Arguments
If a method takes a wrapper type, then you can pass a reference to a wrapper or a primitive of the matching type. If a method takes a primitive, then you can pass in either a compatible primitive or a reference to a wrapper of that primitive type.
Example: void takeNumber(Integer i) { }
Return Values
If a method declares a primitive return type, then you can return either a compatible primitive or a reference to the wrapper of that primitive type. If a method declares a wrapper return type, then you can return either a reference to the wrapper type or a primitive of the matching type. Example:
int giveNumber() { return x; }
In the preceding example, x can be either a reference to Integer wrapper or int primitive type.
Control Structures
Control structures allows you to change the ordering of how the statements in your programs are executed Two types of control structures are: Decision control structures: Allows you to select specific sections of code to be executed Repetition control structures: Allows you to execute specific sections of the code a number of times.
NIIT
Java Handout 17
Decision control structures are Java statements that allows you to select and execute specific blocks of code on the basis of condition. Types of decision control structures are: if-statement if-else-statement if-else if-statement
if-statement
if-statement specifies that a statement (or block of code) will be executed if and only if a certain boolean statement is true. if-statement has the form:
if( boolean_expression ) statement or if( boolean_expression ){ statement1; statement2; }
switch Statement
switch allows branching on multiple outcomes. Its a substitute of if-else. switch statement has the form:
switch( switch_expression ){ case case_selector1: statement1;// statement2;//block 1 break; case case_selector2: statement1;// statement2;//block 2 break; : default: statement1;//
18 Java Handout NIIT
statement2;//block n }
while-loop
Statement written in the while loop block are executed till the condition is satisfied. while loop has the following form:
while( boolean_expression ){ statement1; statement2; . . . }
do-while-loop
It is similar to while loop. But block of statements will be executed at least once. After that it will execute the statements based on the condition is true. do-while loop has the following form:
do{ statement1; statement2; . . . }while( boolean_expression );
for-loop
for loop allows execution of the same code a number of times. for loop has the following form:
for(InitializationExpression;LoopCondition;StepExpression) { statement1; statement2; . . .
NIIT Java Handout 19
Branching Statements
Branching statements allows you to redirect the flow of program execution. Java offers three branching statements: break continue return
Constructors
Java provides a special construct named constructor exclusively for creating an object of a class and initializing its instance variables. Constructors should have the same name as the name of the class. It is generally declared as public. It may have optional list of arguments. It does not have any return type and not even void. You cannot invoke a constructor on an existing object. You can use a constructor only in combination with the new operator.
Declaring Methods
To declare methods you write,
<modifier> <returnType>
20 Java Handout NIIT
<name>(<parameter>*) { <statement>* }
Where: <modifier> can carry a number of different modifiers <returnType> can be any data type (including void) <name> can be any valid identifier <parameter> can be one or more parameters passed as argument to the method. Each <parameter> is associated with a parameter type (primitive or object) and a parameter name.
Static Methods
Example:
public class StudRec { private static int studentCount; public static int getStudentCount(){ return studentCount; } }
Where: public means that the method can be called from objects outside the class.
NIIT
Java Handout 21
static means that the method is static and should be called by typing, [ClassName].[methodName]. For example, in this case, you call the method StudRec.getStudentCount() int is the return type of the method. This means that the method should return a value of type int. getStudentCount is the name of the method. () means that your method does not have any parameters.
Method Overloading
Method overloading: It allows a method with the same name but different parameters, to have different implementations and return values of different types It is used when the same operation has different implementations
Access Modifiers
Access modifiers are used to define the scope of a variable or method or class. There are four different types of access modifiers in Java: public (Least restrictive) protected default private (Most restrictive)
public Accessibility
Public access: Specifies that class members (variables or methods) are accessible to anyone, both inside and outside the class and outside of the package Any object that interacts with the class can have access to the public members of the class Keyword: public
22 Java Handout
NIIT
protected Accessibility
Protected access: Specifies that the class members are accessible only to methods in that class and the subclasses of the class The subclass can be in different packages Keyword: protected
default Accessibility
Default access: Specifies that only classes in the same package can have access to the variables and methods of the class No actual keyword is their for the default modifier and it is applied in the absence of an access modifier
private Accessibility
Private accessibility: Specifies that the class members are only accessible by the class in which they are defined Keyword: private
Inheritance
Inheritance is the concept, used to inherit the variables and methods defined in the parent class (super class) in the child class (sub class). Generalized variables and methods are defined in the super class and specialized variables and methods are defined in the sub class.
NIIT
Java Handout 23
Deriving a Subclass
The extends keyword is used to inherit the class. Suppose you have a parent class called Automobile.
public class Automobile { protected String brandname; protected String address; /** * Default constructor */ public Automobile (){ System.out.println(Inside Automobile:Constructor); brandname = ""; address = ""; } . . . . }
extends Keyword
Now, you want to create another class named Car. Since a car is also an automobile, therefore, use the extend keyword to inherit all the properties and methods of the existing class Automobile.
Use of Subclass
A subclass inherits all of the public and protected members (fields or methods) of its parent, no matter what package the subclass is in. If the subclass is in the same package as its parent, then it also inherits the package-private members (fields or methods) of the parent.
Fields
The inherited fields can be used directly, just like any other fields. You can declare new fields in the subclass that are not in the super class. You can declare a field in the subclass with the same name as the one in the super class, thus hiding it (not recommended).
24 Java Handout
NIIT
A subclass does not inherit the private members of its parent class. However, if the super class has public or protected methods for accessing its private fields, these can also be applied by the subclass.
Methods
The inherited methods can be used directly as they are. You can write a new instance method in the subclass that has the same signature as the one in the super class, thus overriding it. You can write a new static method in the subclass that has the same signature as the one in the super class, thus hiding it. You can declare new methods in the subclass that are not in the super class.
Object Class
Object class is mother of all classes. In Java language, all classes are subclassed (extended) from the Object super class. Object class is the only class that does not have a parent class Object class defines and implements behavior common to all classes including the ones that you write. Following are some of the important methods of the Object class: o getClass() o equals() o toString()
In the code, you create an object of class Car. The output of the program is: Inside Automobile:Constructor Inside Automobile:Constructor Example: Constructor Calling Chain
Few things to remember when using the super constructor call: The super() call must occur as the first statement in a constructor. The super() call can only be used in a constructor (not in ordinary methods). Another use of super is to refer to members of the super class (just like the this reference ). For example:
public Car() { super.brandname = somename; super.address = some address; }
Overriding Methods
If a derived class needs to have a different implementation of a certain instance method from the super class, then override that instance method in the sub class. The overriding concept applies only to instance methods. For static methods, it is called hiding methods. The overriding method has the same name, number and type of parameters, and return type as the method it overrides.
NIIT
26 Java Handout
Now, when you invoke the getName() method of an object of the subclass Car, the getName() method of the Car class would be called, and the output would be: Car: getName
Hiding Methods
If a subclass defines a class method (static method) with the same signature as a class method in the super class, then the method in the subclass hides the one in the super class.
System.out.println("The class method in Animal."); } } // The testClassMethod() of the child class hides the one of // the super class it looks like overriding, doesn't it? class Cat extends Animal { public static void testClassMethod() { System.out.println("The class method in Cat."); } }
Abstract Methods
Methods that do not have implementation (body) are called abstract methods. To create an abstract method, just write the method declaration without the body and use the keyword abstract. No { } Please make this point that there are no parentheses will be available. For example,
// Note that there is no body public abstract void someMethod();
Abstract Class
An abstract class is a class that contains one or more abstract methods. An abstract class cannot be instantiated. You will get a compile error on the following code
MyAbstractClass a1 = new MyAbstractClass();
Another class (Concrete class) has to provide implementation of abstract methods: o Concrete class has to implement all abstract methods of the abstract class in order to be used for instantiation o Concrete class uses extends keyword
What is an Interface
All methods of an interface are abstract methods: Defines the signatures of a set of methods, without the body (implementation of the methods). A concrete class must implement the interface (all the abstract methods of the Interface). It allows classes, regardless of their locations in the class hierarchy, to implement common behaviours.
Example 1: Interface
// Note that Interface contains just set of method // signatures without any implementations. // No need to say abstract modifier for each method // since it assumed. public interface Relation { public boolean isGreater( Object a, Object b); public boolean isLess( Object a, Object b); public boolean isEqual( Object a, Object b); }
NIIT
Java Handout 29
Interfaces have no direct inherited relationship with any particular class, they are defined independently. Interfaces themselves have inheritance relationship among themselves.
Implicit Casting
30 Java Handout NIIT
Suppose you want to store a value of int data type to a variable of data type double.
int numInt = 10; double numDouble = numInt; //implicit cast
In this example, as the data type (double) of the destination variable holds a larger value than the data type (int) of the value, the data is implicitly casted to the data type double of the destination variable. Implicit Casting: Example
int numInt1 = 1; int numInt2 = 2; //result is implicitly casted to type double double numDouble = numInt1/numInt2;
Explicit Casting
When you convert a data that has a large type to a smaller type, you must use an explicit cast. Explicit casts take the following form:
(Type)value
where, Type is the name of the type you are converting to and value is an expression that results in the value of the source type. Explicit Casting: Example
double valDouble = 10.12; int valInt = (int)valDouble; //convert valDouble to int type double x = 10.2; int y = 2; int result = (int)(x/y); //typecast result of operation to int
Casting Objects
Instances of classes can also be cast into instances of other classes, with one restriction. The source and destination classes must be related by inheritance. One class must be a subclass of the other. Casting objects is analogous to converting a primitive value to a larger type, some objects might not need to be cast explicitly.
NIIT Java Handout 31
(classname)object
where, classname is the name of the destination class and object is a reference to the source object. Casting Objects: Example The following example casts an instance of the class VicePresident to an instance of the class Employee. VicePresident is a subclass of Employee with more information, which here defines that the VicePresident has executive room.
Employee emp = new Employee(); VicePresident veep = new VicePresident(); // no cast needed for upward use emp = veep; // must cast explicitly veep = (VicePresident)emp;
Inner Class
Inner class is a class declared within another class Accessing the members of the inner class: o Need to instantiate an object instance of an inner class first Example:
innerObj.innerMember = 5; //innerObj is an instance of the inner class //innerMember is a member of the inner class
32 Java Handout
8 }
public static void main(String args[]) { OuterClass1 ocobj = new OuterClass1(); InnerClass1 icobj = ocobj.new InnerClass1(); System.out.println(ocobj.data); System.out.println(icobj.data2); icobj.method(); } }
Anonymous Classes
It is common in Java programming to encounter situations where you need to create an object but do not need to bother giving it an explicit name.
NIIT
Java Handout 33
With the inner classes you can take this to another level by creating and instantiating a class without bothering to give it a name. This is called as an anonymous class. This anonymity eliminates a lot unnecessary named objects and makes the code more readable.
Exception
Exceptional event Error that occurs during run-time Cause normal program flow to be disrupted Examples are: Divide by zero errors Accessing the elements of an array beyond its range Invalid input Hard disk crash Opening a file that does not exist Heap memory exhausted
Exception Example
1 2 3 4 5 6 class DivByZero { public static void main(String args[]) { System.out.println(5/0); System.out.println(Display the output.); } }
Default exception handler: Provided by Java run time Prints out exception description Prints the stack trace: Hierarchy of methods where the exception occurred Causes the program to terminate
34 Java Handout NIIT
Exception class:
Error class:
o Out of memory errors o Hard disk crash Used by the Java run-time system to handle errors occurring in the run-time environment
An exception you throw is an object. You have to create an exception object in the same way you create any other object. Example:
throw new ArithmeticException(testing...);
Definition Returns the character located in the specified index. Compares this string with the specified
Java Handout 39
anotherString)
parameter. 1. It returns a negative value if passed string is less than the compared string. 2. It returns a positive value if passed string is greater than the compared string. 3. It returns a zero value if passed string is equal to the compared string. Like compareTo but ignores the case used in this string and the specified string. Returns true if compared and passed strings are same and both the objects are string objects. Returns false if compared and passed strings are not same and inspite of both the objects are string objects. Like equals but ignores the case used in this string and the specified string. Get the characters starting from the srcBegin index up to the srcEnd index and copies these characters to the dst array starting at the dstBegin index. Returns a length of the string. Returns the string wherein all occurences of the oldChar in the string is replaced with newChar. Returns the substring of the string starting from the specified beginIndex up to the endIndex index. Convert the string into character array and returns the same. Returns a string wherein the leading and trailing white space are removed. Takes in a simple data type such as boolean, integer, or character, or it takes in an object as a parameter and returns the String equivalent of the specified
NIIT
public int compareToIgnoreCase (String str) public boolean equals (Object anObject)
public boolean equalsIgnoreCase (String anotherString) public void getChars (int srcBegin, int srcEnd, char[] dst, int dstBegin) public int length() public String replace (char oldChar, char newChar) public String substring (int beginIndex, int endIndex) public char[] toCharArray() public String trim() public static String valueOf(-)
40 Java Handout
parameter.
public String Buffer delete(int start, int end) public StringBuffer insert(int offset,-)
NIIT
Java Handout 41
The String class defines a new constructor that enables you to construct a String from a StringBuilder as shown in the following code:
String(StringBuilder strBuildObj)
Collection
A collection object groups multiple elements into a single unit. Collections are used to store, retrieve, manipulate, and communicate aggregate data. Typically, they represent data items that form a natural group, such as a poker hand (a collection of cards), a mail folder (a collection of letters), or a telephone directory (a mapping of names to phone numbers).
Collection Framework
A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks contain the following: Interfaces Implementations Algorithms
Collection Interfaces
Collection interfaces are abstract data types that represent collections. Collection interfaces are in the form of Java interfaces. Interfaces allow collections to be manipulated independently of the implementation details of their representation, which is called the polymorphic behavior.
42 Java Handout NIIT
In Java programming language (and other object-oriented languages), interfaces generally form a hierarchy. You choose one that meets your need as a type.
Implementations
Implementations are the data objects used to store collections, which implement the interfaces. Java Collections Framework also provides several implementations for special purpose situations that require nonstandard performance, usage restrictions, or other unusual behavior.
Collection Interface
Collection interface is the root of the collection hierarchy. Collection interface is the least common denominator that all collections implement. Every collection object is a type of Collection interface. Collection interface is used to pass collection objects around and to manipulate them when maximum generality is desired. Apply Collection interface as a type. JDK (Java Development Kit) does not provide any direct implementations of this interface but provides implementations of more specific sub interfaces, such as Set and List.
Set Interface
The Set interface is a collection that does not allow duplicate elements. The Set interface models the mathematical set abstraction and is used to represent sets: Cards comprising a poker hand Courses making up the schedule of a student The processes running on a machine
Iterator<E> iterator(); // Bulk operations boolean containsAll(Collection<?> c); boolean addAll(Collection<? extends E> c); //optional boolean removeAll(Collection<?> c); //optional boolean retainAll(Collection<?> c); //optional void clear(); //optional // Array Operations Object[] toArray(); <T> T[] toArray(T[] a); }
HashSet
HashSet is much faster than TreeSet (constant-time versus log-time for most operations) but it does not arrange the data in specific order. HashSet is the most commonly used implementation.
TreeSet
The TreeSet is one of two sorted collections (the other being TreeMap). It does not allow duplicate data and it iterates in sorted order as ascending.
LinkedHashSet
LinkedHashSet is implemented as a hash table with a linked list running through it. It provides insertion-ordered iteration (least recently inserted to most recently) and runs nearly as fast as HashSet.
44 Java Handout NIIT
It spares its clients from the unspecified, generally chaotic ordering provided by HashSet without incurring the increased cost associated with TreeSet.
List Interface
List interface is an ordered collection (sometimes called a sequence). Lists can contain duplicate elements. The list elements are accessed by their integer index (position).
Map Interface
Map interface handles key or value pairs. A Map interface cannot contain duplicate keys. Each key can map to at most one value.
NIIT
Java Handout 45
SortedMap Interface
The SortedMap interface maintains the mappings in ascending key order. This is the Map analog of SortedSet. Sorted maps are used for naturally ordered collections of key or value pairs, such as dictionaries and telephone directories.
Queue Interface
Queue interface is a collection it holds multiple elements prior to processing.
NIIT
46 Java Handout
Apart from basic Collection operations, a Queue interface provides additional insertion, extraction, and inspection operations. Typically, but do not necessarily, Queue interface order elements in a FIFO (First-In, First-Out) manner.
Iterator: An Iterator is an object that enables you to traverse through a collection and to remove elements from the collection selectively, if desired.
Iterator Interface
public interface Iterator { boolean hasNext(); Object next(); void remove(); //optional }
hasNext() method returns true if the iteration has more elements. next() method returns the next element in the iteration. remove() is the only safe way to modify a collection during iteration. The behavior is unspecified if the underlying collection is modified in any other way while the iteration is in progress.
NIIT
Java Handout 47
It returns an iterator to the set of elements contained in the invoking object. Although the for-each form of the for loop was designed with arrays and collections in mind, it can be used to cycle through the contents of any object that implements the Iterable interface. This enables you to create classes whose objects can be applied with the foreach form of the for loop. This is a powerful feature that substantially increases the types of programming situations to which the for can be applied.
Threads
Threads are required to handle concurrent processes. Threads provide single sequential flow of control within a program. Example: o Operating System o HotJava Web browser
48 Java Handout
NIIT
Thread Priorities
Priorities determine, which thread receives CPU control and gets to be executed first. Priority ranging from one to 10. Higher the thread priority larger is the chance of being executed first Example: o Two threads are ready to run o First thread: priority of 5, already running o Second thread = priority of 10, comes in while first thread is running Context switch: Occurs when a thread snatches the control of CPU from another When more than one thread having highest priority is ready to run then decision which thread will be executed dependens on the operating system. o -sliced round-robin o control
Description Creates a new Thread object. Creates a new Thread object with the specified name. Creates a new Thread object based on a Runnable object, target refers to the object whose run method is called. Creates a new Thread object the specified name and based on a Runnable object.
NIIT
Java Handout 49
Description The maximum priority value, 10. The maximum priority value, 1. The default priority value,5.
50 Java Handout
NIIT
Runnable Interface
The Runnable interface should be implemented by any class whose instances are intended to be executed as a thread. The class must define run() method of no arguments. The run() method is like main() for the new thread. The Runnable interface provides the means for a class to be active while not subclassing Thread. A class that implements Runnable can run without subclassing Thread by instantiating a Thread instance and passing itself in as the target.
calls the notify or notifyAll method on this object. May throw InterruptedException. Wakes up a thread that called the wait method on the same object. Wakes up all threads that called the wait method on the same object.
Concurrency Utilities
List of Concurrency Utilities are: Task Scheduling Framework Callable's and Future's Synchronizers Concurrent Collections Atomic Variables Locks Nanosecond-granularity timing
52 Java Handout
NIIT
Executor Interface
Many Executor implementations impose some sort of limitation on how and when tasks are scheduled.
I/O Streams
An I/O Stream represents an input source or an output destination. A stream can represent many different kinds of sources and destinations like disk files, devices, other programs, a network socket, and memory arrays. Streams support many different kinds of data like simple bytes, primitive data types, localized characters, and objects.
NIIT Java Handout 53
Some streams simply pass on data, others manipulate and transform the data in useful ways. No matter how they work internally, all streams present the same simple model to programs that use them. A stream is a sequence of data.
Input Stream
A program uses an input stream to read data from a source, one item at a time.
Output Stream
A program uses an output stream to write data to a destination, one item at time.
54 Java Handout
Root classes of all output streams: o The OutputStream class o The Writer class
Description An overloaded method, which also has three versions like that of the Reader class, Reads bytes. Reads the next byte of data from this stream. Reads some number of bytes and store them in the bBuf byte array. Reads upto length number of bytes and stores them in the byte array bBuf starting at the specified offset. Closes this stream. Calling the other Inputstream methods after closing the stream would cause an IOException to occur.
Byte Stream
Programs use byte streams to perform input and output of 8-bit bytes. All byte stream classes are descended from InputStream and OutputStream. There are many byte stream classes like FileInputStream and FileOutputStream.
Character Stream
The Java platform stores character values using Unicode conventions. All character stream classes are descended from Reader and Writer.
NIIT Java Handout 55
The FileReader and FileWriter classes are used for I/O operations. Reader and Writer are the abstract superclasses for character streams in java.io package. They work with character streams rather than byte streams. The Reader and Writer classes were added to JDK 1.1 to support internationalization.
Buffered Streams
In unbuffered I/O means each read or write request is handled directly by the underlying OS. This can make a program much less efficient, because each such request often triggers disk access, network activity, or some other operation that is relatively expensive. To reduce this kind of overhead, the Java platform implements buffered I/O streams. Buffered input streams read data from a memory area known as a buffer. The native input API is called only when the buffer is empty. Similarly, buffered output streams write data to a buffer, and the native output API is called only when the buffer is full.
Object Streams
Object streams support I/O of objects: Like Data streams support I/O of primitive data types The object has to be of Serializable type The object stream classes are ObjectInputStream and ObjectOutputStream. These classes implement ObjectInput and ObjectOutput, which are sub interfaces of DataInput and DataOutput. An object stream can contain a mixture of primitive and object values.
56 Java Handout NIIT
JDBC
JDBC is a standard Java API for accessing relational database and hides database specific details from application.
JDBC API
The JDBC API is a Java API for accessing virtually any kind of tabular data. The JDBC API consists of a set of classes and interfaces written in the Java programming language that provide a standard API for tool/database developers and makes it possible to write industrial-strength database applications entirely in the Java programming language. Majority of JDBC API is located in java.sql package, which are DriverManager, Connection, ResultSet, DatabaseMetaData, ResultSetMetaData, PreparedStatement, CallableStatement and Types The javax.sql package provides many advanced functionalities. For example, an alternative to the DriverManager facility, a DataSource object is the preferred means of getting a connection. The DataSource interface is implemented by a driver vendor. With a basic implementation, the connection obtained through a DataSource object is identical to a connection obtained through the DriverManager facility.
JDBC Driver
JDBC driver is an implementation of JDBC interfaces that is specific to database. Every database server has corresponding JDBC drivers. JDBS allows: 1. Establish a connection with a data source. 2. Send queries and update statements to the data source. 3. Process the results.
NIIT
Java Handout 57
Database URL
Database URL is used to make a connection to the database and can contain server, port, protocol, and so on.
jdbc:subprotocol_name:driver_dependant_databasename: Oracle thin driver jdbc:oracle:thin:@machinename:1521:dbname:Derby jdbc:derby://localhost:1527/sample: Pointbase jdbc:pointbase:server://localhost/sample
58 Java Handout
NIIT
Transaction
One of the main benefits of using a PreparedStatement is executing the statements in a transactional manner. The committing of each statement when it is first executed is very time consuming. By setting AutoCommit to false, the developer can update the database more then once and then commit the entire transaction as a whole. Also, if each statement is dependent on the other, the entire transaction can be rolled back and the user is notified.
PreparedStatement
The contained SQL is sent to the database and compiled or prepared beforehand. From this point on, the prepared SQL is sent and this step is bypassed. The more dynamic statement requires this step on every execution. Depending on the DB engine, the SQL may be cached and reused even for a different PreparedStatement and most of the work is done by the DB engine rather than the driver. Instances of PreparedStatement contain an SQL statement that has already been compiled. This is what makes a statement "prepared. The SQL statement contained in a PreparedStatement object may have one or more IN parameters.
Java Handout 59
NIIT
An IN parameter is a parameter whose value is not specified when the SQL statement is created. Instead, the statement has a question mark (?) as a placeholder for each IN parameter. The ? is also known as a parameter marker or parameter placeholder. An application must set a value for each parameter marker in a prepared statement before executing the prepared statement. Because PreparedStatement objects are precompiled, their execution can be faster than that of Statement objects. Consequently, an SQL statement that is executed many times is often created as a PreparedStatement object to increase efficiency. Being a subclass of Statement, PreparedStatement inherits all the functionality of Statement. In addition, it adds a set of methods that are needed for setting the values to be sent to the database in place of the placeholders for IN parameters. Also, the three methods execute, executeQuery, and executeUpdate are modified so that they take no argument. The Statement forms of these methods (the forms that take an SQL statement parameter) cannot be used with a PreparedStatement object.
CallableStatement
CallableStatement is the interface used to execute SQL stored procedures. A stored procedure is a group of SQL statements that form a logical unit and perform a particular task. Stored procedures are used to encapsulate a set of operations or queries to execute on a database server. A CallableStatement object contains a call to a stored procedure. It does not contain the stored procedure itself. The following first line of code creates a call to the stored procedure SHOW_SUPPLIERS using the connection con. The part that is enclosed in curly braces is the escape syntax for stored procedures.
CallableStatementcs = con.prepareCall("{call SHOW_SUPPLIERS}"); ResultSetrs = cs.executeQuery();
60 Java Handout
NIIT