Professional Documents
Culture Documents
Core Java
Core Java
Table of Contents
1.INTRODUCTION TO JAVA FRAMEWORK.............................................................................................6
What is Java?...........................................................................................................................................6
JVM:.........................................................................................................................................................6
The Byte Code: ........................................................................................................................................7
Architecture of JVM:................................................................................................................................7
...........................................................................................................................................................8
Class loader:.............................................................................................................................................8
Java and Unicode:....................................................................................................................................9
Java Characteristics & Features:............................................................................................................10
Importance of Internet with Java:.........................................................................................................12
Comparison of C & C++ Vs Java:.............................................................................................................12
2.JAVA LANGUAGE.............................................................................................................................14
First java program:.................................................................................................................................14
Statements & Expressions:....................................................................................................................15
Keyword & comments:..........................................................................................................................15
Data Types:............................................................................................................................................16
Variables:...............................................................................................................................................19
Operators:..............................................................................................................................................20
Control Statements:...............................................................................................................................22
Iteration Statements:.............................................................................................................................25
3. OBJECT ORIENTED PROGRAMMING WITH JAVA............................................................................29
OOPs (Object oriented programming) Principles:..................................................................................29
Data Member:.......................................................................................................................................33
Method:.................................................................................................................................................33
Using Static:...........................................................................................................................................35
Constructor:...........................................................................................................................................36
Difference between constructor and method:......................................................................................38
This Keyword:........................................................................................................................................38
Modifiers:..............................................................................................................................................39
Page 1
J2SE (Core JAVA) Notes
Copying object:......................................................................................................................................40
Casting In Java:......................................................................................................................................41
Garbage Collection................................................................................................................................43
4. INHERITANCE..............................................................................................................................44
IS-A Relationship:...................................................................................................................................45
Types of INHERITANCES (Reusable techniques):....................................................................................46
Constructor inheritance:........................................................................................................................48
Calling the Base Class Constructor.........................................................................................................48
Super keyword:......................................................................................................................................49
Final Keyword:.......................................................................................................................................50
Important points on final in Java:..........................................................................................................51
why java does not support pointers?.....................................................................................................52
Aggregation (HAS-A):.............................................................................................................................52
.......................................................................................................................................................54
5. POLYMORPHISM.........................................................................................................................55
Method overloading:.............................................................................................................................55
Overloading a Constructor:....................................................................................................................57
Method Overriding:...............................................................................................................................58
Difference Between Overloading And Overriding..................................................................................60
Why Java does not support Operator overloading:...............................................................................61
6. JAVA-CORE TECHNOLOGIES..........................................................................................................62
Abstract Classes and Interfaces:............................................................................................................62
Abstract Class:.......................................................................................................................................62
Interface:..............................................................................................................................................63
Extending Interfaces:.............................................................................................................................64
Implementing Interfaces:.......................................................................................................................65
Using Interface:......................................................................................................................................66
Interface Variables:................................................................................................................................66
Real time example for abstract class and interface...............................................................................66
7. PACKAGES...................................................................................................................................66
Package Structure:.................................................................................................................................67
Page 2
J2SE (Core JAVA) Notes
Page 3
J2SE (Core JAVA) Notes
Page 4
J2SE (Core JAVA) Notes
Page 5
J2SE (Core JAVA) Notes
Page 6
J2SE (Core JAVA) Notes
CORE JAVA
JVM:
JVM is the heart of entire java program execution process. it is responsible for taking .class files
and converting each byte code instruction into the machine language instruction that can be
executed by microprocessor.
Page 7
J2SE (Core JAVA) Notes
The JRE provides runtime support for Java applications. The JDK provides the Java
compiler and other development tools. The JDK includes the JRE.
Both the JRE and the JDK include a Java Virtual Machine (JVM). This is the application that
executes a Java program. A Java program requires a JVM to run on a particular platform
A Java Virtual Machine (JVM) is a virtual machine capable of executing Java byte code. Java
Virtual Machine is the one which change the source code in to the code that is executable
through the system so that this helps in making the Java Platform independent as this code is
accessible in any of the operating system
Page 8
J2SE (Core JAVA) Notes
This memory is divided into 5 parts, called run time data areas, which contain the data
and results while running the program.
Method Area: Method area is the memory block, which stores the class code, code of the
variables, and code of the methods in the java program. (Method means functions written in a
class)
Heap: This is the area where objects are created. Whenever JVM loads a class, a method and a
heap area are immediately created in it.
Java Stacks: Method code is stored on method area. But while running a method, it needs some
more memory to store the data and results. This memory is allotted on java stacks. So, java
stacks are memory areas where java methods are executed. While executing methods, a separate
frame will be created in the java stack, where the method is executed.JVM uses a separate thread
(or process) to execute each thread.
Page 9
J2SE (Core JAVA) Notes
One of the main features of java is "Write Once and Run Anywhere". The Java Virtual Machine
(JVM) is responsible for loading and executing the code. For this purpose, it uses the java class
loader. The java class loaders are responsible for loading appropriate classes in the JVM at the
runtime. In a JVM, each and every class is loaded by some instance of a java.lang.ClassLoader.
The main feature of the classloader is that JVM.
A class file is the smallest unit that gets loaded by the class loader. It contains binary
representation of a java class and contains bytecodes and links to other class files that will be
used. Class loader reads this bytecode and creates the instance of java.lang.Class. When the JVM
starts, initially only the class file is loaded and other classes are loaded as and when required by
the JVM.
The loading of Java classes is performed by class loaders (CL), they are responsible for loading
classes into the JVM. Simple applications can use the Java platform’s built-in class loading
facility to load their classes, more complex applications tend to define their own custom class
loaders.
Java and Unicode:
Before Unicode:
Most programming languages before Java (C/C++, Pascal, Basic ...) there were many
language standards:
ASCII (American Standard Code for Information Interchange) for the United States.
ISO 8859-1 for Western European Language.
KOI-8 for Russian.
This caused two problems:
A particular code value corresponds to different letters in the various language standards.
Page 10
J2SE (Core JAVA) Notes
The encodings for languages with large character sets have variable length. Some common
characters are encoded as single bytes, other require two or more byte.
To solve these problems, a new language standard was developed i.e. Unicode System.
Unicode is a system of encoding characters. All characters and Strings in Java use the
Unicode encoding, which allows truly international programming.
In Unicode, character holds 2 byte, so java also uses 2 byte for characters.
How Does Java Use Unicode?
Java was created around the time when the Unicode standard had values defined for a
much smaller set of characters. Back then it was felt that 16-bits would be more than enough to
encode all the characters that would ever be needed. With that in mind Java was designed to use
UTF-16. In fact, the char data type was originally used to be able to represent a 16-bit Unicode
code point.
Java Characteristics & Features:
Simple
Platform independent
Architectural neutral
Portable
Multi threading
Distributed
Dynamic
Robust
Secured
High performance
Interpreted
Object Oriented Programming Language.
Simple:
Java is easy to write and understand because of the following reasons.
Java programmer doesn't have to work with pointers and doesn’t need to manage memory
explicitly. Java eliminated the use of pointers for security reasons. The software JAVA contains
a program called garbage collector which is always used to Collect unreferenced (unused)
memory location for improving performance of a JAVA program.
Platform independent:
Java provides the facility to "Write once -Run anywhere"(Known as platform
independent). Not even a single language is idle to this feature but java is more closer to this
feature. Java Provide the facility of cross-platform programs by compiling in intermediate code
known as bytecode. This bytecode can be interpreted on any systems which have Java Virtual
Machine (JVM).
Architectural neutral:
Page 11
J2SE (Core JAVA) Notes
A language or technology is said to be processors in the real world. The Java compiler
does this by generating byte code instructions, to be easily interpreted on any machine and to be
easily translated into native machine code on the fly. The compiler generates an architecture-
neutral object file format to enable a Java application to execute anywhere on the network and
then the compiled code is executed on many processors, given the presence of the Java runtime
system. Hence Java was designed to support applications on network. This feature of Java has
thrived the programming language.
Portable:
The feature of java "write once -run anywhere" make java portable. Java programs can
execute in any environment for which there is a java run-time system. (JVM) Java program can
be run on any platform (Linux, Window, Mac) Java program can be transferred over World
Wide Web.
Multi threading:
A thread is like a separate program, executing concurrently. We can write Java programs
that deal with many tasks at once by defining multiple threads. The main advantage of multi-
threading is that it shares the same memory. Threads are important for multi-media, Web
applications etc
Distributed:
Java is a good supporter of networking. It supports LAN (Socket) communication
through java.net package, Web communication through Servlets and JSP (Java Server Pages) and
distributed communication with RMI (Remote Method Invocation) and EJB (Enterprise Java
Beans). Distributed applications are preferred by large scale organizations.
Dynamic:
Java is capable for dynamically linking in new class libraries, methods, and objects.
Robust:
Robust simply means strong. Java uses strong memory management. There are lack of
pointers that avoids security problem. There is automatic garbage collection in java. There is
exception handling and type checking mechanism in java. All these points make java robust.
Secured:
Java is secured because:
No explicit pointers.
Programs run inside virtual machine sandbox.
Classloader- adds security by separating the package for the classes of the local file
system from those that are imported from network sources.
Bytecode Verifier- checks the code fragments for illegal code that can violate access
right to objects.
Page 12
J2SE (Core JAVA) Notes
Security Manager- determines what resources a class can access such as reading and
writing to the local disk.
These security are provided by java language. Some security can also be provided by application
developer through SSL, JAAS, cryptography etc.
High performance:
Java is faster than traditional interpretation since byte code is "close" to native code
still somewhat slower than a compiled language (e.g., C++)
Interpreted:
Different languages are there that are compiled (C/C++), parsed (HTML and XML) and
interpreted (JavaScript and VBScript) etc. But Java is both compiled and interpreted. The source
code is compiled (into bytecode) and byte code is interpreted (into binary code). From source
code to output, two stages exist – compilation and interpretation.
Page 13
J2SE (Core JAVA) Notes
Java does not include the C unique statement keywords ‘goto’, ‘sizeof’ and ‘typedef’.
Java does not define the type modifiers keywords auto, extern, register, signed and
unsigned.
Java does not support and explicit pointer type.
Java does not have a pre-processor and therefore we cannot use #define, #include and
#ifdef statement.
Java requires that the functions with no arguments must be declared with empty
parenthesis and not with the void keyword as done in C.
C++ Vs Java:
Java is more simple than C++ as it doesn’t have typedefs, #defines and preprocessor.
Java does not support Operator Overloading.
Java does not have template classes as in C++.
Java does not support global variables. Every variable and methods is declared with in a
class and forms part of that class.
Java is an architectural-neutral. It works on different types of environments.
Java is both compiled and interpreted whereas C++ is only compiled.
Java doesn’t support multiple inheritances. And it can be achieved through a new
concept called Interfaces.
Java has replaced the destructor function with a finalize () method.
Packages are added in Java.
Page 14
J2SE (Core JAVA) Notes
2. JAVA LANGUAGE
First java program:
To execute your first Java program:
Write the following lines of code in a new text document:
Ex1:
public class HelloWorld
{
public static void main(String[] args)
{
System.out.println("Hello World!");
}
}
Save the file as HelloWorld.java — the name of your file should be the same as the
name of your class definition and followed by the .java extension. This name is case-
sensitive, which means you need to capitalize the precise letters that were capitalized in
the name for the class definition.
Next, open your preferred command-line application.
For example, Command Prompt on Windows;
Compile the Java source file using the following command which you can copy and paste
in if you want:
Compilation:
javac HelloWorld.java
Once the compiler returns back to the prompt, run the application using the following
command:
Execution:
java HelloWorld
The above command should result in your command-line application displaying the
following result:
Output:
Hello World!
Page 15
J2SE (Core JAVA) Notes
Page 16
J2SE (Core JAVA) Notes
Comments:
The Java language supports three types of comments:
I. /* text */ : The compiler ignores everything from /* to */.
II. // text : The compiler ignores everything from // to the end of the line.
III. /** documentation */: This is a documentation comment and in general its called doc
comment. The JDK javadoc tool uses doc comments when preparing automatically
generated documentation.
Data Types:
Page 17
J2SE (Core JAVA) Notes
Every variable must have a data type. When variables declared system reserved some
space to store value. Based on the data type of a variable, the operating system allocates memory
and decides what can be stored in the reserved memory. Therefore, by assigning different data
types to variables, you can store integers, decimals, or characters in these variables.
There are two data types available in Java:
Primitive Data Types
Reference/Object Data Types
byte:
byte data type is the first data type with least memory size allocated which can only be
used for numbers of small ranges.
byte data type is used to save space in large arrays, mainly in place of integers, since a
byte is four times smaller than an int.
Default value is 0.
short:
Short data type can also be used to save memory as byte data type. A short is 2 times
smaller than an int.
Default value is 0.
int:
Page 18
J2SE (Core JAVA) Notes
int is generally used as the default data type for integral values unless there is a concern
about memory.
The default value is 0.
long:
This type is used when a wider range than int is needed.
Default value is 0L.
float:
double:
boolean:
char:
Reference variables are created using defined constructors of the classes. They are used
to access objects. These variables are declared to be of a specific type that cannot be
changed. For example, Employee, Puppy etc.
Class objects, and various type of array variables come under reference data type.
Default value of any reference variable is null.
Page 19
J2SE (Core JAVA) Notes
A reference variable can be used to refer to any object of the declared type or any
compatible type.
Example: Animal animal = new Animal("giraffe");
Variables:
A variable is a container that holds values that are used in a Java program. Every variable
must be declared to use a data type. For example, a variable could be declared to use one of the
eight primitive data types: byte, short, int, long, float, double, char or boolean. And, every
variable must be given an initial value before it can be used.
The declaration syntax is as follows:
Page 20
J2SE (Core JAVA) Notes
Instance variables are declared in a class, but outside a method, constructor or any block.
When a space is allocated for an object in the heap, a slot for each instance variable value
is created.
Instance variables are created when an object is created with the use of the keyword 'new'
and destroyed when the object is destroyed.
More than one method, constructor or block can refer to the values hold by instance
variable.
Access modifiers can be given for instance variables.
Inside class, you can access variable by calling variable name directly without using any
object reference. But within static methods and different class, it should be called using
object reference as :ObjectReference.VariableName
Local variables:
In order to store Temporary state we use local variables.
Generally local variables are declared in the methods,constructors,blocks.
Local variables are created when the method, constructor or block is entered and the
variable will be destroyed once it exits the method, constructor or block.
Access modifiers cannot be used for local variables.
Operators:
Operators are special characters within the Java language that perform operations on
arguments to return a specific result. Some of the types of basic operators are given below:
Arithmetic Operators
Comparison Operators
Boolean Logical Operators
Unary Operators
Bitwise Operators
Arithmetic Operators:
Arithmetic operators are used in mathematical expressions in the same way that they are
used in algebra. The following table lists the arithmetic operators:
Assume integer variable A holds 10 and variable B holds 20, then:
Operator Description Example
+ Addition - Adds values on either side of the operator A + B will give 30
Subtraction - Subtracts right hand operand from left hand
- A - B will give -10
operand
* Multiplication - Multiplies values on either side of the operator A * B will give 200
/ Division - Divides left hand operand by right hand operand B / A will give 2
Modulus - Divides left hand operand by right hand operand and
% B % A will give 0
returns remainder
++ Increment - Increases the value of operand by 1 B++ gives 21
-- Decrement - Decreases the value of operand by 1 B-- gives 19
Page 21
J2SE (Core JAVA) Notes
The relational operator determine the relationship that one operand has to other. Specifically,
they determine equality and ordering. The relational operators are shown here:
Operator Result
== Equal to
!= Not equal to
> greater than
< less than
>= greater than or equal to
<= less than or equal to
Page 22
J2SE (Core JAVA) Notes
Control Statements:
Java Control statements control the order of execution in a java program. This execution
order depends on the supplied data values and the conditional logic. There are three main
categories of control flow statements;
I. Selection Statements
II. Repetition statements
III. Branching Statements
Selection statements:
1. If Statement:
The if statement executes a block of code only if the specified expression is true. If the value is
false, then the if block is skipped and execution continues with the rest of the program. You can
either have a single statement or a block of code within an if statement.
Syntax:
if(conditional_expression){
<statements>;
...;
...;
}
The conditional expression must be a Boolean expression.
Ex 1:
public class IfStatementEx {
public static void main(String[] args) {
int a = 10, b = 20;
if (a > b)
System.out.println("Execute statement 1");
if (a < b)
System.out.println("Execute statement 2");
}
}
2. If-else Statement:
The if/else statement is an extension of the if statement. If the statements in the if
statement fails, the statements in the else block are executed. You can either have
a single statement or a block of code within if-else blocks.
Syntax:
if(conditional_expression){
<statements>;
Page 23
J2SE (Core JAVA) Notes
...;
...;
}
else{
<statements>;
....;
....;
}
EX 2:
public class IfElseStatementEx {
Page 24
J2SE (Core JAVA) Notes
default:
//statement;
}
Ex: 3
public class SwitchCaseStatementDemo {
Page 25
J2SE (Core JAVA) Notes
Page 26
J2SE (Core JAVA) Notes
do{
<statement>;
...;
...;
}while (expression);
EX: 5
public class DoWhileLoopDemo {
Page 27
J2SE (Core JAVA) Notes
System.out.println(count);
}
}
}
Output:
Printing Numbers from 1 to 10
1
.
.
10
Branching Statements:
Break statements:
The break statement is a branching statement that contains two forms: labeled and unlabeled.
The break statement is used for breaking the execution of a loop (while, do-while and for) . It
also terminates the switch statements.
Syntax:
break; // breaks the innermost loop or switch statement.
break label; // breaks the outermost loop in a series of nested loops.
Continue Statement:
This is a branching statement that are used in the looping statements (while, do-while and for) to
skip the current iteration of the loop and resume the next iteration .
Syntax:
continue;
Ex:
Break statements: Continue Statement
for(initialization;test condition;increment) for(initialization;test
{ condition;increment)
if(condition) {
{ if(condition)
//statements {
break; //statements
} continue;
} }
}
Page 28
J2SE (Core JAVA) Notes
In an IT we have two types of programming models are available. They are in the mid-
1980s procedure oriented programming language and in the early 1990s object oriented
programming language (OOP).
The procedural -oriented programs are made up of functions. Functions are less reusable.
It is very difficult to copy a function from one program and reuse in another program. The
procedural languages are not suitable of high-level abstraction for solving real life problems. For
example, C programs uses constructs such as if-else, for-loop, array, method, pointer, which are
low-level and hard to abstract real problems such as a Customer Relationship Management
(CRM) system. Examples of POP are FORTRON, COBOL, PASCAL, BASIC, C, etc.
Object-oriented software are easier to understand, therefore easier to test, debug, and
maintain. The fastest and safest way of developing a new application is to reuse existing codes -
fully tested and proven codes. Examples of object oriented programming languages are LISP,
JAVA, DOT NET, ALGOL, SMALLTALK, OBJECT COBOL, OBJECT PASCAL, Cpp, , etc.
Page 29
J2SE (Core JAVA) Notes
Page 30
J2SE (Core JAVA) Notes
Memory space for methods will be creating on stack memory (that too when we call the
methods).
A class encapsulates the data structures (in variables) and algorithms (methods). The
values of the variables constitute its state. The methods constitute its behaviors.
The class definition exists only one time but whose objects can exists many number of
times i.e., a class is acting as a formula form.
2. OBJECT:
“Object is an instance of the class.”
Object is the basic entity of object oriented programming language. Class itself does
nothing but the real functionality is achieved through their objects.
An instance is a realization of a particular item of a class. In other words, an instance is
an instantiation of a class. All the instances of a class have similar properties, as
described in the class definition.
For example, you can define a class called “Student” and create three instances of the
class “Student” for “Ramesh”, “Raju” and “Ravi”.
Real world entities are called as objects. Ex. Cars, Dogs, Humans, etc. All these objects
have a state and behavior.
If we consider a dog, then its state is - name, breed, color, and the behavior is -
barking, wagging, running.
Page 31
J2SE (Core JAVA) Notes
4. Encapsulation:
Encapsulation is the process of binding together the methods and data variables as a
single entity. This keeps both the data and functionality code safe from the outside world. It
hides the data within the class and makes it available only through the methods. Java provides
different accessibility scopes (public, protected, private, default) to hide the data from outside.
real time example:-if you get fever you will take the medicine to cure. The medicine is the
capsule in which the powder is present. the powder is a mixture of several chemicals as in the
same way all the classes are mixed and only the output(object) you will see as if a capsule.
This keeps the data safe from outside interface and misuse. One way to think about
encapsulation is as a protective.
Wrapper that prevents code and data from being arbitrarily accessed by other code
defined outside the wrapper.
5. Inheritance:
“Inheritance is nothing but extending the class from parent to the child.”
Inheritance allows a class (subclass) to acquire the properties and behavior of another
class (superclass). In java, a class can inherit only one class(superclass) at a time but a class can
have any number of subclasses. It helps to reuse, customize and enhance the existing code. So it
helps to write a code accurately and reduce the development time. Java uses extend keyword to
extend a class.
real time example:- the prime minister of India (late)mr.jawaharlal Nehru and his daughter
indira Gandhi and her son Rajiv Gandhi and his wife Sonia Gandhi.
6. Polymorphism.
“Polymorphism refers to which it does many things.”
Polymorphism means having many forms. In java you can see polymorphism when you
have multiple methods with the same name.
There are two types of polymorphism one is Compile time polymorphism and the other
is run time polymorphism. Compile time polymorphism is method overloading. Runtime time
polymorphism is done using inheritance and interface.
Note: From a practical programming viewpoint, polymorphism manifests itself in three distinct
forms in Java:
Method overloading
Method overriding through inheritance
Method overriding through the Java interface
Page 32
J2SE (Core JAVA) Notes
Real time example:- consider the electric power which does many things .
Many people can have the same name but their mentalities should be different.
Data Member:
We know that a class is a collection of data members and methods. In java programming we
have two types of data members they are
Instance/non-static data members.
Static data members.
Instance Data members Static Data members
1. Instance data members are those 1. Static data members are those whose memory
whose memory space is created each and every time space is created only once, whenever the class is
whenever an object is created. loaded in the main memory irrespective of no of
objects are created.
2. Instance data members are always meant for 2. Static data members are meant for storing common
storing specific values. values.
5. Instance data members are also known as Object 5. Static data member are also known as Class Level
Level Data Members because they depend on object Data Members because they depends on class name
name and independent from class name. and independent from object name
Ex: - Ex: -
int pin; static String cname;
int stno; static String CapIndia;
string sname;
Method:
Java methods are where you put the operations on data (variables) in your Java code. Java
methods must be located inside a Java class. A Java method is a collection of statements that are
grouped together to perform an operation. When you call the System.out.println method, for
example, the system actually executes several statements in order to display a message on the
console.
Syntax:
public static int funcName(int a, int b) {
// body
Page 33
J2SE (Core JAVA) Notes
}
There are two types of methods:
Instance methods are associated with an object and use the instance variables of that
object. This is the default.
Syntax: objectname.methodname().
A static method is a method that can be called and executed without creating an object.
In general, static methods are used to create instance methods.
Static method can be invoked directly via class name i.e.; we don't have to create
an object for a class in order to initiate static method.
Syntax: classname.methodname();
Method Calling:
For using a method, it should be called. There are two ways in which a method is called
i.e. method returns a value or returning nothing (no return value). When a program invokes a
method, the program control gets transferred to the called method. This called method then
returns control to the caller in two conditions, when:
return statement is executed.
reaches the method ending closing brace.
Ex: 8
Following is the example to demonstrate how to define a method and how to call it:
return min;
}
Page 34
J2SE (Core JAVA) Notes
}
Output:
Minimum value = 6
The void Keyword: The void keyword allows us to create methods which do not return a value.
Using Static:
In java "static" can be applied to a class variable, or method, or even for a code block
within a class. Static variables, static methods, and static blocks are stored in method are of JVM.
Static variable: A static variable is a variable whose single copy in memory is shared by all the
objects of the class. So, any modification to the static variable will be reflected on all
objects. Static variables are used to maintain common values which can be shared across all the
objects of the class.
Syntax: <access-specifiers> static <data type> <variable name>;
Eg: public final static float PI;
Static method: A static method is a method that can be called and executed without creating an
object. In general, static methods are used to create instance methods.
Any stand alone Java program needs a main method which is static. "main()" method has
to be declared as static because JVM calls it directly without creating an object to a class.
Static block: "static" block is a code block followed by static keyword. The static block can be
declared as part of the class definition which will be invoked by JVM automatically when class
is loaded into JVM's memory.
Syntax:
static
{
--------;
--------;
--------;
}
Ex9: MyStaticMethods.java
public class MyStaticMethods {
private String name;
private static String staticStr = "STATIC-STRING";
Page 35
J2SE (Core JAVA) Notes
Page 36
J2SE (Core JAVA) Notes
Syntax:
<class_name>(){}
class Student {
Parameterized constructor:
class Student{
int id;
String name;
Page 37
J2SE (Core JAVA) Notes
222 Aryan
In the above example, we have created the constructor of Student class that have two
parameters. We can have any number of parameters in the constructor.
This Keyword:
There can be a lot of usage of this keyword. In java, this is a reference variable that refers to the
current object.
Usage of this keyword:
this keyword can be used to refer current class instance variable.
this() can be used to invoke current class constructor.
this keyword can be used to invoke current class method (implicitly)
this can be passed as an argument in the method call.
this can be passed as argument in the constructor call.
this keyword can also be used to return the current class instance.
A. The this keyword can be used to refer current class instance variable:
If there is ambiguity between the instance variable and parameter, this keyword
resolves the problem of ambiguity.
Page 38
J2SE (Core JAVA) Notes
In the above example, parameter (formal arguments) and instance variables are same that
is why we are using this keyword to distinguish between local variable and instance
variable.
If local variables(formal arguments) and instance variables are different, there is no need
to use this keyword.(refer Example program 11).
Call to this() must be the first statement in constructor.
Modifiers:
Modifiers are keywords that you add to those definitions to change their meanings. The
Java language has a wide variety of modifiers, including the following:
Java Access Modifiers
Non Access Modifiers
To use a modifier, you include its keyword in the definition of a class, method, or variable. The
modifier precedes the rest of the statement, as in the following examples.
Example:
public class className {
// ...
}
private boolean myFlag;
static final double weeks = 9.5;
protected static final int BOXWIDTH = 42;
public static void main(String[] arguments) {
// body of method
}
Access Control Modifiers:
Java provides a number of access modifiers to set access levels for classes, variables,
methods and constructors. The four access levels are:
I. Public: Public class is visible in other packages, field is visible everywhere. (class must
be public too).
Page 39
J2SE (Core JAVA) Notes
II. Private: Private variables or methods may be used only by an instance of the same class that
declares the variable or method, A private feature may only be accessed by the class that owns
the feature.
III. Protected: Is available to all classes in the same package and also available to all
subclasses of the class that owns the protected feature.
IV. default :What you get by default ie, without any access modifier (ie, public private or
protected).It means that it is visible to all within a particular package.
Student(Student s){
System.out.println("Copy constructor called");
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}
Page 40
J2SE (Core JAVA) Notes
s1.display();
s2.display();
}
}
Output: Copy constructor called
111 Raju
111 Raju
Copying the values of one object to another without constructor:
We can copy the values of one object into another by assigning the objects values to
another object. In this case, there is no need to create the constructor.
Example 14:
class Student{
int id;
String name;
Student(int i,String n){
id = i;
name = n;
}
Student(){}
void display(){System.out.println(id+" "+name);}
Casting In Java:
Assigning one data type to another or one object to another is known as casting. Reference
type casting is nothing but assigning one Java object to another object. It comes with very strict
rules and is explained clearly in Object.
Page 41
J2SE (Core JAVA) Notes
Ex:
int x = 10; // occupies 4 bytes
double y = x; // occupies 8 bytes
System.out.println(y); // prints 10.
byte –> short –> int –> long –> float –> double
Ex:
double x = 10.5;
int y = (int) x;
double –> float –> long –> int –> short –> byte
The double x is explicitly converted to int y. The thumb rule is, on both sides, the same
data type should exist.
Boolean casting:
A boolean value cannot be assigned to any other data type. Except boolean, all the
remaining 7 data types can be assigned to one another either implicitly or explicitly; but boolean
cannot. We say, boolean is incompatible for conversion. Maximum we can assign a boolean
value to another boolean.
Page 42
J2SE (Core JAVA) Notes
Subclass object can be assigned to a super class object and this casting is done implicitly.
This is known as upcasting (upwards in the hierarchy from subclass to super class).
Java does not permit to assign a super class object to a subclass object (implicitly)
and still to do so, we need explicit casting. This is known as downcasting (super class to
subclass). Downcasting requires explicit conversion.
Garbage Collection
In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming
the runtime unused memory automatically.
Advantage of Garbage Collection:
It makes java memory efficient because garbage collector removes the unreferenced
objects from heap memory.
It is automatically done by the garbage collector so we don't need to make extra efforts.
Garbage Collection in Java is carried by a daemon thread called Garbage Collector. This
thread calls the finalize() method before object is garbage collected.
Before removing an object from memory Garbage collection thread invokes finalize ()
method of that object and gives an opportunity to perform any sort of cleanup required.
You as Java programmer can not force Garbage collection in Java; it will only trigger if
JVM thinks it needs a garbage collection based on Java heap size.
When an Object becomes Eligible for Garbage Collection:
An Object becomes eligible for GC if its not reachable from any live threads or any static
references in other words an object becomes eligible for garbage collection if its all references
are null. Cyclic dependencies are not counted as reference so if Object A has reference of object
B and object B has reference of Object A and they don't have any other live reference then both
Objects A and B will be eligible for Garbage collection(GC).
All references of that object explicitly set to null e.g. object = null
Object is created inside a block and reference goes out scope once control exit that block.
Parent object set to null, if an object holds reference of another object and when you set
container object's reference null, child or contained object automatically becomes eligible
for garbage collection.
Example 15:
class Simple{
Page 43
J2SE (Core JAVA) Notes
4. INHERITANCE
Object-oriented programming allows you to define new classes from existing classes.
This is called inheritance.
Inheritance is an important and powerful feature for reusing software. Suppose you need
to define classes to model circles, rectangles, and triangles. These classes have many common
features. What is the best way to design these classes so as to avoid redundancy and make the
Page 44
J2SE (Core JAVA) Notes
system easy to comprehend and easy to maintain? The answer is to use inheritance.
Inheritance in Java can be best understood in terms of Parent and Child relationship, also
know n as Super class(Parent) and Sub class(child) in Java language.
In inheritance, the most commonly used keyword would be extends and implements. These
words would determine whether one object IS-A type of another. By using these keywords we
can make one object acquire the properties of another object.
IS-A Relationship:
The concept of IS-A is a totally based on Inheritance, which can be of two types Class
Inheritance or Interface Inheritance.
Example: Apple is a Fruit, Car is a Vehicle etc.
It is key point to note that you can easily identify the IS-A relationship. Wherever you see
an extends keyword or implements keyword in a class declaration, then this class is said to have
IS-A relationship
Page 45
J2SE (Core JAVA) Notes
Single Inheritance:
Single class is one in which there exists single base class and single derived class.
Class A
Base Class
Class B
Derived Class
A
Base Class
B
Intermediate class
D
Derived Class
One class is inherited by many sub classes. In below example class B,C and D inherits
the same class A. A is parent class (or base class) of B,C & D
Page 46
J2SE (Core JAVA) Notes
Multiple Inheritances:
“Multiple Inheritance” refers to the concept of one class extending (Or inherits) more
than one base class. The problem with “multiple inheritance” is that the derived class will have
to manage the dependency on two base classes.
Multiple inheritances are not supported by JAVA through classes but it is supported by
JAVA through the concept of interfaces.
Hybrid Inheritance:
Java doesn’t support multiple inheritance, the hybrid inheritance is also not possible by
JAVA through the concept of classes but it is supported through the concept of interfaces.
Example 16:
class Parent
{
public void p1()
{
System.out.println("Parent method");
}
}
public class Child extends Parent {
public void a1()
{
System.out.println("Child method");
}
public static void main(String[] args)
{
Page 47
J2SE (Core JAVA) Notes
Constructor inheritance:
Java does not inherit constructors. A subclass inherits all the members (fields, methods,
and nested classes) from its superclass. Constructors are not members, so they are not inherited
by subclasses, but the constructor of the superclass can be invoked from the subclass.
Java compiler assumes that the first line of every constructor is an implicit call to the
default superclass constructor unless you explicitly use super() or this().
That Super keyword is used to explicitly invoke a superclass constructor. If you use this
form, it must appear as the first statement of the constructor to ensure that the superclass
constructor executes before the subclass constructor in java.
Syntax to call Superclass Constructor: super(args);
Page 48
J2SE (Core JAVA) Notes
}
private String name;
private String breed;
}
Super keyword:
The super is a reference variable that is used to refer immediate parent class object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly i.e.
referred by super reference variable.
Usage of super Keyword
I. Super is used to refer immediate parent class instance variable.
II. super() is used to invoke immediate parent class constructor.
III. super is used to invoke immediate parent class members (methods and Variables).
void display(){
}
}
Output:50
Example 17:
Page 49
J2SE (Core JAVA) Notes
class Vehicle{
Vehicle(){System.out.println("Vehicle is created");}
}
class Car extends Vehicle{
Car(){
super(); //will invoke parent class constructor
System.out.println("Bike is created");
}
public static void main(String args[]){
Car b=new Car();
}
}
Final Keyword:
Final in java is very important keyword and can be applied to class, method, and
variables in Java. The final keyword is used to restrict the user. That means once you make a
reference final you are not allowed to change that reference and compiler will verify this and
raise compilation error if you try to re-initialized final variables in java.
The final keyword can be used in many context. Final can be:
Variable
Method
Class
Final variable:
Final variables are often declare with static keyword in java and treated as constant. Here
is an example of final variable in Java.
Example of Final keyword:
2) final method:
Final keyword in java can also be applied to methods. A java method with final keyword
is called final method and it can not be overridden in sub-class.
Final methods are faster than non-final methods because they are not required to be
Page 50
J2SE (Core JAVA) Notes
Example 18:
class Bike{
honda.run();
3) final class:
Java class with final modifier is called final class in Java. Final class is complete in
nature and cannot be sub-classed or inherited. Several classes in Java are final e.g. String, Integer
and other wrapper classes.
Example:
Page 51
J2SE (Core JAVA) Notes
Final methods are bonded during compile time also called static binding.
As per Java code convention final variables are treated as constant and written in all
Caps
Aggregation (HAS-A):
If a class have an entity reference, it is known as Aggregation. Aggregation represents
HAS-A relationship.
Consider a situation, Employee object contains many information’s such as id, name, emailId
etc. It contains one more object named address, which contains its own information’s such as
city, state, country, zip code etc. as given below.
class Employee{
int id;
String name;
Address address;//Address is a class
...
}
In such case, Employee has an entity reference address, so relationship is Employee HAS-A
address.
Example:
class Student
{
Page 52
J2SE (Core JAVA) Notes
String name;
Address ad;
}
Student class has an instance variable of type Address. Student code can use Address reference
to invoke methods on the Address, and get Address behavior.
Aggregation allow you to design classes that follow good Object Oriented practices. It also
provide code reusability.
Example of Aggregation:
In this example, Employee has an object of Address, address object contains its own
informations such as city, state, country etc. In such case relationship is Employee HAS-A
address.
AggregationAddress.java
package inharitence;
package inharitence;
Page 53
J2SE (Core JAVA) Notes
}
public static void main(String[] args) {
AggregationAddress address = new AggregationAddress("W.G", "A.P", "India");
AggregationAddress address1 = new AggregationAddress("Hyderabad", "T.G", "India");
emp1.display();
emp2.display();
}
}
Output: 100 Raj
W.G India A.P
101 Ramesh
Hyderabad India T.G
When use Aggregation?
Code reuse is also best achieved by aggregation when there is no is-a relationship.
Inheritance should be used only if the relationship is-a is maintained throughout the
lifetime of the objects involved; otherwise, aggregation is the best choice.
Page 54
J2SE (Core JAVA) Notes
5. POLYMORPHISM
Polymorphism means having many forms. There are two types of polymorphism one is
Compile time polymorphism and the other is run time polymorphism.
Method overloading:
If a class have multiple methods by same name but different parameters, it is known
as Method Overloading. The parameters may differ in type or number, or both. However, the
return types of overloaded methods can be the same or different.
System.out.println("sum is"+(a+b)) ;
System.out.println("sum is"+(a+b));
Page 55
J2SE (Core JAVA) Notes
}
Output: Sum is 13
Sum is 8.4
In the above example, method sum() is overloaded based on the data type of
arguments. we have two definition of method sum(), one with int argument and another with
float argument.
System.out.println(c);
class Sample{
obj.disp('a');
obj.disp('a',10);
Page 56
J2SE (Core JAVA) Notes
Output: a
a 10
In the above example – method disp() has been overloaded based on the number of
arguments – We have two definition of method disp(), one with one argument and another with
two arguments.
Overloading a Constructor:
Like method overloading we can overload constructors also. Constructor overloading in
java allows to have more than one constructor inside one Class. Method overloading you have
multiple methods with same name but different signature, in Constructor overloading you
have multiple constructor with different signature with only difference that Constructor doesn't
have return type in Java. Those constructor will be called as overloaded constructor.
Why do you overload Constructor in Java?
If you have been using framework or API like JDK or Spring you must have seen
lot of method overloading and constructor overloading. Constructor overloading make sense if
you can Construct object via different way.
Example 20:
public class MyOverloading {
public MyOverloading(){
System.out.println("Inside default constructor");
}
public MyOverloading(int i){
System.out.println("Inside single parameter constructor with int value");
}
public MyOverloading(String str){
System.out.println("Inside single parameter constructor with String object");
}
public MyOverloading(int i, int j){
System.out.println("Inside double parameter constructor");
}
Page 57
J2SE (Core JAVA) Notes
Method Overriding:
Declaring a method in subclass which is already present in parent class is known
as method overriding.
If a class inherits a method from its super class, then there is a chance to override the
method provided that it is not marked final.
Advantage of Java Method Overriding
Method Overriding is used to provide specific implementation of a method that is already
provided by its super class.
In this example, we have defined the run method in the subclass as defined in the parent class
but it has some specific implementation. The name and parameter of the method is same and there is
IS-A relationship between the classes, so there is method overriding.
Page 58
J2SE (Core JAVA) Notes
class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
class Bike extends Vehicle{
void run(){System.out.println("Bike is running safely");}
Example 22:
class Bank{
int getRateOfInterest(){return 0;}
}
class SBI extends Bank{
int getRateOfInterest(){return 8;}
}
class ICICI extends Bank{
int getRateOfInterest(){return 7;}
}
class AXIS extends Bank{
int getRateOfInterest(){return 9;}
}
class Test{
public static void main(String args[]){
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}
}
Page 59
J2SE (Core JAVA) Notes
The argument list should be exactly the same as that of the overridden method.
The return type should be the same or a subtype of the return type declared in the original
overridden method in the superclass.
The access level cannot be more restrictive than the overridden method's access level. For
example: if the superclass method is declared public then the overridding method in the
sub class cannot be either private or protected.
Instance methods can be overridden only if they are inherited by the subclass.
A subclass within the same package as the instance's superclass can override any
superclass method that is not declared private or final.
A subclass in a different package can only override the non-final methods declared public
or protected.
Constructors cannot be overridden.
Page 60
J2SE (Core JAVA) Notes
Overloaded methods can change the The access level can't be less restrictive in
access modifier. overridden method.
Overloaded methods can declare new Can throw any unchecked exception by
or broader checked exceptions. overriding.
The overridden method can throw any sub type
or same type exception of overriding method.
A method can be overloaded in the Without inheritance no overriding.
same class or in a subclass.
Can overload final and static methods. You cannot override a method marked final and
static.
Why Java does not support Operator overloading:
Java doesn't support operator overloading. Java doesn't provide freedom to
programmer, to overload the standard arithmetic operators e.g. +, -, * and / etc.
some of these reasons why Operator overloading is not supported in Java.
Simple and clear design was one of the goals of Java designers. They, just don't
want to replicate the language, but wanted to have a clear, truly object oriented language.
Adding Operator overloading would have definitely made design more complex than without it,
and it might have lead to more complex compiler or slows the JVM ,because it needs to do extra
work to identify the actual meaning of operators, and reduce the opportunity to optimize the
language by guarantee behavior of operators in Java.
2) Avoid Programming Errors
Java doesn't allow user defined operator overloading, because if you allow programmer to
do operator overloading, they will come up with multiple meanings for same operator, which
will make the learning curve of any developer hard and things more confusing and messy. Its
been observed that, there is increase in programming errors, when language supports operator
overloading, which in turn increase e development and delivery time.
3) JVM Complexity
From JVM perspective, supporting operator overloading is more difficult, and if the same
thing can be achieved, by using method overloading in more intuitive and clean way, it does
make sense to not support operator overloading in Java.
4) Easy Development of Tools
This is an additional benefit of not supporting operator overloading in Java. Omission of
operator overloading has kept the language easier to handle and process, which in turn makes it
easier to develop the tools, that process the language e.g. IDE or re-factoring tool. Re-factoring
tools in Java are far better than C++.
Page 61
J2SE (Core JAVA) Notes
6. JAVA-CORE TECHNOLOGIES
Page 62
J2SE (Core JAVA) Notes
A method that is declared as abstract and does not have implementation is known as
abstract method. An abstract method consists of a method signature, but no method body.
Syntax:
abstract return_type <method_name>(); //no braces{}
Page 63
J2SE (Core JAVA) Notes
void showMaxSpeed();
Page 64
J2SE (Core JAVA) Notes
//Filename: Football.java
public interface Football extends Sports
{
public void homeTeamScored(int points);
public void visitingTeamScored(int points);
public void endOfQuarter(int quarter);
}
//Filename: Hockey.java
public interface Hockey extends Sports
{
public void homeGoalScored();
public void visitingGoalScored();
public void endOfPeriod(int period);
public void overtimePeriod(int ot);
}
The Hockey interface has four methods, but it inherits two from Sports; thus, a class that
implements Hockey needs to implement all six methods. Similarly, a class that implements
Football needs to define the three methods from Football and the two methods from Sports.
Implementing Interfaces:
When a class implements an interface, you can think of the class as signing a contract,
agreeing to perform the specific behaviors of the interface. If a class does not perform all the
behaviors of the interface, the class must declare itself as abstract.
Page 65
J2SE (Core JAVA) Notes
Using Interface:
There are several advantages in utilizing the features of Interfaces in general programming.
In general when one writes a simple program, one may not think about the need of using
an Interface. But when you are building a larger system or a library which keeps
evolving, it is a good idea to use Interface. A particular advantage of using interface in
Java is that it allows multiple inheritance.
Interfaces are used when you need multiple implementations of the same behavior.
In Java you can only inherent (extend) from one class, but you can implement more than
one interface, so sometimes you will have to use interfaces when you need that sort of
multiple inheritance and when you decide not to use composition over inheritance.
Interface Variables:
An interface may contain variables and constants. However, often it does not makes
sense to put variables in an interface. In some cases it may make sense to define constants in an
interface. Especially if those constants are to be used by the classes implementing the interface,
e.g. in calculations, or as parameters to some of the methods in the interface. However, my
advice to you is to avoid putting variables in interfaces if you can.
All variables in an interface are public, even if you leave out the public keyword in the variable
declaration
Real time example for abstract class and interface
the most real time example of abstract class and interface is bulding a house
concrete methods are explained with completed house.
abstract classes are explained with completed house but a little bit of work left
interfaces are explained with taking a building plan
7. PACKAGES
Java packages are a mechanism to group Java classes that are related to each other, into the same
"module" (package).
If you are writing a normal one-programmer application, it will typically be in one
package. The purpose of a package is to group all related classes together. If you are working on
Page 66
J2SE (Core JAVA) Notes
a program that is divided into separate sections that are worked on by others, each section might
be in its own package.
Page 67
J2SE (Core JAVA) Notes
Page 68
J2SE (Core JAVA) Notes
The -d switch specifies the destination where to put the generated class file. You can use
any directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to
keep the package within the same directory, you can use . (dot).
run the Package (if not using IDE):
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
To Compile: javac -d . Simple.java
To Run: java mypack.Simple
Page 69
J2SE (Core JAVA) Notes
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
Using fully qualified name
If you use fully qualified name then only declared class of this package will be accessible. Now
there is no need to import. But you need to use fully qualified name every time when you are
accessing the class or interface.
It is generally used when two packages have same class name e.g. java.util and java.sql packages
contain Date class.
Example of package by import fully qualified name
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
Output:Hello
8. ARRAYS, STRINGS
Array:
Page 70
J2SE (Core JAVA) Notes
An array is a type of variable that can store multiple values. The array is an object in Java
that contains similar data type values.
Java Array is a data structure in java that can hold one or more values in a single
variable.
Array in java is a collection of similar type of values.
Java has two types of arrays, single dimensional and multidimensional java arrays.
Java array index starts at 0.
Declaring Array Variables:
To use an array in a program, you must declare a variable to reference the array, and you
must specify the type of array the variable can reference.
Syntax for declaring an array variable:
dataType[] arrayRefVar; // preferred way.
or
dataType arrayRefVar[]; // works but not preferred way.
The style dataType arrayRefVar[] comes from the C/C++ language and was adopted in Java
to accommodate C/C++ programmers.
Example: The following code snippets are examples of this syntax:
Creating Arrays:
You can create / Instantiate an array by using the new operator with the following syntax:
dataType[] arrayRefVar = new dataType[arraySize];
Example:
Following statement declares an array variable, myList, creates an array of 10 elements
of double type and assigns its reference to myList:
Processing Arrays:
When processing array elements, we often use either for loop or foreach loop because all
of the elements in an array are of the same type and the size of the array is known.
Example 27:
Page 71
J2SE (Core JAVA) Notes
Page 72
J2SE (Core JAVA) Notes
}
}
}
Output:
1.9
2.9
3.4
3.5
String Handling:
String is a sequence of characters. But in java, string is an object that represents a
sequence of characters. String class is used to create string object. In java, string is basically an
immutable object.
Java String provides a lot of concepts that can be performed on a string such as
compare, concat, equals, split, length, replace, compareTo, intern, substring etc.
Creating Strings:
String can be created in number of ways, here are a few ways of creating string object.
1) Using a String literal
String literal is a simple string enclosed in double quotes " ". A string literal is treated as a String
object.
String greeting = "Hello world!";
2) Using another String object
String str2 = new String(str1);
3) Using new Keyword
String str3 = new String("Java");
4) Using + operator (Concatenation)
String str4 = str1 + str2;
or,
String str5 = “hello”+”Java”;
Each time you create a String literal, the JVM checks the string pool first. If the string
literal already exists in the pool, a reference to the pool instance is returned. If string does not
exist in the pool, a new string object is created, and is placed in the pool. String objects are stored
in a special memory area known as string constant pool inside the heap memory.
Example 29:
public class StringDemo{
Page 73
J2SE (Core JAVA) Notes
}
}
Output:
hello.
The String class is immutable, so that once it is created a String object cannot be
changed. If there is a necessity to make a lot of modifications to Strings of characters, then you
should use String Buffer & String Builder Classes.
Concatenating Strings:
The String class includes a method for concatenating two strings. There are 2 methods to
concatenate two or more string.
Using concat() method
Using + operator
1) Using concat() method
string s = "Hello";
2) Using + operator
System.out.println(str.charAt(3));
Output : k
length():
Page 74
J2SE (Core JAVA) Notes
System.out.println(str.length());
Output : 8
replace():
replace() method replaces occurances of character with a specified new character.
String str = "Change me";
System.out.println(str.replace('m','M'));
Output : Change Me
toLowerCase():
toLowerCase() method returns string with all uppercase characters converted to lowercase.
String str = "ABCDEF";
System.out.println(str.toLowerCase());
Output : abcdef
toUpperCase():
This method returns string with all lowercase character changed to uppercase.
String str = "abcdef";
System.out.println(str.toLowerCase());
Output : ABCDEF
trim():
This method returns a string from which any leading and trailing whitespaces has been removed.
System.out.println(str.trim());
Output : hello
Page 75
J2SE (Core JAVA) Notes
The StringBuilder class was introduced as of Java 5 and the main difference between the
StringBuffer and StringBuilder is that StringBuilders methods are not thread safe(not
Synchronised).
Wrapper Classes:
Wrapper class is a wrapper around a primitive data type. It represents primitive data types
in their corresponding class instances e.g. a boolean data type can be represented as a Boolean
class instance. All of the primitive wrapper classes in Java are immutable i.e. once assigned a
value to a wrapper class instance cannot be changed further.
Wrapper Classes are used broadly with Collection classes in the java.util package and with the
classes in the java.lang.reflect reflection package.
Page 76
J2SE (Core JAVA) Notes
char Character
boolean Boolean
Each of Java's eight primitive data types has a class dedicated to it. These are known as
wrapper classes, because they "wrap" the primitive data type into an object of that class. So,
there is an Integer class that holds an int variable, there is a Double class that holds a double
variable, and so on. The wrapper classes are part of the java.lang package, which is imported
by default into all Java programs. The following discussion focuses on the Integer wrapper
class, but applies in a general sense to all eight wrapper classes.
The following two statements illustrate the difference between a primitive data type and an
object of a wrapper class.
a. int x = 25;
b. Integer y = new Integer(33);
Importance of Wrapper classes
There are mainly two uses with wrapper classes.
1. To convert simple data types into objects, that is, to give object form to a data type; here
constructors are used.
2. To convert strings into data types (known as parsing operations), here methods of type
parseXXX() are used.
Auto boxing and auto unboxing:
Autoboxing is a process by which primitive type is automatically encapsulated(boxed)
into its equivalent type wrapper
Auto-Unboxing is a process by which the value of object is automatically extracted from
a type wrapper.
Creating a wrapper class object using the constructors and retrieving the values wrapped
by those objects using the methods as shown above can become quite cumbersome. As an
alternative, there exists auto boxing and auto-unboxing. Auto boxing refers to an implicit call to
the constructor and auto unboxing refers to an implicit call to the *value() method. Therefore, a
new wrapper object can be created by specifying the value to be wrapped just as we would do for
a primitive data type variable. Also, the value can be retrieved and used in a simple way by
specifying the object name.
since Java 1.5 we can write
Page 77
J2SE (Core JAVA) Notes
Similarly, auto boxing and auto boxing apply to other wrapper classes also.
The data field in an Integer object is only accessible using the methods of the Integer
class. One such method — the intValue() method — returns an int equal to the value of the
object, effectively "unwrapping" the Integer object:
int z = x + y.intValue();
Note : the format of the method call. The intValue() method is an instance method, because it
is called through an instance of the class — an Integer object. The syntax uses dot notation,
where the name of the object variable precedes the dot.
class Boxing{
public static void main(String args[]){
int a=50;
Integer a2=new Integer(a);//Boxing
Integer a3=5;//Boxing
System.out.println(a2+" "+a3);
System.out.println(b);
}
}
OutPut: 50 5
50
Page 78
J2SE (Core JAVA) Notes
System.out.println(i+" "+iob);
Output :
100 100
aa
Integer iOb;
iOb = 100; //Autoboxing of int
++iOb;
When we perform increment operation on Integer object, it is first unboxed, then incremented
and then again reboxed into Integer type object.
This will happen always, when we will use Wrapper class objects in expressions or conditions
etc.
Page 79
J2SE (Core JAVA) Notes
9. EXCEPTION HANDLING:
These days users have become used to expecting a program to fall over at some point.
Even if the programmers work very hard to eliminate all the errors that inadvertently appear in
their code, most programs will have to interact with the operating system, users and other
programs.
In Java terms, the error is known as an exception and to keep the program running
smoothly is known as catching an exception.
Java exception handling enables your Java applications to handle errors sensibly. An
exception is a problem that arises during the execution of a program. An exception can occur for
many different reasons.
Need of Exception:
A user has entered invalid data.
A file that needs to be opened cannot be found.
A network connection has been lost in the middle of communications or the JVM has run
out of memory.
Some of these exceptions are caused by user error, others by programmer error, and
others by physical resources that have failed in some manner.
Type of Exception:
An exception is an event which causes the program to be unable to flow in its intended
execution.
Page 80
J2SE (Core JAVA) Notes
int k;
/*The method close() closes the file input stream It throws IOException*/
fis.close();
}
}
Output: Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Unhandled exception type FileNotFoundException
Unhandled exception type IOException
Unhandled exception type IOException
In the above example we are reading the file myfile.txt and displaying its content on the
screen. In this program there are three places where an checked exception is thrown as
mentioned in the comments below. FileInputStream which is used for specifying the file path
and name, throws FileNotFoundException. The read() method which reads the file content
throws IOException and the close() method which closes the file input stream also throws
IOException.
Why this compilation error?
The checked exceptions get checked during compile time. Since we didn’t
handled/declared the exceptions, our program gave the compilation error. There are two ways to
avoid this error.
Declare the exception using throws keyword.
Handle them using try-catch blocks.
Few other Checked Exceptions:
SQLException
IOException
DataAccessException
ClassNotFoundException
InvocationTargetException
Page 81
J2SE (Core JAVA) Notes
advance, that can cause such exceptions and handle them appropriately. All Unchecked
exceptions are direct sub classes of RuntimeException class.
Example:
class Example {
public static void main(String args[])
{
int num1=10;
int num2=0;
/*Since I'm dividing an integer with 0
* it should throw ArithmeticException*/
int res=num1/num2;
System.out.println(res);
}
}
If you compile this code, it would compile successfully however when you will run it, it
would throw ArithmeticException. That clearly shows that unchecked exceptions are not
checked at compile-time, they are being checked at runtime.
Here are the few most frequently seen unchecked exceptions :
NullPointerException
ArrayIndexOutOfBoundsException
ArithmeticException
IllegalArgumentException
3) Errors:
These are not exceptions at all, but problems that arise beyond the control of the user or
the programmer. Errors are typically ignored in your code because you can rarely do anything
about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored
at the time of compilation.
When an exception occurs the JVM will create an exception object. These objects all derive from
the Throwable class. The Throwable class has two main subclasses - Error and Exception. The Error class
denotes an exception that an application is not likely to be able to deal with.
These exceptions are considered rare. For example, the JVM might run out of resources
due to the hardware not being able to cope with all the processes it is having to deal with. It's
possible for the application to catch the error to notify the user but typically the application is
going to have to close until the underlying problem is dealt with.
Exception Hierarchy:
Page 82
J2SE (Core JAVA) Notes
All exception classes are subtypes of the java.lang.Exception class. The exception class is a
subclass of the Throwable class. Other than the exception class there is another subclass called
Error which is derived from the Throwable class.
Errors are not normally trapped form the Java programs. These conditions normally happen in
case of severe failures, which are not handled by the java programs. Errors are generated to
indicate errors generated by the runtime environment. Example : JVM is out of Memory.
Normally programs cannot recover from errors.
The Exception class has two main subclasses: IOException class and RuntimeException Class.
Handling Exception:
In java, exception handling is done using five keywords.
1) try
2) catch
3) throw
4) throws
5) finally
Exception handling is done by transferring the execution of a program to an appropriate
exception handler when exception occurs.
Page 83
J2SE (Core JAVA) Notes
Block of statements
}
Syntax of catch block:
catch(Exception type)
{
//Code for handling exception
}
Example 31: using Try and catch
class Excp
{
public static void main(String args[])
{
int a,b,c;
try
{
a=0;
b=10;
c=b/a;
System.out.println("This line will not be executed");
}
catch(ArithmeticException e)
{
System.out.println("Divided by zero");
}
System.out.println("After exception is handled");
}
}
output: Divided by zero
After exception is handled
An exception will thrown by this program as we are trying to divide a number by zero
inside try block. The program control is transfered outside try block. Thus the line "This line will
not be executed" is never parsed by the compiler. The exception thrown is handle in catch block.
Once the exception is handled the program controls continue with the next line in the program.
Thus the line "After exception is handled" is printed.
3) throw keyword:
We use this keyword to throw an exception manually. Normally exceptions are thrown by
java runtime system. Using 'throw' keyword, we can throw both built in and custom exceptions.
Syntax:
throw Throwableinstance;
Page 84
J2SE (Core JAVA) Notes
4) throws keyword:
'throws' is a keyword that is used to specify the list of various types of Exceptions that a
method might throw. If there is a priority for an Exception to arise in a method and the Exception
is not handled by the method itself, then the method throws this Exception object and this must
be specified by the 'throws' clause!
The 'throws' clause must be given for all type of exceptions except those of type ‘error’ or
’runtime’ Exception or any of its subclasses.
Syntax :
type method_name(parameter_list) throws exception_list{
.
. //body of method
Page 85
J2SE (Core JAVA) Notes
.
}
Where list is a comma separated list of exception that the method might throw
NOTE : It is necessary for all exceptions, except the exceptions of type Error and
RuntimeException, or any of their subclass.
Example: 33
import java.io.*;
class throwsdemo
{
public static void add() throws ArithmeticException
{
try
{
throw new ArithmeticException("E");
}
catch(NullPointerException t)
{
System.out.println("NullPointer" +t);
}}
public static void main(String arg[])
{
int c=9,b=0;
try
{
add();
}
catch(ArithmeticException e)
{
System.out.println ("ArithmetricException"+e);
}
}
}
OUTPUT: ArithmetricExceptionjava.lang.ArithmeticException: E
5) finally keyword:
'finally' creates a block of code that will be executed after a try/catch block has completed
and before the code following the try/catch block. The 'finally' block will execute even if no
catch statement matches the exception also 'finally' block will execute whether or not an
exception is not thrown.
5.1)Using ‘finally’ with a try only
Page 86
J2SE (Core JAVA) Notes
As we have discussed earlier, a try catch mush have atleast one catch or finally block with it.
Here is the syntax of using a try followed by finally block,
try{
// java code lines
}
finally{
// java code lines that would always be executed, no matters what happened inside try block
}
Page 87
J2SE (Core JAVA) Notes
import java.io.*;
class Mark extends Exception
{
public String toString()
{
return "Mark entered is not valid!";
}
}
public class Marks
{
public static void main(String a[])
{
int m=120;
try
{
if(m>100||m<0)
throw new Mark();
}
catch(Mark me)
{
System.out.println("Exception in marks:"+me);
}
}
}
Page 88
J2SE (Core JAVA) Notes
Re-throwing an Exception:
In the following program, exception is raised in method c ( ) and handled in the same
method. After handling, it throw the exception (this is done to illustrate the throw clause ) and
search continues in the hierarchy( that is, in calling methods). In the hierarchy, the match is
found in method a ( ) and is executed( observe the output).
Re-throwing can be done for extra functionality from the calling method. We can have
output from the catch methods of called and calling methods.
Example 36:
class CatchDemo3 {
static void a ( ) {
try {
b();
}
catch(ArithmeticException e) {
System.out.println("Exception is caught in a ( ): " + e) ;
}
}
static void b ( ) {
c();
}
static void c ( ) {
try {
int i = 5, j = 0 ;
System.out.println( i / j ) ;
}
catch(ArithmeticException e) {
System.out.println("Exception is caught in c ( ): " + e) ;
throw e ;
}
}
public static void main(String args[ ] ) {
a();
}
}
Output: Exception is caught in c ( ): java.lang.ArithmeticException: / divide by zero
Exception is caught in a ( ): java.lang.ArithmeticException: / divide by zero
Page 89
J2SE (Core JAVA) Notes
There cannot be any type of code in between a try, catch and finally blocks
10. THREADS
Java is amultithreaded programming language which means we can develop
multithreaded program using Java. A multithreaded program contains two or more parts that can
run concurrently and each part can handle different task at the same time making optimal use of
the available resources specially when your computer has multiple CPUs.
By definition multitasking is when multiple processes share common processing
resources such as a CPU. Multithreading extends the idea of multitasking into applications where
you can subdivide specific operations within a single application into individual threads. Each of
the threads can run in parallel. The OS divides processing time not only among different
applications, but also among each thread within an application.
Multithreading enables you to write in a way where multiple activities can proceed concurrently
in the same program.
Understanding Threads
Multithreading refers to two or more tasks executing concurrently within a single
program. A thread is an independent path of execution within a program. Many threads can run
concurrently within a program. Every thread in Java is created and controlled by the
java.lang.Thread class. A Java program can have many threads, and these threads can run
concurrently, either asynchronously or synchronously.
For example: We see different peoples in our daily life, they multiple task at a time, I mean they
watch television, and at the same time they are also busy in their handset, or people drive while
talking on phone. How do our mind does this, how do we focus on both the things.
In the domain of object oriented programming this sort of multitasking , can be achieved ,
that is simply using threads. So before going in details of threads we need to understand some
basic concepts of process, this because the threads run within a process
What is a Process:
When we make any sort of application , it consist of processes, so a simple application
may consist of single processes but a complex and relatively large application would consist of
many process. Process in its most simplest form is a program that is in execution.
For Example: suppose you open up any picture in picture viewer software, so there is process
running in that application. Because we know that application consist of process, in the same all
the application uses process.
Note: Both process and Thread are independent path of execution but one process can
have multiple Threads.
Threads:
Page 90
J2SE (Core JAVA) Notes
Threads are contained in the process, or we can say that they are the basic units in process
which can keep the processor busy for a certain amount of time while they are executing i.e
processor is allocated to threads. This processor allocation is done by the OS (Operating
System). Threads in a process can be programmatically scheduled, that is specifying their order
of their execution.
Java thread model:
Multithreading is best in all cases in contrast with single-thread model. Single-thread
system uses an approach of event loop with polling. According to this approach a single thread in
the system runs in an infinite loop. Polling the mechanism, that selects a single event from the
event queue to choose what to do next. As the event is selected, then event loop forwards the
control to the corresponding required event handler. Nothing else can be happened, until the
event handler returns. Because of this CPU time is wasted. Here, only one part of the complete
program is dominating the whole system, and preventing the system to execute or start any other
process. In single-thread model one thread blocks all other threads until its execution completes.
On other waiting or idle thread can start and acquire the resource which is not in use by the
current thread. This causes the wastage of resources.
Java's multithreading provides benefit in this area by eliminating the loop and polling
mechanism, one thread can be paused without stopping the other parts of the program. If any
thread is paused or blocked, still other threads continue to run.
As the process has several states, similarly a thread exists in several states. A thread can be in the
following states:
Thread Life Cycle:
A thread can be in one of the five states. According to sun, there is only 4 states in thread life
cycle in java new, runnable, non-runnable and term inated. There is no running state.
But for better understanding the threads, we are explaining it in the 5 states. The life
cycle of the thread in java is controlled by JVM. The java thread states are as follows:
Page 91
J2SE (Core JAVA) Notes
I. New
II. Runnable
III. Running
IV. Non-Runnable (Blocked)
V. Terminated
1) New:
A new thread begins its life cycle in the new state. It remains in this state until the program
starts the thread. It is also referred to as a born thread.
Page 92
J2SE (Core JAVA) Notes
Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs
following tasks:
I. A new thread starts(with new callstack).
II. The thread moves from New state to the Runnable state.
III. When the thread gets a chance to execute, its target run() method will run.
Page 93
J2SE (Core JAVA) Notes
Where, threadObj is an instance of a class that implements the Runnable interface and
threadName is the name given to the new thread.
Step 3
Once Thread object is created, you can start it by calling start( ) method, which executes a call
to run( ) method. Following is simple syntax of start() method:
void start( );
EX: 37
class Multi3 implements Runnable{
public void run(){
System.out.println("thread is running...");
}
Page 94
J2SE (Core JAVA) Notes
}
}
Output: thread is running...
Thread Priority and Scheduling:
Every thread in java is asigned a priority. By default, a thread inherits the priority from
the thread that spawned it. You can increase or decrease the priority of any thread by using the
setPriority() method, and you can get the thread’s priority by sing the getPriority() method.
Prorities are the numbers rangining from 1 to 10. The thread class has int constants
MIN_PRIORITY, NORM_PRIORITY, and MAX_PRIORITY, representing 1, 5 and 10. The
priority of the main thread is Thread.NORM_PRIORITY.
The java runtime system always picks the thread with the highest prioiryt that is
currently runnable. If severla runnable threads have equal hightest priority, the CPU is allocated
to all of them, in a round-robin fashion. Alower priority thread can run only when no higher
priority threads are currently running.
Thread Synchronization:
When we start two or more threads within a program, there may be a situation when
multiple threads try to access the same resource and finally they can produce unforeseen result
due to concurrency issue. For example if multiple threads try to write within a same file then
they may corrupt the data because one of the threads can overrite data or while one thread is
opening the same file at the same time another thread might be closing the same file.
So there is a need to synchronize the action of multiple threads and make sure that only one
thread can access the resource at a given point in time. This is implemented using a concept
called monitors. Each object in Java is associated with a monitor, which a thread can lock or
unlock. Only one thread at a time may hold a lock on a monitor.
Java programming language provides a very handy way of creating threads and
synchronizing their task by using synchronized blocks. You keep shared resources within this
block. Following is the general form of the synchronized statement:
Syntax:
synchronized(objectidentifier) {
// Access shared variables and other shared resources
}
Here, the objectidentifier is a reference to an object whose lock associates with the
monitor that the synchronized statement represents.
class ThreadSynchronization
{
public static void main(String args[])
Page 95
J2SE (Core JAVA) Notes
Page 96
J2SE (Core JAVA) Notes
sleep((long)(3000*Math.random()));
} catch (InterruptedException x) {
System.out.println("Interrupted!");
}
}
}
class SynchronizedOutput
{
public static synchronized void displayList(String name,String list[])
{
for(int i=0;i<list.length;++i) {
MyThread t = (MyThread) Thread.currentThread();
t.randomWait();
System.out.println(name+list[i]);
}
}
}
Output:
thread1: Java
thread1: is
thread1: hot,
thread1: aromatic,
thread1: and
thread1: invigorating.
Thread 1 is dead.
thread2: Java
thread2: is
thread2: hot,
thread2: aromatic,
thread2: and
thread2: invigorating.
Thread 2 is dead.
Now edit ThreadSynchronization.java and delete the synchronized keyword in the declaration
of the displayList() method of class SynchronizedOutput. Save ThreadSynchronization.java,
recompile it, and rerun it with the new change in place. You may now get different output.
Page 97
J2SE (Core JAVA) Notes
11. DEADLOCKS
Deadlock:
Deadlock describes a situation where two or more threads are blocked forever, waiting
for each other. Deadlock occurs when multiple threads need the same locks but obtain them in
different order. A Java multithreaded program may suffer from the deadlock condition because
the synchronized keyword causes the executing thread to block while waiting for the lock, or
monitor, associated with the specified object.
Here is an example:
Deadlock is a situation of complete Lock, when no thread can complete its execution
because lack of resources. In the above picture, Thread 1 is holding a resource R1, and need
another resource R2 to finish execution, but R2 is locked by Thread 2, which needs R3, which in
turn is locked by Thread 3. Hence none of them can finish and are stuck in a deadlock.
Page 98
J2SE (Core JAVA) Notes
synchronized (resource2) {
System.out.println("Thread 1: locked resource 2");
}
}
}
};
synchronized (resource1) {
System.out.println("Thread 2: locked resource 1");
}
} }
};
t1.start();
t2.start();
}
}
There are simply three methods and a little trick which makes thread communication
possible. First let's see all the three methods listed below:
wait()
notify()
notifyAll()
Page 99
J2SE (Core JAVA) Notes
1) wait () method:
Causes current thread to release the lock and wait until either another thread invokes the
notify() method or the notifyAll() method for this object, or a specified amount of time has
elapsed.
The current thread must own this object's monitor, so it must be called from the synchronized
method only otherwise it will throw exception.
Method Description
public final void wait()throws InterruptedException waits until object is notified.
public final void wait(long timeout)throws waits for the specified amount of time.
InterruptedException
2) notify() method:
Wakes up a single thread that is waiting on this object's monitor. If any threads are
waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs
at the discretion of the implementation.
3) notifyAll() method:
wait() sleep()
wait() method releases the lock sleep() method doesn't release the lock.
This examples shows how two thread can communicate using wait() and notify() method.
Page 100
J2SE (Core JAVA) Notes
package InterThreadCommunication;
class Chat {
boolean flag = false;
System.out.println(msg);
flag = false;
notify();
}
}
Page 101
J2SE (Core JAVA) Notes
Output: Hello
Hi
How are you ?
I am good, what about you?
I am also doing fine!
Great!
Thread Group:
Every thread is a member of a thread group. A thread group provides a mechanism for
collecting multiple threads into a single object and manipulating those threads all at once rather
than individually. For example, you can interrupt all the threads within a group with a single
method call. Thread groups are implemented by the ThreadGroup class in the java.lang
package.
The thread group represents a set of threads.
A thread group can also include other thread groups.
The thread groups form a tree in which every thread group except the initial thread group
has a parent.
A thread from Thread group is allowed to access information about its own thread group,
but not to access information about its thread group's parent thread group or any other thread
groups.
12. IO STREAMS & FILE HANDLING
Page 102
J2SE (Core JAVA) Notes
Java performs I/O through Streams. A Stream is linked to a physical layer by java I/O
system to make input and output operation in java. In general, a stream means continuous flow of
data. Streams are clean way to deal with input/output without having every part of your code
understand the physical. All these streams represent an input source and an output destination.
The stream in the java.io package supports many data such as primitives, Object, localized
characters, etc.
A stream can be defined as a sequence of data. The InputStream is used to read data from
a source and the OutputStream is used for writing data to a destination.
Java encapsulates Stream under java.io package. Java defines two types of streams. They are,
1. Byte Stream: It provides a convenient means for handling input and output of byte.
2. Character Stream: It provides a convenient means for handling input and output of
characters. Character stream uses Unicode and therefore can be internationalized.
Both readers and writers are divided into low-level and high-level classes. Low-level classes
communicate with I/O devices, and high-level classes communicate with the low-level ones.
Byte Stream:
Byte stream is defined by using two abstract class at the top of hierarchy, they are
InputStream and OutputStream.
Page 103
J2SE (Core JAVA) Notes
Java byte streams are used to perform input and output of 8-bit bytes. Though there are many
classes related to byte streams but the most frequently used classes are , FileInputStream and
FileOutputStream. Following is an example which makes use of these two classes to copy an
input file into an output file:
Example:
package Example1;
try {
in = new FileInputStream("E:\\input.txt");
out = new FileOutputStream("E:\\output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Output: Now let's have a file input.txt with the following content:
Page 104
J2SE (Core JAVA) Notes
Character stream is also defined by using two abstract class at the top of hierarchy, they
are Reader and Writer.
Java Byte streams are used to perform input and output of 8-bit bytes, where as
Java Characterstreams are used to perform input and output for 16-bit unicode. Though there
are many classes related to character streams but the most frequently used classes
are , FileReader and FileWriter.. Though internally FileReader uses FileInputStream and
FileWriter uses FileOutputStream but here major difference is that FileReader reads two bytes at
a time and FileWriter writes two bytes at a time.
Example: We can re-write above example which makes use of these two classes to copy an
input file (having unicode characters) into an output file.
package Example1;
public class CopyFile {
public static void main(String args[]) throws IOException
{
FileReader in = null;
FileWriter out = null;
try {
in = new FileReader("E:\\input.txt");
out = new FileWriter("E:\\output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Page 105
J2SE (Core JAVA) Notes
Output: Now let's have a file input.txt with the following content:
import java. Io *;
class ReadTest
try
String str;
while ((str=br.readLine())!=null)
System.out.println(str);
br.close();
fl.close();
catch (IOException e)
{ e.printStackTrace(); }
Page 106
J2SE (Core JAVA) Notes
Unlike earlier streams(that can read only or write only), this class can read and write also.
While opening a file with RandomAccessFile, we must specify in what mode we would
like to open. This is not necessary with earlier streams because they support only one mode
either read (input streams) or write (output streams). RandomAccessFile supports only two
modes – “r” for read mode and “rw” for read and write mode.
Java provides a mechanism, called object serialization where an object can be represented
as a sequence of bytes that includes the object's data as well as information about the object's
type and the types of data stored in the object.
After a serialized object has been written into a file, it can be read from the file and deserialized
that is, the type information and bytes that represent the object and its data can be used to
recreate the object in memory.
Most impressive is that the entire process is JVM independent, meaning an object can be
serialized on one platform and deserialized on an entirely different platform.
Java serialization does not cannot occur for transient or static fields. Marking the field transient
prevents the state from being written to the stream and from being restored during
Page 107
J2SE (Core JAVA) Notes
deserialization. Java provides classes to support writing objects to streams and restoring objects
from streams. Only objects that support the java.io.Serializableinterface or the
java.io.Externalizable interface can be written to streams.
public interface Serializable
The Serializable interface has no methods or fields. (Marker Interface)
Only objects of classes that implement java.io.Serializable interface can be serialized or
deserialized
Input and Output Object Streams:
Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain
the methods for serializing and deserializing an object.
The ObjectOutputStream class contains many write methods for writing various data
types, but one method in particular stands out:
public final void writeObject(Object x) throws IOException
The above method serializes an Object and sends it to the output stream. Similarly, the
ObjectInputStream class contains the following method for deserializing an object:
public final Object readObject() throws IOException,
ClassNotFoundException
This method retrieves the next Object out of the stream and deserializes it. The return value is
Object, so you will need to cast it to its appropriate data type.
Example:
In this example Suppose that we have the following Employee class, which implements
the Serializable interface:
package inharitence;
Page 108
J2SE (Core JAVA) Notes
All of the fields in the class must be serializable. If a field is not serializable, it must be
marked transient.
Serializing an Object:
The ObjectOutputStream class is used to serialize an Object. The following
SerializeDemo program instantiates an Employee object and serializes it to a file.
Note: When serializing an object to a file, the standard convention in Java is to give the file
a .ser extension
package inharitence;
import java.io.*;
Deserializing an Object:
Page 109
J2SE (Core JAVA) Notes
The following DeserializeDemo program deserializes the Employee object created in the
SerializeDemo program.
EXAMPLE:
package Serializing;
import java.io.*;
try
{
FileInputStream fileIn = new FileInputStream("E:\\employee.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
e = (Employee) in.readObject();
in.close();
fileIn.close();
}catch(IOException i)
{
i.printStackTrace();
return;
}catch(ClassNotFoundException c)
{
System.out.println("Employee class not found");
c.printStackTrace();
return;
}
System.out.println("Deserialized Employee...");
System.out.println("Name: " + e.name);
System.out.println("Address: " + e.address);
System.out.println("SSN: " + e.SSN);
System.out.println("Number: " + e.number);
}
}
Page 110
J2SE (Core JAVA) Notes
1. Banking example:
the account holder tries to withdraw money from the server through ATM, the
account holder information along with the withdrawl details will be serialized
(marshalled/flattened to bytes) and sent to server where the details are deserialized
(unmarshalled/rebuilt the bytes)and used to perform operations. This will reduce the network
calls as we are serializing the whole object and sending to server and further request for
information from client is not needed by the server.
2. Stock example:
Lets say an user wants the stock updates immediately when he request for it. To achieve
this, everytime we have an update, we can serialize it and save it in a file. When user requests the
information, deserialize it from file and provide the information. This way we dont need to make
the user wait for the information until we hit the database, perform computations and get the
result.
Page 111
J2SE (Core JAVA) Notes
Collections Framework
Introduction
A collection—sometimes called a container—is simply an object that groups multiple
elements into a single unit. Collections are used to store, to retrieve, and to manipulate data and
to transmit data from one method to another. Collections typically 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).
If you've used the Java programming language—or just about any other programming language
—you're already familiar with collections. Collection implementations in earlier versions of the
Java platform included Vector, Hashtable, and array. Those earlier versions, however,
did not contain a Collections Framework.
Page 112
J2SE (Core JAVA) Notes
Reduces programming effort: By providing useful data structures and algorithms, the
Collections Framework frees you to concentrate on the important parts of your program
rather than on the low-level plumbing required to make it work. By facilitating
interoperability among unrelated APIs, the Collections Framework frees you from
writing oodles of adapter objects or conversion code to connect APIs.
Increases program speed and quality: The Collections Framework does this primarily
by providing high-performance, high-quality implementations of useful data structures
and algorithms. Also, because the various implementations of each interface are
interchangeable, programs can be easily tuned by switching collection implementations.
Finally, because you're freed from the drudgery of writing your own data structures,
you'll have more time to devote to improving the rest of your program's quality and
performance.
Allows interoperability among unrelated APIs: The collection interfaces will become
the vernacular by which APIs pass collections back and forth. If my network
administration API furnishes a Collection of node names and if your GUI toolkit expects
a Collection of column headings, our APIs will interoperate seamlessly, even though they
were written independently.
Reduces effort to learn and to use new APIs: Many APIs naturally take collections on
input and output. In the past, each such API had a little "sub-API" devoted to
manipulating its collections. There was little consistency among these ad hoc collections
sub-APIs, so you had to learn each one from scratch, and it was easy to make mistakes
when using them. With the advent of standard collection interfaces, the problem goes
away.
Reduces effort to design new APIs: This is the flip side of the previous advantage.
Designers and implementers don't have to reinvent the wheel each time they create an
API that relies on collections but instead just use the standard collection interfaces.
Fosters software reuse: New data structures that conform to the standard collection
interfaces are by nature reusable. The same goes for new algorithms that operate on
objects that implement these interfaces.
Page 113
J2SE (Core JAVA) Notes
The core interfaces that define common functionality and allow collections to be
manipulated independent of their implementation.
The 6 core Interfaces used in the Collection framework are:
Collection
List
Set
Iterator (Not a part of the Collections Framework)
SortedSet
Map
SortedMap
The core collection interfaces form a hierarchy: A Set is a special kind of Collection, a
SortedSet is a special kind of Set, and so forth. Note also that the hierarchy consists of two
distinct trees: A Map is not a true Collection.
To keep the number of core collection interfaces manageable, the Java 2 SDK doesn't provide
separate interfaces for each variant of each collection type. (Immutable, fixed-size, and append-
only variants are possible.) Instead, the modification operations in each interface are designated
optional: A given implementation may not support some of these operations. If an unsupported
operation is invoked, a collection throws an UnsupportedOperationException. Implementations
Page 114
J2SE (Core JAVA) Notes
are responsible for documenting which of the optional operations they support. All the Java 2
Platform's general-purpose implementations support all the optional operations.
The four basic core collection interfaces are as follows.
The Collection interface, the root of the collection hierarchy, represents a group of
objects, known as its elements. Some Collection implementations allow duplicate
elements, and others do not. Some are ordered and others unordered. The Java 2 SDK
doesn't provide any direct implementations of this interface but does provide
implementations of more specific subinterfaces, such as Set and List. This interface is the
least common denominator that all collections implement and is used to pass collections
around and to manipulate them when maximum generality is desired.
A Set is a collection that cannot contain duplicate elements. As you might expect, this
interface models the mathematical set abstraction and is used to represent sets, such as
the cards comprising a poker hand, the courses making up a student's schedule, or the
processes running on a machine.
A List is an ordered collection (sometimes called a sequence). Lists can contain duplicate
elements. The user of a List generally has precise control over where in the List each
element is inserted. The user can access elements by their integer index (position). If
you've used Vector, you're familiar with the general flavor of List. .
A Map is an object that maps keys to values. Maps cannot contain duplicate keys: Each
key can map to at most one value.
The last two core collection interfaces (SortedSet and SortedMap) are merely sorted versions of
Set and Map. To understand these interfaces, you have to know how order is maintained among
objects.
The last two core collection interfaces are as follows.
A SortedSet is a Set that maintains its elements in ascending order. Several additional
operations are provided to take advantage of the ordering. Sorted sets are used for
naturally ordered sets, such as word lists and membership rolls.
A SortedMap, a Map that maintains its mappings in ascending key order, is the Map
analog of SortedSet. Sorted maps are used for naturally ordered collections of key/value
pairs, such as dictionaries and telephone directories.
Example:
The following program illustrates several of the methods supported by LinkedList:
import java.util.*;
Page 115
J2SE (Core JAVA) Notes
ll.add("B");
ll.add("D");
ll.add("E");
ll.add("C");
ll.addLast("Z");
ll.addFirst("A");
ll.add(1, "A2");
System.out.println("Original contents of ll: " + ll);
Elements can be inserted or accessed by their position in the list, using a zero-based
index.
A list may contain duplicate elements.
In addition to the methods defined by Collection, List defines some of its own, which are
summarized in the following below Table.
Several of the list methods will throw an UnsupportedOperationException if the
collection cannot be modified, and a ClassCastException is generated when one object is
incompatible with another.
Page 116
J2SE (Core JAVA) Notes
Example:
package Collections;
import java.util.*;
Page 117
J2SE (Core JAVA) Notes
By default you can put any Object into a Set, but from Java 5, Java Generics makes it
possible to limit the types of object you can insert into a Set. Here is an example:
Set<MyObject> set = new HashSet<MyObject>();
This Set can now only have MyObject instances inserted into it. You can then access and iterate
its elements without casting them. Here is how it looks:
for(MyObject anObject : set){
//do someting to anObject...
}
Example:
package Collections;
import java.util.*;
}
catch(Exception e){}
}
}
Page 118
J2SE (Core JAVA) Notes
SortedSet Interface:
The SortedSet interface extends Set and declares the behavior of a set sorted in ascending
order. In addition to those methods defined by Set, the SortedSet interface declares the methods
summarized in below Table:
Several methods throw a NoSuchElementException when no items are contained in the
invoking set. A ClassCastException is thrown when an object is incompatible with the elements
in a set.
A NullPointerException is thrown if an attempt is made to use a null object and null is
not allowed in the set.
Example:
import java.util.*;
Page 119
J2SE (Core JAVA) Notes
The Map interface maps unique keys to values. A key is an object that you use to retrieve
a value at a later date.
Given a key and a value, you can store the value in a Map object. After the value is
stored, you can retrieve it by using its key.
Several methods throw a NoSuchElementException when no items exist in the invoking
map.
A ClassCastException is thrown when an object is incompatible with the elements in a
map.
A NullPointerException is thrown if an attempt is made to use a null object and null is
not allowed in the map.
An UnsupportedOperationException is thrown when an attempt is made to change an
unmodifiable map.
Example: Map has its implementation in various classes like HashMap. Following is the
example to explain map functionality:
import java.util.*;
Page 120
J2SE (Core JAVA) Notes
SortedMap Interface:
The SortedMap interface extends Map. It ensures that the entries are maintained in
ascending key order
Several methods throw a NoSuchElementException when no items are in the invoking
map. A ClassCastException is thrown when an object is incompatible with the elements in a
map. A NullPointerException is thrown if an attempt is made to use a null object when null is
not allowed in the map.
Example: Following is the example to explain SortedMap functionlaity:
package Collections;
import java.util.*;
Page 121
J2SE (Core JAVA) Notes
// keySet method returns a Set view of the keys contained in this map.
Iterator iterator = map.keySet().iterator();
while (iterator.hasNext()) {
Object key = iterator.next();
System.out.println("key : " + key + " value :" + map.get(key));
}
}
}
Output:
The lowest key value is: 1
The highest key value is: 5
All key value is:
{1=One, 2=Two, 3=Three, 4=Four, 5=Five}
The head map is:
{1=One, 2=Two, 3=Three}
The tail map is:
{4=Four, 5=Five}
key : 1 value :One
key : 2 value :Two
key : 3 value :Three
key : 4 value :Four
key : 5 value :Five
Page 122
J2SE (Core JAVA) Notes
defined by the legacy classes such as Vector and Properties, is used by several other API classes,
and is currently in widespread use in application code.
LinkedList Class:
The LinkedList class extends AbstractSequentialList and implements the List interface. It
provides a linked-list data structure.
The LinkedList class supports two constructors. The first constructor builds an empty
linked list:
LinkedList( )
The following constructor builds a linked list that is initialized with the elements of the
collection c.
LinkedList(Collection c)
ArrayList Class:
The ArrayList class extends AbstractList and implements the List interface. ArrayList
supports dynamic arrays that can grow as needed.
Standard Java arrays are of a fixed length. After arrays are created, they cannot grow or
shrink, which means that you must know in advance how many elements an array will hold.
Array lists are created with an initial size. When this size is exceeded, the collection is
automatically enlarged. When objects are removed, the array may be shrunk.
The ArrayList class supports three constructors. The first constructor builds an empty array list.
ArrayList( )
The following constructor builds an array list that is initialized with the elements of the
collection c.
ArrayList(Collection c)
Page 123
J2SE (Core JAVA) Notes
In array list element will be stored In linked list element will be stored randomly
side by side with indexing notation.
Array list element will be access Linked list element will be accessed
randomly because it sequentially
Insertion and deletion operation are bit Insertion and deletion operation are very easy
difficult in array list in linked list
Array list will use less memory than Linked list is very Hungary about memory.
linked list. because you need to use some memory to
store address of next node in the linked list
HashSet :
Elements are stored as unordered and unsorted.
Elements are stored using hashing algorithm.
Each object has a hashcode value which is used to used to inserting or retrieving
an element from a set.
Example:
import java.util.*;
public class HashSetDemo {
Page 124
J2SE (Core JAVA) Notes
System.out.println(hs);
}
}
Output: [D, E, F, A, B, C]
LinkedHashSet :
It maintains insertion order.
It's unsorted Set.
Maintain doubly linked list across elements.
TreeSet :
It is a sorted set.
It uses natural ordering or rather say ascending order.
Map has four subclasses:
HashMap
HashTable
TreeMap
LinkedHashMap
HashMap Class:
The HashMap class uses a hashtable to implement the Map interface. This allows the execution
time of basic operations, such as get( ) and put( ), to remain constant even for large sets.
The HashMap class supports four constructors. The first form constructs a default hash map:
HashMap( )
The second form initializes the hash map by using the elements of m:
HashMap(Map m)
The third form initializes the capacity of the hash map to capacity:
HashMap(int capacity)
The fourth form initializes both the capacity and fill ratio of the hash map by using its
arguments:
HashMap(int capacity, float fillRatio)
legacy classes:
Vector
HashTable
Page 125
J2SE (Core JAVA) Notes
Properties
Dictionary
Stack
Vector:
Vector implements a dynamic array. It is similar to ArrayList, but with two differences:
Vector is synchronized.
Vector contains many legacy methods that are not part of the collections framework.
Vector proves to be very useful if you don't know the size of the array in advance or you
just need one that can change sizes over the lifetime of a program.
The Vector class supports four constructors. The first form creates a default vector, which has an
initial size of 10:
Vector( )
Hashtable Class:
Hashtable was part of the original java.util and is a concrete implementation of a Dictionary.
However, Java 2 re-engineered Hashtable so that it also implements the Map interface.
Thus, Hashtable is now integrated into the collections framework. It is similar to HashMap, but
is synchronized.
Like HashMap, Hashtable stores key/value pairs in a hash table. When using a Hashtable,
you specify an object that is used as a key, and the value that you want linked to that key. The
key is then hashed, and the resulting hash code is used as the index at which the value is stored
within the table.
The Hashtable defines four constructors. The first version is the default constructor:
Hashtable( )
Difference between HashMap and HashTable
HashMap HashTable
Page 126
J2SE (Core JAVA) Notes
Using iterator you can read elements of Using enumeration only you can read
collection and also you can add the elements.
elements, update element, read
elements and remove elements.
You can use iterator to access the You can use enumeration to access the
elements of Array list, Vector, Linked elements of vector only
list, HashSet ,TreeSet, LinkedHashSet.
Properties class:
The properties object contains key and value pair both as a string. It is the subclass of
Hashtable.
Page 127
J2SE (Core JAVA) Notes
It can be used to get property value based on the property key. The Properties class
provides methods to get data from properties file and store data into properties file. Moreover, it
can be used to get properties of system.
Easy Maintenance: If any information is changed from the properties file, you don't need to
recompile the java class. It is mainly used to contain variable information i.e. to be changed.
Sorting:
We can sort the elements of:
1. String objects
2. Wrapper class objects
3. User-defined class objects
Collections class provides static methods for sorting the elements of collection.If
collection elements are of Set type, we can use TreeSet.But We cannot sort the elements of
List.Collections class provides methods for sorting the elements of List type elements.
public void sort(List list): is used to sort the elements of List.List elements must be of
Comparable type.
Comparable interface:
Comparable interface is used to order the objects of user-defined class. This interface is
found in java.lang package and contains only one method named compareTo(Object).It
provide only single sorting sequence i.e. you can sort the elements on based on single
datamember only. For instance it may be either roll no, name, age or anything else
Syntax:
public int compareTo(Object obj): is used to compare the current object with the specified
object.
Note: String class and Wrapper classes implements the Comparable interface.So if you store the
objects of string or wrapper classes, it will be Comparable.
Comparator interface:
Comparator interface is used to order the objects of user-defined class.
This interface is found in java.util package and contains 2 methods compare(Object obj1,Object
obj2) and equals(Object element).
Page 128
J2SE (Core JAVA) Notes
It provides multiple sorting sequence i.e. you can sort the elements based on any data member.
For instance it may be on rollno, name, age or anything else.
There are many new features that have been added in java. There are major enhancement
made in Java5, Java6 and Java7 like auto-boxing, generics, var-args, java
annotations, enum, premain method etc.
J2SE 4 Features:
Assertion:
Assertion is a statement in java. It can be used to test your assumptions about the
program.
While executing assertion, it is believed to be true. If it fails, JVM will throw an error named
AssertionError. It is mainly used for testing purpose.
Advantage of Assertion:
It provides an effective way to detect and correct programming errors
Syntax of using Assertion:
class AssertionExample{
public static void main( String args[] ){
System.out.println("value is "+value);
}
}
Page 129
J2SE (Core JAVA) Notes
If you use assertion, It will not run simply because assertion is disabled by default. To enable the
assertion, -ea or -enableassertions switch of java must be used.
There are some situations where assertion should be avoid to use. They are:
1. According to Sun Specification, assertion should not be used to check arguments in the
public methods because it should result in appropriate runtime exception e.g.
IllegalArgumentException, NullPointerException etc.
2. Do not use assertion, if you don't want any error in any situation.
J2SE 5 Features:
For-each loop (Java 5)
Varargs (Java 5)
Enum (Java 5)
Annotation (Java 5)
Generics (Java 5)
The for-each loop introduced in Java5. It is mainly used to traverse array or collection
elements. The advantage of for-each loop is that it eliminates the possibility of bugs and makes
the code more readable.
Page 130
J2SE (Core JAVA) Notes
The varrags allows the method to accept zero or muliple arguments. Before varargs either
we use overloaded method or take an array as the method parameter but it was not considered
good because it leads to the maintenance problem. If we don't know how many argument we will
have to pass in the method, varargs is the better approach.
Advantage of Varargs:
We don't have to provide overloaded methods so less code.
Syntax of varargs:
The varargs uses ellipsis i.e. three dots after the data type. Syntax is as follows:
Example of Varargs:
class VarargsExample1{
display();//zero argument
display("my","name","is","varargs");//four arguments
}
}
Page 131
J2SE (Core JAVA) Notes
Static Import:
The static import feature of Java 5 facilitate the java programmer to access any static
member of a class directly. There is no need to qualify it by the class name.
class StaticImportExample{
}
}
Output: Hello
Java
Enum:
An enum is a data type which contains fixed set of constants. It can be used for days of
the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY and
SATURDAY) , directions (NORTH, SOUTH, EAST and WEST) etc. The enum constants are
static and final implicitely. It is available from Java 5. Enums can be thought of as classes that
have fixed set of constants.
Page 132
J2SE (Core JAVA) Notes
}
}
Output:WINTER
SPRING
SUMMER
FALL
Java Annotations:
Java Annotation is a tag that represents the metadata i.e. attached with class, interface,
methods or fields to indicate some additional information which can be used by java compiler
and JVM.
Annotations in java are used to provide additional information, so it is an alternative option for
XML and java marker interfaces.
Built-In Java Annotations:
There are several built-in annotations in java. Some annotations are applied to java code and
some to other annotations.
Built-In Java Annotations used in java code:
@Override
@SuppressWarnings
@Deprecated
Built-In Java Annotations used in other annotations:
@Target
Page 133
J2SE (Core JAVA) Notes
@Retention
@Inherited
@Documented
Understanding Built-In Annotations in java:
@Override
@Override annotation assures that the subclass method is overriding the parent class
method. If it is not so, compile time error occurs.
Sometimes, we does the silly mistake such as spelling mistakes etc. So, it is better to
mark @Override annotation that provides assurity that method is overridden.
@SuppressWarnings
@SuppressWarnings annotation: is used to suppress warnings issued by the compiler.
@Deprecated
@Deprecated annoation marks that this method is deprecated so compiler prints
warning. It informs user that it may be removed in the future versions. So, it is better not to use
such methods.
Custom Annotation:
Java Custom annotations or Java User-defined annotations are easy to create and use.
The @interface element is used to declare an annotation. For example:
@interface MyAnnotation{}
Points to remember for java custom annotation signature:
There are few points that should be remembered by the programmer.
1. Method should not have any throws clauses
2. Method should return one of the following: primitive data types, String, Class, enum or array
of these data types.
3. Method should not have any parameter.
4. We should attach @ just before interface keyword to define annotation.
Types of Annotation
There are three types of annotations.
Marker Annotation
Single-Value Annotation
Multi-Value Annotation
1) Marker Annotation
An annotation that has no method, is called marker annotation. For example:
Page 134
J2SE (Core JAVA) Notes
@interface MyAnnotation{}
The @Override and @Deprecated are marker annotations.
2) Single-Value Annotation
An annotation that has one method, is called single-value annotation. For example:
@interface MyAnnotation{
int value();
}
We can provide the default value also. For example:
@interface MyAnnotation{
int value() default 0;
}
How to apply Single-Value Annotation
Let's see the code to apply the single value annotation.
@MyAnnotation(value=10)
The value can be anything.
3) Mulit-Value Annotation
An annotation that has more than one method, is called Multi-Value annotation. For example:
@interface MyAnnotation{
int value1();
String value2();
String value3();
}
}
Generics:
Before generics, we can store any type of objects in collection i.e. non-generic. Now
generics, forces the java programmer to store specific type of objects.
A class or interface that operates on parameterized type is called Generic. Generics was
first introduced in Java5 to deal with type-safe objects. Now it is one of the most profound
feature of java programming language. It provides facility to write algorithm independent of any
specific type of data. Generics also provide type safety.
Using Generics, it becomes possible to create a single class or method that automatically works
with all types of data(Integer, String, Float etc). It expanded the ability to reuse code safely and
easily.
1) Type-safety: We can hold only a single type of objects in generics. It doesn’t allow to store
other objects.
Page 135
J2SE (Core JAVA) Notes
3) Compile-Time Checking: It is checked at compile time so problem will not occur at runtime.
The good programming strategy says it is far better to handle the problem at compile time than
runtime.
ArrayList<String>
import java.util.*;
class TestGenerics1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();
list.add("rahul");
list.add("jai");
//list.add(32);//compile time error
Iterator<String> itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
Page 136
J2SE (Core JAVA) Notes
}
}
}
Output: element is: jai
rahul
jai
Page 137