Core Java-Zulfikar Ali
-
Upload
alizulfikar -
Category
Documents
-
view
226 -
download
0
Transcript of Core Java-Zulfikar Ali
-
7/31/2019 Core Java-Zulfikar Ali
1/60
NIIT Java Handout 1
CORE JAVA
Object Oriented Programming
All the problems in real world mapped to OOP.OOP defines things (objects), which can either do something or have something
done to them.
OOP creates a type (class) for these objects which has properties and behavior.
OOP languages: Operations (verbs) are performed by or on Actors (objects), whichhave names and store data (nouns)
ObjectsAn 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 accessthe 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
-
7/31/2019 Core Java-Zulfikar Ali
2/60
2 Java Handout NIIT
OOP Features
Abstraction
A programmer should focus on the overall working of an object and ignore specificdetails regarding the inner-workings of an object. This concept is called abstraction.
EncapsulationAbstraction 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 thosemethods 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
InheritanceOne 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.
PolymorphismPolymorphism is a Greek word and its meaning many forms. In this case subclassescan 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.
-
7/31/2019 Core Java-Zulfikar Ali
3/60
NIIT Java Handout 3
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 OverloadingIn 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.
Features or Characteristics of JavaThe features of Java are:
Simple Object oriented
Secure
Platform independent
Robust
Portable
Automatic garbage collection
Dynamic
Multithreaded Distributed
Overview of Java Virtual Machine Java Virtual Machine (JVM) specification defines the JVM as an imaginary
(virtual) machine that is implemented by emulating it in software on a real
machine. Code for the JVM is stored in .class files.
-
7/31/2019 Core Java-Zulfikar Ali
4/60
4 Java Handout 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.
Java SE or J2SE Runtime Environment 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;
-
7/31/2019 Core Java-Zulfikar Ali
5/60
NIIT Java Handout 5
}
}
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 differentvalues 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 thekeyword 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 classname. 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 matchesthe 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.
-
7/31/2019 Core Java-Zulfikar Ali
6/60
6 Java Handout 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 Objectclass.
Few of the important methods of the Object class are as follows:
equals(Object obj) : Indicates whether some other object is "equal to" thisone 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
The main Method In Java, everything is written in a class. The source code file is saved with a .java
extension. This is then compiled into a new class file (with a .class extension)
When you run your program, you are really running a class.
While execution of program Java Virtual Machine (JVM) load the class andexecute its main() method. Keep running till all the code in main() method is
finished.
The main() method is a start-up method.
Every Java application should have at least one main() method.
The main() method will be written as shown in the following code:
public static void main (String[] args) {// Write the code here}
The System.out.println (SOP) Method The System class is available in the java.lang package.
The out is a field of the System class representing the standard output stream.
-
7/31/2019 Core Java-Zulfikar Ali
7/60
NIIT Java Handout 7
To write on console following statement is used:System.out.println(Sample Statement);
It inserts a new line after writing the statement on the console.
Code Structure in Java Write a class in a source file
Write methods in a class
Write statements in a method
Example/*** Sample program to print This is my first Java program**/class MyFirstProgram { // Declare class MyFirstProgramvoid displayMessage() {System.out.println("This is my first Java program");}
public static void main(String[] args) {MyFirstProgram myFirstProgram = new MyFirstProgram();myFirstProgram.displayMessage();}}
Save the preceding contents in a file called MyFirstProgram.java
Compile and Run a Java Program
Compile: To compile MyFirstProgram.java source file in a MS-DOS prompt, give the
following command:
javac MyFirstProgram.java
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 followingcommand:
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:
-
7/31/2019 Core Java-Zulfikar Ali
8/60
8 Java Handout NIIT
This is my first Java program
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 soon.
A list of Java keywords are as follows:
abstract Continue for new switch
assert Default goto package synchronizedboolean Do if private thisbreak Double implements protected throw
byte Else import public throwscase Enum instanceof return transientcatch Extends int short trychar Final interface static void
class Finally long strictfp volatile
const Float native super while
Java LiteralsLiterals 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
Java Literals: Integer
decimal (base 10)
hexadecimal (base 16)
octal (base 8)
Java Literals: Floating point
Represents decimals with fractional parts:
Example: 5.255
Can be expressed in standard or scientific notation:
Example: 583.45 (standard), 5.8345e2 (scientific)
-
7/31/2019 Core Java-Zulfikar Ali
9/60
NIIT Java Handout 9
Java Literals: Boolean
Boolean literals have only two values, true or false.
Java Literals: Character
Character Literals represent single Unicode characters. To use a character literal, enclose the character in single quote delimiter.
For example: The letter a, is represented as a.
Special characters such as a newline character, a backslash is usedfollowed by the character code. For example, \n for the newline
character, \r for the carriage return, and \b for backspace.
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.
Java Literals: String
String literals represent multiple characters and are enclosed by double
quotes.
An example of a string literal is, This is a sample.
Primitive Data TypesThe Java programming language defines eight primitive data types:
boolean (for logical)
char (for textual)
byte
short
int
long (integral)
double float (floating point)
Primitive Data Types: Logical-booleanA boolean data type represents two states of true and false.
An example is boolean result = true;
In the preceding statement, declared a variable named result as boolean type and
assigned it a value of true.
-
7/31/2019 Core Java-Zulfikar Ali
10/60
10 Java Handout NIIT
Primitive Data Types: Textual-charA character data type (char), represents a single Unicode character.
It must have its literal enclosed in single quotes( ).
For example the following code:
x //The letter x
\t //a tab
To represent special characters like ' (single quotes) or " (double quotes), use the
escape character \. For example the following code:
'\'' //for single quotes
'\"' //for double quotes
Primitive Data Types: Integralbyte, short, int, and, longIntegral data types in Java uses three forms of decimal, octal, or hexadecimal.
Examples are:
5// The decimal value 5
088 // The leading 0 indicates an octal value
0xBABB // The leading 0x indicates a hex value
Integral types has int as default data type.
A long value can be defined by appending the letter l or L.
For example: 20L
Integral data type have the following ranges:
Integer Length Name or Type Range
8 bits byte -27 to 27-1
16 bits short -215 to 215-132 bits int -231 to 231-1
64 bits long -263 to 263-1
Coding Guidelines: In defining a long value, a lowercase L is not recommended
because it is hard to distinguish from the digit 1.
-
7/31/2019 Core Java-Zulfikar Ali
11/60
NIIT Java Handout 11
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 itwill hold.
Declaring and Initializing Variables
Declare a variable as follows:
[=initial value];
Reference Variables Versus Primitive Variables
Two types of variables can be created in Java as Primitive and Reference.
Primitive Variables:
Variables with primitive data types such as int or long.
Stores data in the actual memory location of where the variable is present.
Reference Variables:
Variables that store the address in the memory locationPoints to another memory location where the actual data is present
When you declare a variable of a certain class, you are actually declaring a
reference variable to the object with that certain class.
Example of a reference variable and primitive variable
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
-
7/31/2019 Core Java-Zulfikar Ali
12/60
12 Java Handout NIIT
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.
-
7/31/2019 Core Java-Zulfikar Ali
13/60
NIIT Java Handout 13
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 anexplicit 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
-
7/31/2019 Core Java-Zulfikar Ali
14/60
14 Java Handout NIIT
/ - 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 typespecified by the right operand.
The instanceof operator cannot be used with primitive types (this results in a
compilation error).
Introduction to Arrays
Declaring Arrays
To declare an array, write the data type, followed by a set of square brackets[],
followed by the identifier name.
For example,int []ages;
or
int ages[];
-
7/31/2019 Core Java-Zulfikar Ali
15/60
NIIT Java Handout 15
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 ArraysMultidimensional 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 48char[][][] threeDim = new char[16][32][48];
// String array 4 rows x 2 columns
String[][] breed_color = {{ "terry", "brown" },
{ "kristin", "white" },
{ "toby", "gray"},
{ "fido", "black"}
};
-
7/31/2019 Core Java-Zulfikar Ali
16/60
16 Java Handout NIIT
The Wrapper Classes
Primitive data types are not objects: Cannot access methods of the Object class.
Only actual objects can access methods of the Object class.
Need of wrapper classes: Need an object representation for the primitive type.variables to apply methods that are in-built in Java.
Definition: Object representations of simple variables that are not object variables.
An instance of a wrapper contains, or wraps, a primitive value of thecorresponding type.
The wrappers are normal classes in the java.lang package that extend theObject 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 into Character is a wrapper class of the primitive charo Double is a wrapper class of the primitive double
Primitive Types: Wrapper ClassesThe following table lists the primitive types and the corresponding wrapper classes:
Primitive Wrapper
boolean java.lang.Boolean
byte java.lang.Byte
char java.lang.Character
double java.lang.Double
float java.lang.Float
int java.lang.Integer
long java.lang.Long
short java.lang.Short
void java.lang.Void
Autoboxing
The autoboxing feature added to Java 5.0 does the conversion (wrapping) from
primitive to wrapper object.
-
7/31/2019 Core Java-Zulfikar Ali
17/60
NIIT Java Handout 17
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 ArgumentsIf 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 ValuesIf a method declares a primitive return type, then you can return either a compatibleprimitive 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 intprimitive 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 tobe executed
Repetition control structures: Allows you to execute specific sections of the
code a number of times.
Decision Control Structures
-
7/31/2019 Core Java-Zulfikar Ali
18/60
-
7/31/2019 Core Java-Zulfikar Ali
19/60
NIIT Java Handout 19
statement2;//block n
}
Repetition Control Structures
Repetition control structures are Java statements which allows to execute specific
blocks of code a number of times.
Types of repetition control structures are:
while-loop
do-while loop
for-loop
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;
. . .
-
7/31/2019 Core Java-Zulfikar Ali
20/60
20 Java Handout NIIT
}
Branching StatementsBranching 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.
To declare a constructor, you write, (*) {
*
}
Default Constructor (Method)
Constructor without any parameters
If the class does not specify any constructors, then an implicit default constructor is
created.
Example: Default Constructor Method of StudRec Class
public StudRec(){
//some code here
}
Declaring MethodsTo declare methods you write,
-
7/31/2019 Core Java-Zulfikar Ali
21/60
NIIT Java Handout 21
(*) {
*
}
Where:
can carry a number of different modifiers
can be any data type (including void)
can be any valid identifier
can be one or more parameters passed as argument to the method.
Each is associated with a parameter type (primitive or object) and a
parameter name.
Accessor (Getter) Methods
Accessor methods:
Used to read values from your class variables (instance or static)
Usually written as get
It also returns a value
Mutator (Setter) MethodsMutator Methods:
Used to write or change values of your class variables (instance or static)Usually written as set
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.
-
7/31/2019 Core Java-Zulfikar Ali
22/60
22 Java Handout NIIT
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
-
7/31/2019 Core Java-Zulfikar Ali
23/60
NIIT Java Handout 23
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 AccessibilityPrivate accessibility:
Specifies that the class members are only accessible by the class in which theyare defined
Keyword:private
Java Program Structure: The Access Modifiersprivate default/package protected public
Same class Yes Yes Yes Yes
Same package Yes Yes Yes
Different package
(subclass)
Yes Yes
Different package
(non-subclass)
Yes
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 andspecialized variables and methods are defined in the sub class.
-
7/31/2019 Core Java-Zulfikar Ali
24/60
24 Java Handout NIIT
Deriving a SubclassThe 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.
To do this, you write,
public class Car extends Automobile {public Car(){
System.out.println(Inside Car:Constructor);}. . . .
}
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 thesuper class, thus hiding it (not recommended).
-
7/31/2019 Core Java-Zulfikar Ali
25/60
NIIT Java Handout 25
A subclass does not inherit the private members of its parent class. However, ifthe 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 signatureas 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 includingthe ones that you write.
Following are some of the important methods of the Object class:o getClass()o equals()
o toString()
How Constructor Method of a Super Class gets Called A subclass constructor invokes the constructor of the superclass implicitly.
When a Car object, a subclass (child class), is instantiated, the default
constructor of its super class (parent class), Automobile class, is invoked
implicitly before the constructor method of the subclass is invoked.
A subclass constructor can invoke the constructor of the super explicitly by
using the super keyword:o The constructor of the Car class can explicitly invoke the constructor ofthe Automobile class using super keyword
o Used when passing parameters to the constructor of the super class
Example: Constructor Calling ChainTo illustrate this, consider the following code:public static void main( String[] args ){
-
7/31/2019 Core Java-Zulfikar Ali
26/60
26 Java Handout NIIT
Car hondacity = new Car();}
In the code, you create an object of class Car.
The output of the program is:
Inside Automobile:ConstructorInside Automobile:Constructor
Example: Constructor Calling Chain
The super Keyword A subclass can also explicitly call a constructor of its immediate super class.
This is done by using the super constructor call.
A super constructor call in the constructor of a subclass will result in the
execution of relevant constructor from the super class, based on the arguments
passed. In the given the following code for Car:
public Car(){super( "BrandName", "Address" );System.out.println("Inside Car:Constructor");}
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 thisreference ).
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 instancemethod 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, andreturn type as the method it overrides.
-
7/31/2019 Core Java-Zulfikar Ali
27/60
NIIT Java Handout 27
Example: Overriding MethodsSuppose you have the following implementation for the getName method in the
Automobile super class:public class Automobile {:
:public String getName(){System.out.println("Parent: getName");return name;}}To override the getName() method of the superclass Automobile in thesubclass Car, reimplement the method with the same signature.public class Car extends Automobile{:public String getName(){
System.out.println("Car: getName");return name;}:}
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
Modifiers in the Overriding Methods The access specifier for an overriding method can allow more, but not less,
access than the overridden method. For example, a protected instance method
in the super class can be made public, but not private, in the subclass.
You will get a compile-time error if you attempt to change an instance methodin the super class to a class method in the subclass, or change the class method
to an instance method in the super class.
Hiding MethodsIf a subclass defines a class method (static method) with the same signature as a classmethod in the super class, then the method in the subclass hides the one in the super
class.
Example: Coding of Hiding Static Methodclass Animal {
public static void testClassMethod() {
-
7/31/2019 Core Java-Zulfikar Ali
28/60
28 Java Handout NIIT
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 thebody 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 bodypublic 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 codeMyAbstractClass 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 abstractclass in order to be used for instantiation
o Concrete class uses extends keyword
Sample Abstract Classpublic abstract class LivingThing {public void breath(){System.out.println("Living Thing breathing...");}public void eat(){System.out.println("Living Thing eating...");}/*** Abstract method walk()* We want this method to be implemented by a
-
7/31/2019 Core Java-Zulfikar Ali
29/60
NIIT Java Handout 29
* Concrete class.*/public abstract void walk();}
Extending An Abstract Class
When a concrete class extends the LivingThing abstract class, it must implement theabstract method walk() , or else, that subclass will also become an abstract class, and
therefore cannot be instantiated.
For example,public class Human extends LivingThing {public void walk(){System.out.println("Human walks...");}
}
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 theInterface).
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);}
Interface versus Abstract Class All methods of an interface are abstract methods while some methods of an
abstract class are abstract methods. Abstract methods of abstract class have
abstract modifier.
An interface can only define constants while abstract class can have fields.
-
7/31/2019 Core Java-Zulfikar Ali
30/60
30 Java Handout NIIT
Interfaces have no direct inherited relationship with any particular class, theyare defined independently. Interfaces themselves have inheritance relationship
among themselves.
When to use an Abstract Class Over Interface? For methods that are not abstract, you want to use them when you want to
provide common implementation code for all subclasses: Reducing the
duplication
For abstract methods, the motivation is the same with the ones in the interfaceto impose a common behavior for all subclasses without dictating how to
implement it.
Remember that a concrete can extend only one super class whether that superclass is in the form of concrete class or abstract class.
Using IS-A and HAS-AWhen one class inherits from another, you say that the subclass extends the super
class. When you want to know if one thing should extend another, use the IS-A test.
Examples for IS-A relationship:
Triangle IS-A Shape
Green IS-A Color
When two classes are related, but not through inheritance, (for example, one class has
a reference to another class) then you say that the two classes are joined by HAS-A
relationship. Examples for HAS-A relationship:
Bathroom HAS-A Tub
Tub HAS-A Bubble
Casting Primitive Types
Casting enables us to convert the value of one data type to another primitive type.
Commonly occurs between numeric types.
The boolean data type cannot be cast though.Types of Casting:
Implicit Casting
Explicit Casting
Implicit Casting
-
7/31/2019 Core Java-Zulfikar Ali
31/60
NIIT Java Handout 31
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.
-
7/31/2019 Core Java-Zulfikar Ali
32/60
32 Java Handout NIIT
(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
Accessing Members of Outer Class Within an Inner Class
Methods of the inner class can directly access members of the outer class:
Example:1 class Outer {
2 int outData;
3 class Inner {
4 void inMeth() {
5 outData = 10;
6 }
7 }
-
7/31/2019 Core Java-Zulfikar Ali
33/60
NIIT Java Handout 33
8 }
Java Program Structure: Inner Classes
class OuterClass1 {
int data = 5;
class InnerClass1 {
int data2 = 10;
void method() {
System.out.println(data);
System.out.println(data2);
}
}
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();
}
}
Static Nested Classes A static nested class is just a class enclosed within another class, and marked
with the keyword static.
Static nested classes are considered a member of the enclosing or outer class.
Static nested classes can access only the private static members of the outerclass.
Static nested class is not connected to an instance of the outer class.
Static nested class cannot access the variables that are not static and methods of
the outer class.
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.
-
7/31/2019 Core Java-Zulfikar Ali
34/60
34 Java Handout NIIT
With the inner classes you can take this to another level by creating andinstantiating 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.
ExceptionExceptional 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 class DivByZero {
2 public static void main(String args[]) {
3 System.out.println(5/0);
4 System.out.println(Display the output.);
5 }
6 }
Example: Default Exception Handling
Displays this error message:
Exception in thread "main java.lang.ArithmeticException: / by zero
at DivByZero.main(DivByZero.java:3)
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
-
7/31/2019 Core Java-Zulfikar Ali
35/60
NIIT Java Handout 35
What Happens when an Exception Occurs? When an exception occurs within a method, the method creates an exception
object and hands it off to the run-time system. This is called throwing an
exception. Exception object contains information about the error, type of exception and
the state of the program when the error occurred.
The run time system searches the call stack for a method that contains anexception handler.
When an appropriate handler is found, the run-time system passes theexception to the handler.
o An exception handler is considered appropriate if the type of theexception object thrown matches the type that can be handled by the
handler.o The exception handler chosen is said to catch the exception.o If the run-time system exhaustively searches all the methods on the call
stack without finding an appropriate exception handler, then the run-
time system (and, consequently, the program) terminates and uses the
default exception handler.
Benefits of Java Exception Handling Framework
The benefits of Java Exception Handling Framework are: Separating Error-Handling code from regular business logic code
Propagating errors up the call stack
Grouping and differentiating error types
Exception Class Hierarchy
The Throwable, Exception, and Error classes:
Throwable class:
Root class of exception classes
Immediate subclasses:
Error
Exception
Exception class:
-
7/31/2019 Core Java-Zulfikar Ali
36/60
36 Java Handout NIIT
o Division by zero erroro Array out-of-bounds error
Error class: Used by the Java run-time system to handle errors occurring in the run-time
environment
o Out of memory errorso Hard disk crash
Catching Exceptions: The try-catch StatementsSyntax of try-catch statements:try {
} catch ( ) {
}
...
} catch ( ) {
}
1 class DivByZero {
2 public static void main(String args[]) {
3 try {
4 System.out.println(5/0);
5 System.out.println(Display the output.);
6 } catch (ArithmeticException exc) {
7 //Division by zero is an ArithmeticException
8 System.out.println(exc);9 }
10 System.out.println(After exception.);
11 }
12 }
Throwing Exceptions: The throw Keyword
-
7/31/2019 Core Java-Zulfikar Ali
37/60
NIIT Java Handout 37
Java allows you to throw exceptions (generate exceptions).throw ;
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...);
Example: Throwing Exceptions
class ThrowExample {
public static void main(String args[]){
String input = "invalid input";
try {
if (input.equals("invalid input")) {throw new RuntimeException("throw example");
} else {
System.out.println(input);
}
System.out.println("After throwing");
} catch (RuntimeException e) {
System.out.println("Exception caught:" + e);
}
}
}
Using Java Exception Handling
Any checked exceptions that can be thrown within a method must be specified in its
throws clause.function1 {
try {
call function2;
} catch (Exception ex) {
doErrorProcessing;
}
}
function2 throws Exception {
call function3;
}
function3 throws Exception {
call readDataFile;
-
7/31/2019 Core Java-Zulfikar Ali
38/60
38 Java Handout NIIT
}
Checked and Unchecked Exceptions
Checked exception:
Java compiler checks if the program either catches or lists the occurringchecked exception
If not, then compilation error will occur
Unchecked exceptions:
Not subjected to checking at the time of compilation for exception handling
Built-in unchecked exception classes:o Error
o RuntimeExceptiono Their subclasses
Handling all these exceptions may make the program cluttered and maybecome a nuisance
Creating Your Own Exception Class
Steps to follow for creating your own exception class are:
1. Create a class that extends the RuntimeException or the Exception (Base class)
class.2. Customize the class: Members and constructors may be added to the class.
Example:class MyExceptionClass extends RuntimeException {
/* some code */
}
How to use Your own Exceptions
class TestExceptionClass {
public static void main(String args[]) {
String input = "invalid input";
try {
if (input.equals("invalid input")) {
throw new MyExceptionClass();
}
System.out.println("Good string.");
-
7/31/2019 Core Java-Zulfikar Ali
39/60
NIIT Java Handout 39
} catch (MyExceptionClass e) {
System.out.println("Bad string!");
}
}
}
The String Class
The String class represents collection of character literals. It can be represented as
array of characters.
Note: A String object is different than an array of characters.
The String Class: Constructors
1 class StringConstructorsExample {
2 public static void main(String args[]) {
3 String s1 = new String(); //empty string
4 char chars[] = { 'h', 'e', 'l', 'l', 'o'};
5 String s2 = new String(chars); //s2="hello";
6 byte bytes[] = { 'w', 'o', 'r', 'l', 'd' };
7 String s3 = new String(bytes); //s3="world"
8 String s4 = new String(chars, 1, 3);
9 String s5 = new String(s2);10 String s6 = s2;
11 System.out.println(s1);
12 System.out.println(s2);
13 System.out.println(s3);
14 System.out.println(s4);
15 System.out.println(s5);
16 System.out.println(s6);
17 }
18 }
The String Class: MethodsThe methods of String class are:
Method Definitionpublic char charAt (int index) Returns the character located in the
specified index.public int compareTo (String Compares this string with the specified
-
7/31/2019 Core Java-Zulfikar Ali
40/60
40 Java Handout NIIT
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 comparedstring.
3.It returns a zero value if passed string
is equal to the compared string.
public int compareToIgnoreCase
(String str)Like compareTo but ignores the case used
in this string and the specified string.public boolean equals (Object
anObject)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.public boolean equalsIgnoreCase
(String anotherString)Like equals but ignores the case used in
this string and the specified string.public void getChars (int
srcBegin, int srcEnd, char[] dst,
int dstBegin)
Get the characters starting from the
srcBegin index up to the srcEnd index and
copies these characters to the dst arraystarting at the dstBegin index.
public int length() Returns a length of the string.public String replace (char
oldChar, char newChar)Returns the string wherein all occurences
of the oldChar in the string is replaced
with newChar.public String substring (int
beginIndex, int endIndex)Returns the substring of the string starting
from the specified beginIndex up to the
endIndex index.
public char[] toCharArray() Convert the string into character array andreturns the same.
public String trim() Returns a string wherein the leading and
trailing white space are removed.public static String valueOf(-) Takes in a simple data type such as
boolean, integer, or character, or it takesin an object as a parameter and returns the
String equivalent of the specified
-
7/31/2019 Core Java-Zulfikar Ali
41/60
NIIT Java Handout 41
parameter.
The StringBuffer Class
There is a problem with String objects as once they are created they cannot be
modified because String is a final class.
A StringBuffer object is same as String object. But its mutable and can be modified.
Like length and content may get changed through some method calls.
The StringBuffer Class: Methods
Method Definition
public int capcity() Returns the current capacity of theStringBuffer object.
public StringBuffer append(-) Append the passed parameter value.
public char charAt(int index) Returns the character located at the
specified index value.
public void getChars(int srcBegin, int
srcEnd, char[] dst, int dstBegin)
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.
public String Buffer delete(int start, intend) Delete the characters from within the range.
public StringBuffer insert(int offset,-) Insert the value at the specified offset.
The java.lang.StringBuilder Class J2SE5.0 added the StringBuilder class, which is a drop-in replacement for
StringBuffer in cases where thread safety is not an issue. It should be used when
multithreading implementation is required.
The StringBuilder is not synchronized therefore it offers faster performance than
StringBuffer. As a best practice we should apply StringBuilder instead of StringBuffer. The
J2SE 5.0 javac compiler normally uses StringBuilder instead of StringBuffer
whenever you perform string concatenation as in System.out.println("The result is
" + result);
All the methods available on StringBuffer are also available on StringBuilder, soit really is a drop-in replacement.
-
7/31/2019 Core Java-Zulfikar Ali
42/60
42 Java Handout NIIT
The String class defines a new constructor that enables you to construct a Stringfrom a StringBuilder as shown in the following code:
String(StringBuilder strBuildObj)
CollectionA 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 manipulatingcollections.
All collections frameworks contain the following:
Interfaces
Implementations
Algorithms
Benefits of Collection Framework
The benefits of collection framework are:
Reduces programming effort
Increases program speed and quality
Allows interoperability among unrelated APIs: The collection interfaces are thevernacular by which APIs pass collections back and forth
Reduce effort to learn and use new APIs
Reduces effort to design new APIs
Fosters software reuse: New data structures that conform to the standard
collection interfaces are by nature reusable
Collection InterfacesCollection interfaces are abstract data types that represent collections. Collectioninterfaces 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.
-
7/31/2019 Core Java-Zulfikar Ali
43/60
-
7/31/2019 Core Java-Zulfikar Ali
44/60
44 Java Handout NIIT
Iterator iterator();
// Bulk operations
boolean containsAll(Collection c);
boolean addAll(Collection c); //optional
boolean retainAll(Collection c); //optionalvoid clear(); //optional
// Array Operations
Object[] toArray();
T[] toArray(T[] a);
}
Implementations of Set InterfaceThe implementations of Set interface are:
HashSet
TreeSet
LinkedHashSet
HashSetHashSet 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.
Caveats of Using HashSet
Iteration is linear in the sum of the number of entries and the number of buckets (the
capacity):
Choosing an initial capacity that is too high, can waste both space and time
Choosing an initial capacity that is too low, wastes time by copying the data
structure each time it is forced to increase its capacity
TreeSetThe 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.
LinkedHashSetLinkedHashSet 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.
-
7/31/2019 Core Java-Zulfikar Ali
45/60
NIIT Java Handout 45
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).
Additional Operations Supported by List Interface over
Collection
The additional operations supported by List interface over Collection interface are:
Elements are accessed based on the numerical position in the list.
Search searches for a specified object in the list and returns its numerical
position.
Iteration extends Iterator semantics adds an advantage of the sequential nature
of the list.
Range-view performs arbitrary range operations on the list.
Implementations of List InterfaceThe implementations of List interface are:
ArrayList:
o Offers constant-time positional accesso Provides fast iteration and fast random accesso Ordered collection (by index), but not sortedo Most commonly used implementation
LinkedList: It allows to add elements to the beginning of the List or iterate
over the List to delete elements from its interior.
Map InterfaceMap interface handles key or value pairs.
A Map interface cannot contain duplicate keys. Each key can map to at most one
value.
-
7/31/2019 Core Java-Zulfikar Ali
46/60
46 Java Handout NIIT
Map Interface (Java SE 5)public interface Map {// Basic operationsV put(K key, V value);V get(Object key);
V remove(Object key);boolean containsKey(Object key);boolean containsValue(Object value);int size();boolean isEmpty();// Bulk operationsvoid putAll(Map
-
7/31/2019 Core Java-Zulfikar Ali
47/60
NIIT Java Handout 47
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.
Implementations of Queue Interface
General purpose Queue implementations:
LinkedList implements the Queue interface, provides FIFO queue operationsfor addition, polling, etc.
PriorityQueue class is a priority queue based on the heap data structure.
The order of elements can be specified at the time of construction which can be
the natural order of the elements or the order imposed by an explicitComparator.
Two Schemes of Traversing Collections
There are two ways of traversing collections are:
for-each: The for-each construct allows you to concisely traverse a collection or array
using a for loopfor (Object o: collection)
System.out.println(o);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. Thebehavior is unspecified if the underlying collection is modified in any other
way while the iteration is in progress.
-
7/31/2019 Core Java-Zulfikar Ali
48/60
48 Java Handout NIIT
Use Iterator Over for-eachIterator is used over for-each for removing the current element:
The for-each construct hides the iterator, so you cannot call remove.
Therefore, the for-each construct is not usable for filtering.static void filter(Collection c) {
for (Iterator it = c.iterator(); it.hasNext(); )
if (!cond(it.next()))
it.remove();
}
Iterating over multiple collections in parallel.
The Iterable Interface Iterable is a generic interface that was added by Java 2, v5.0.
A class must implement Iterable whenever an object needs to be used within a
for-each style for loop in that class. Iterable has the following declaration:
interface Iterable
It defines one method, iterator(), as shown here:
Iterator iterator()
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 andcollections 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 for-
each form of the for loop.
This is a powerful feature that substantially increases the types of programmingsituations 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 Systemo HotJava Web browser
-
7/31/2019 Core Java-Zulfikar Ali
49/60
NIIT Java Handout 49
Multi-Threading in Java Platform Every application has at least one thread which is called default thread. It may
use several threads. For example, system threads that do things like memory
management and signal handling.
An application has one thread, called the main thread. Using this thread otherthread can be created.
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 runo First thread: priority of 5, already runningo 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 thendecision which thread will be executed dependens on the operating system.
o -sliced round-robino control
The Thread Class: ConstructorThe Thread class has eight constructors. Some of the important constructors are as
follows:
Method Description
Thread() Creates a new Thread object.
Thread(String name) Creates a new Thread object with the specified
name.
Thread(Runnable target) Creates a new Thread object based on a Runnableobject, target refers to the object whose run method
is called.
Thread(Runnable target,String name)
Creates a new Thread object the specified name andbased on a Runnable object.
-
7/31/2019 Core Java-Zulfikar Ali
50/60
50 Java Handout NIIT
The Thread Class: ConstantsThe Thread class contains fields for priority values.
Method Description
public final static int
MAX_PRIORITY
The maximum priority value, 10.
public final static intMIN_PRIORITY
The maximum priority value, 1.
public final static intNORM_PRIORITY
The default priority value,5.
The Thread Class: MethodsSome Thread methods of Thread class are as follows:
Thread Methods Descriptionpublic static ThreadcurrentThread()
Returns a reference to the thread that is
currently running.public final String getName() Returns the name of this method.public final void setName(Stringname)
Renames the thread to the specified
argument name. May throw
SecrityException.public final int get Priority() Returns the priority assigned to this thread.public final Boolean isAlive() Indicates whether this thread is running or
not.
Two Ways of Creating and Starting a Thread
The two ways of creating and starting a thread are:
Extending the Thread class
Implementing the Runnable interface
Extending Thread ClassThe subclass extends Thread class and the subclass overrides the run() method of
Thread class.
An object instance of the subclass can then be created.
Calling the start() method of the object instance starts the execution of the thread. Java
runtime starts the execution of the thread by calling run() method of object instance.
-
7/31/2019 Core Java-Zulfikar Ali
51/60
NIIT Java Handout 51
Two Schemes of Starting a Thread from a SubclassThe two schemes of starting a thread from a subclass are:
The start() method is not in the constructor of the subclass. The start() method needs to
be explicitly invoked after object instance of the subclass is created in order to start the
thread.The start() method is in the constructor of the subclass. Creating an object instance of
the subclass will start the thread.
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.
Extending Thread versus Implementing Runnable InterfaceSelecting between Thread and Runnable interface is depends on the user.
Implementing the Runnable interface: In this case declare a Thread object, call the
Thread methods on this object.
Extending the Thread class: It is easy to implement and the class which need to
implement the thread, should be extended from Thread class.
Synchronization: Locking an ObjectA thread is synchronized by becoming an owner of the monitor of the object: Consider
it as locking an object.
A thread becomes the owner of the monitor of the object in one of following ways:
Option 1: Use synchronized method
Option 2: Use synchronized statement on a common object
Inter-thread Communication: Methods from Object ClassMethods Description
public final void wait() Causes this thread to wait until some other thread
-
7/31/2019 Core Java-Zulfikar Ali
52/60
52 Java Handout NIIT
calls the notify or notifyAll method on this
object. May throw InterruptedException.Public final void notify() Wakes up a thread that called the wait method on
the same object.Public final void
notifyAll()
Wakes up all threads that called the wait method
on the same object.
Concurrency Utilities: JSR-166 Concurrency utilities enable development of simple yet powerful multi-
threaded applications. Like Collection it provides rich data structure handling
capability.
It beats C performance in high-end server applications.
It provides richer set of concurrency building blocks. The wait() , notify() , and
synchronized methods are too primitive. It enhances scalability, performance, readability, and thread safety of Java
applications.
Why Use Concurrency UtilitiesConcurrency utilities are used because:
It reduces the programming effort.
It increases the performance.
It increases the reliability and eliminate threading hazards such as deadlock,starvation, race conditions, or excessive context switching are eliminated
It improves the maintainability.
It increases the productivity.
Concurrency Utilities
List of Concurrency Utilities are:
Task Scheduling Framework
Callable's and Future's
Synchronizers
Concurrent Collections
Atomic Variables
Locks
Nanosecond-granularity timing
-
7/31/2019 Core Java-Zulfikar Ali
53/60
NIIT Java Handout 53
Task Scheduling Framework Executor /ExecutorService/Executors framework supports:
o Standardizing invocationo Scheduling
o
Executiono Control of asynchronous tasks according to a set of execution policies
Executor is an interface
ExecutorService extends Executor
Executors is factory class for creating various kinds of ExercutorServiceimplementations
Executor Interface Executor interface provides a way of de-coupling task submission from the
execution.
Execution: Mechanics of how each task will be run, including details of threaduse and scheduling.
Example:Executor executor = getSomeKindofExecutor();executor.execute(new RunnableTask1());executor.execute(new RunnableTask2());
Many Executor implementations impose some sort of limitation on how andwhen tasks are scheduled.
Callables and Futures Callable thread (Callee) implements Callable interface: Implement call()method rather than run()
Calling thread (Caller) submits Callable object to Executor and then moves onthrough submit() and not execute()
The submit() returns a Future object
Calling thread (Caller) retrieves the result using get() method of Future object:
If result is ready, then it is returned
If result is not ready, then calling thread will block
I/O StreamsAn 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.
-
7/31/2019 Core Java-Zulfikar Ali
54/60
54 Java Handout NIIT
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 StreamA program uses an input stream to read data from a source, one item at a time.
Output StreamA program uses an output stream to write data to a destination, one item at time.
General Stream Types
The general stream types are:Character and Byte Streams: Character streams are the streams that read and write
16-bit characters whereas Byte streams are the streams that read and write 8-bit bytes.Input and Output Streams: Based on source or destinationNode and Filter Streams: Whether the data on a stream is manipulated or
transformed or not.
Character and Byte Streams Byte streams: For binary data
Root classes for byte streams:o The InputStream classo The OutputStream classo Both classes are abstract
Character streams: For Unicode characters
Root classes for character streams:
o The Reader classo The Writer classo Both classes are abstract
Input and Output Streams Input or source streams: Can read from these streams
Root classes of all input streams:
o The InputStream classo The Reader class
Output or sink (destination) streams: Can write to these streams
-
7/31/2019 Core Java-Zulfikar Ali
55/60
NIIT Java Handout 55
Root classes of all output streams:
o The OutputStream classo The Writer class
InputStream Abstract ClassMethods Descriptionpublic int read(-) throwsIOException
An overloaded method, which also has
three versions like that of the Reader
class, Reads bytes.public abstract int read() Reads the next byte of data from this
stream.public int read(byte[] bBuf) Reads some number of bytes and store
them in the bBuf byte array.public abstract int read(char[]cbuf, int offset, int length) Reads upto length number of bytes andstores them in the byte array bBuf starting
at the specified offset.public abstract void close()throws IOException
Closes this stream. Calling the other
Inputstream methods after closing the
stream would cause an IOException to
occur.
Byte StreamPrograms 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.
When not to use Byte StreamByte Stream represents a kind of low-level I/O that you should avoid:
If the data contains character data, then the best approach is to use character streams.
There are also streams for more complicated data types.Byte streams should only be used for the most primitive I/O.
All other streams are based on byte stream.
Character StreamThe Java platform stores character values using Unicode conventions.
All character stream classes are descended from Reader and Writer.
-
7/31/2019 Core Java-Zulfikar Ali
56/60
-
7/31/2019 Core Java-Zulfikar Ali
57/60
NIIT Java Handout 57
The File ClassThe File class is not a stream class.
The File class is important because stream classes manipulate File objects.
The File class is an abstract representation of actual files and directory pathname.
JDBC
JDBC is a standard Java API for accessing relational database and hides databasespecific 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 Javaprogramming 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 areDriverManager, 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 DataSourceobject 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.
-
7/31/2019 Core Java-Zulfikar Ali
58/60
-
7/31/2019 Core Java-Zulfikar Ali
59/60
NIIT Java Handout 59
TransactionOne 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 onceand 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.
JDBC Transaction Methods
The JDBC transaction methods are:
setAutoCommit() : If set true, every executed statement is committed
immediately commit() :
o Relevant only if setAutoCommit(false)o Commit operations performed because the opening of a Connection or
last commit() or rollback() calls
rollback() :o Relevant only if setAutoCommit(false)o Cancels all operations performed
Prepared and Callable StatementsPreparedStatement: SQL is sent to the database and compiled or prepared beforehand
CallableStatement: Executes SQL Stored Procedures
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 beencompiled. This is what makes a statement "prepared.
The SQL statement contained in a PreparedStatement object may have one ormore IN parameters.
-
7/31/2019 Core Java-Zulfikar Ali
60/60
An IN parameter is a parameter whose value is not specified when the SQLstatement is created.
Instead, the statement has a question mark (?) as a placeholder for each INparameter.
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 befaster than that of Statement objects.
Consequently, an SQL statement that is executed many times is often created asa PreparedStatement object to increase efficiency.
Being a subclass of Statement, PreparedStatement inherits all the functionalityof Statement.
In addition, it adds a set of methods that are needed for setting the values to besent to the database in place of the placeholders for IN parameters.
Also, the three methods execute, executeQuery, and executeUpdate aremodified 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 andperform a particular task.
Stored procedures are used to encapsulate a set of operations or queries toexecute on a database server.
A CallableStatement object contains a call to a stored procedure. It does notcontain 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("{callSHOW_SUPPLIERS}");
ResultSetrs = cs.executeQuery();