Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 137

J2SE (Core JAVA) Notes

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

The Directory Structure of Packages:.....................................................................................................68


How to access package from another package?....................................................................................69
8. ARRAYS, STRINGS.......................................................................................................................71
Array: ....................................................................................................................................................71
Creating Arrays:.....................................................................................................................................71
The foreach Loops:................................................................................................................................73
String Handling:.....................................................................................................................................73
String Methods:.....................................................................................................................................75
Java- String Buffer & String Builder Classes:..........................................................................................76
Difference Between String , StringBuilder and StringBuffer Classes......................................................76
Wrapper Classes:...................................................................................................................................76
Importance of Wrapper classes.............................................................................................................77
Auto boxing and auto unboxing:............................................................................................................77
Benefits of Autoboxing / Unboxing:.......................................................................................................79
9. EXCEPTION HANDLING:.............................................................................................................81
Need of Exception:.................................................................................................................................81
Type of Exception:.................................................................................................................................81
1) Checked exceptions or IOException:..............................................................................................81
2) Runtime Exceptions or Unchecked exceptions:.............................................................................82
3) Errors: ...........................................................................................................................................83
Exception Hierarchy:..............................................................................................................................83
Handling Exception:...............................................................................................................................84
1 & 2) Using try and catch:.................................................................................................................84
3) throw keyword:............................................................................................................................85
4) throws keyword:...........................................................................................................................86
5) finally keyword:.............................................................................................................................87
Declaring you own Exception:................................................................................................................88
Re-throwing an Exception:.....................................................................................................................90
Important notes about Exception Handling in Java:..............................................................................90
10. THREADS..............................................................................................................................91
Understanding Threads.........................................................................................................................91

Page 3
J2SE (Core JAVA) Notes

Java thread model:................................................................................................................................92


Thread Life Cycle: ..................................................................................................................................92
How to create thread:............................................................................................................................94
Thread class or Runnable interface:......................................................................................................94
Create Thread by Extending Thread Class:.............................................................................................95
Thread Priority and Scheduling:.............................................................................................................96
Thread Synchronization:........................................................................................................................96
11. DEADLOCKS.........................................................................................................................100
Deadlock:...........................................................................................................................................100
Inter-thread communication in Java:...................................................................................................101
Difference between wait and sleep?...............................................................................................102
Thread Group:......................................................................................................................................104
12. IO STREAMS & FILE HANDLING...........................................................................................104
Introduction to IO Stream class:..........................................................................................................104
Introduction to Reader and Writer classes:.........................................................................................105
Byte Stream: .......................................................................................................................................105
Character Streams:..............................................................................................................................107
Random Access File:............................................................................................................................109
Serialization:........................................................................................................................................109
Input and Output Object Streams:.......................................................................................................110
Serializing an Object:...........................................................................................................................111
Deserializing an Object:......................................................................................................................112
Transient Fields and Java Serialization.................................................................................................113
Collections Framework..................................................................................................................115
Introduction.........................................................................................................................................115
What Is a Collections Framework?.......................................................................................................115
Benefits of Collections Framework.....................................................................................................116
Core Collection Interfaces:...................................................................................................................117
The List Interface:............................................................................................................................119
The Set Interface:.............................................................................................................................120
SortedSet Interface:.........................................................................................................................122

Page 4
J2SE (Core JAVA) Notes

Difference between HashSet and TreeSet:..........................................................................................122


The Map Interface:..............................................................................................................................123
SortedMap Interface:.......................................................................................................................124
Difference between HashMap and HashTable.....................................................................................125
Enumeration Interface (legacy interface):...........................................................................................125
The Collection Classes:.........................................................................................................................126
LinkedList Class:...............................................................................................................................126
ArrayList Class:.................................................................................................................................126
Difference between array list and linked list :......................................................................................126
legacy classes:......................................................................................................................................128
Vector:.............................................................................................................................................129
Hashtable Class:...............................................................................................................................129
Difference between HashMap and HashTable.....................................................................................129
Similaritys on HashMap and HashTable:..........................................................................................130
Difference between HashMap and TreeMap:......................................................................................130
Difference between iterator and enumeration:...................................................................................130
Sorting:................................................................................................................................................131
Comparable interface:.........................................................................................................................131
Comparator interface:.........................................................................................................................131
New Features in Java....................................................................................................................132
J2SE 4 Features:...................................................................................................................................132
Assertion:.........................................................................................................................................132
J2SE 5 Features:...................................................................................................................................133
For-each loop (Advanced or Enhanced For loop):............................................................................133
Variable Argument (Varargs):..........................................................................................................134
Static Import:...................................................................................................................................135
Enum:...............................................................................................................................................135
Java Annotations:.............................................................................................................................136
Generics:..........................................................................................................................................138
Advantage of Java Generics:............................................................................................................138

Page 5
J2SE (Core JAVA) Notes

Page 6
J2SE (Core JAVA) Notes

CORE JAVA

1. INTRODUCTION TO JAVA FRAMEWORK


What is Java?
Java is a high-level object-oriented programming language developed by James Gosling,
Patric Naugton, etc., at Sun Micro System has released lot of rules for JAVA. The original name
of JAVA is OAK. In the year 1991 they make platform independent software and named it Oak.
But later due to some patent conflicts, it was renamed as Java and in 1995 the Java 1.0 was
officially released to the world. This software product with a slogan named “Write Once Run
Anywhere” that means it can develop and run on any device equipped with Java Virtual
Machine (JVM). This language is applicable in all kinds of operating systems including Linux,
Windows, Solaris, and HP-UX etc.
JAVA released to the market in three categories:
i. J2SE (JAVA 2 Standard Edition)
ii. J2EE (JAVA 2Enterprise Edition)
iii. J2ME (JAVA 2 Micro/Mobile Edition).

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.

When we install a java package. It contains 2 things


 The Java Runtime Environment (JRE)
 The Java Development Kit (JDK).

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

JVM consist of following components:-


1) Byte-code verifier: - It verify the byte-code, it check's for unusual code.
2) Class Loader: - After verifying Class Loader will load the byte-code into the memory for
execution.
3) Execution engine:-It further consist of 2 parts:-
a) Interpreter: - It interprets the code & run. b) JIT (Just-in-Time Interpreter)
JVM Hotspot defines when to use Interpreter or JIT.
4) Garbage Collector: - It periodically checks for the object on heap, whose link is broken So it
can collect the garbage from Heap.
5) Security Manager: - It constantly monitors the code. It is 2nd level of security. [1st level is
Byte-code verifier ] JVM (java virtual machine) is java run time environment (JRE)...Which
converts byte code (suppose A.JAVA) in to machine language (A.CLASS) so it can execute on
any platform.
The Byte Code:
Bytecode is object-oriented programming (OOP) code compiled to run on a virtual
machine (VM) instead of a central processing unit (CPU). The VM transforms program code into
readable machine language for the CPU because platforms utilize different code interpretation
techniques. A VM converts bytecode for platform interoperability, but bytecode is not platform-
specific.
Bytecode is in a compiled Java programming language format and has the .class
extension executed by Java Virtual Machine (JVM).
Architecture of JVM:
First of all. Java program converted into a .class file consisting of byte code by
java compile. Remember, this java compiler is outside the JVM. Now this .class file is given to
the JVM. In JVM, there is module (or program) called class loader sub system, which performs
the following functions:
 First of all, it loads the .class file into memory.
 Then it verifies whether all byte code instructions are proper or not. If it finds any
instruction suspicious, the execution is rejected immediately.
 If the byte instructions are proper, then it allocates necessary memory to execute
the program.

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.

The internal architecture of the Java virtual machine


PC (Program Counter) registers: These are the registers (memory areas), which contain
memory address of the instructions of the methods. if there are 3 methods,3 PC registers will be
used to track the instructions of the methods.
Native method stacks: Java methods are executed on Java stacks. Similarly, native methods (for
example C/C++ functions) are executed on Native method stacks. To execute the native methods,
generally native method libraries(for example C/C+ header files) are required. These header files
are located and connected to JVM by a program, called Native method interface.
Class loader:

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.

Object Oriented Programming Language:


Object means a real word entity such as pen, chair, table etc. Object-Oriented
Programming is a methodology or paradigm to design a program using classes and objects. It
simplifies the software development and maintenance by providing some concepts.
OOP has certain important features like Encapsulation, Polymorphism, Inheritance
and Abstraction. These features are referred to as the OOPS concepts.
Importance of Internet with Java:
Java is strongly associated with the Internet because of the fact that the first application
program written in Java was Hot Java, a web browser to run applets on Internet.
Java was meant to be used in distributed environments such as Internet. Since, both the
web and Java share the same philosophy, Java could be easily incorporated into the web system.
Before Java, the World Wide Web was limited to the display of still images and texts. The
incorporation of Java into web pages has made it capable of supporting animation, graphics,
games and a wide range of special effects. With the support of Java, the Web has become more
interactive and dynamic. On the other hand, with the support of the web, we can run a Java
program on someone else’s computer on the Internet.
Java programs can be one of two types: applications and applets. Applications are stand-
alone programs, like any program written using high-level languages. Applications can be
executed from any computer with a java interpreter. Applets are special kinds of java programs
that can run directly from a java compatible web browser. Due to this, Java is popularly known
as Internet Language.

Comparison of C & C++ Vs Java:


C Vs Java:
 Java does not contain the data type’s struct, union and enum.

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

Statements & Expressions:


A program is a set of instructions, which are simple tasks provided to a computer. These
instructions are called statements in Java. Statements can be anything from a single line of code
to a complex mathematical equation.
Different types of statements are described in following lines.
 Assignment statement
 Compound statement
 Exception handling statement
 Synchronization statement
 Control statement
 Conditional statement
 Loop statement
 Branch statement
Expressions:
Expressions are essential building blocks of any Java program. They are built using
values, variables, operators and method calls.
Keyword & comments:
Keywords:
Keywords are special tokens in the language which have reserved use in the language.
Keywords may not be used as identifiers in Java — you cannot declare a field whose name is a
keyword, for instance.
Examples of keywords are the primitive types, int and boolean; the control flow
statements for and if; access modifiers such as public.

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

Primitive Data Types:


Primitive Data types form the back bone to represent the properties/attributes of the
objects. Any form of the data can be stored by using the primitive data types in Java.
There are eight primitive data types supported by Java. Primitive data types are predefined
by the language and named by a keyword. Let us now look into detail about the eight primitive
data types.

Data types in Java


details
Data Memory Size Range Declaration
Type
byte 8 bits -128 to +127 byte a=9;
short 16 bits -32,768 to +32,767 short b=89;
int 32 bits -2,147,483,648 to +2,147,483,647 int c=8789;
long 64 bits +9.223*1018 long=9878688;
float 32 bits - 3.4* e038 to +3.4*e038 float b=89.8f;
double 64 bits -1.7*e308 to +1.7*e308 double c =87.098
char 16 bits A single character char a ='e';
boolean JVM true or false boolean a =true;
Dependent

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:

 Float data type is a single-precision 32-bit IEEE 754 floating point.


 Float is mainly used to save memory in large arrays of floating point numbers.
 Default value is 0.0f.
 Float data type is never used for precise values such as currency.

double:

 double data type is a double-precision 64-bit IEEE 754 floating point.


 This data type is generally used as the default data type for decimal values, generally the
default choice.
 Double data type should never be used for precise values such as currency.
 Default value is 0.0d.

boolean:

 boolean data type represents one bit of information.


 There are only two possible values: true and false.
 This data type is used for simple flags that track true/false conditions.
 Default value is false.

char:

 char data type is a single 16-bit Unicode character.


 Minimum value is '\u0000' (or 0).
 Maximum value is '\uffff' (or 65,535 inclusive).
 Char data type is used to store any character.

Reference Data Types:

 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:

type identifier [ = value][, identifier [= value] ...] ;


Here 'type' is data type and 'identifier' is the variable name.

Variable naming conventions:


 A variable name must be unique.
 A variable name must begin with a letter, an underscore (_), or the dollar symbol ($),
which can be followed by a sequence of letters or digits (0 to 9), ‘$’, or ‘_’.
 A variable name should not start with a digit.
 A variable name should not contain embedded white spaces.
 A variable name should not consist of a keyword.
 A variable name in Java is case sensitive.

Java has following types of variable:


I. Class/static variables
II. Instance /non-static variables
III. Local variables

Class/ static variables:


 Class variable also declared outside a method, constructor or a block with a 'static'
keyword.
 Class variable has only one copy for each class, regardless of how many objects are
created from it.
 Static variables are generally used as constant. Constants are variables that are declared
as public/private, final and static. Constant variables never change from their initial
value.
 Class variable is created when program starts and ends with the program.
 Suppose we have created 5 objects then all of the objects can share same variable.
 Static can only be accessed by using it's fully qualified name as: ClassName.VariableName.

Instance /non-static variables:


 Non-Static Variables are called as Instance Variable

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

The Relational / Comparison Operators:

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

Boolean Logical Operators:


The Boolean logical operators shown here operates only on Boolean operands. All of the
binary logical operators combine two Boolean values to form a resultant Boolean value.
Operator Results
& Logical AND
\ Logical OR
^ Logical XOR(exclusive OR)
|| Short-circuit OR
&& Short-circuit AND
! Logical Unary not
&= AND assignment
\= OR assignment
^= XOR assignment
== Equal to
!= Not equal to
?: Ternary if-then-else
Bitwise Operators:
In Java the bitwise operators are used to manipulate the contents of variables at a bit level
according to binary format. These operators perform bitwise operations on integral type
variables. There are different types of bitwise operators available in the Java language
summarized in the table.
Symbol Name of the Operator Example
~ Unary bitwise complement ~op2
& Bitwise AND op1 & op2
| Bitwise inclusive OR op1 | op2
^ Bitwise exclusive OR op1 ^ op2
<< Signed left shift op1 << op2

Page 22
J2SE (Core JAVA) Notes

>> Signed right sift op1 >> op2


>>> Unsigned right shift op1 >>> op2

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 {

public static void main(String[] args) {


int a = 10, b = 20;
if (a > b) {
System.out.println("Execute statement 1");
} else {
System.out.println("Execute statement 2");
}
}
}
Output:
Execute statement 2

3. Switch Case Statement:


The switch case statement, also called a case statement is a multi-way branch with
several choices. A switch is easier to implement than a series of if/else statements. The
keyword "switch" is followed by an expression that should evaluates to byte, short, char or int
primitive data types ,only. In a switch block there can be one or more labeled cases. The
expression that creates labels for the case must be unique. The switch expression is matched with
each case label. Only the matched case is executed ,if no case matches then the default statement
(if present) is executed.
Syntax:
switch (expression)
{
case value1:
//statement;
break;
case value2:
//statement;
break;

Page 24
J2SE (Core JAVA) Notes

default:
//statement;
}
Ex: 3
public class SwitchCaseStatementDemo {

public static void main(String[] args) {


int a = 10, b = 20, c = 30;
int status = -1;
if (a > b && a > c) {
status = 1;
} else if (b > c) {
status = 2;
} else {
status = 3;
}
switch (status) {
case 1:
System.out.println("a is the greatest");
break;
case 2:
System.out.println("b is the greatest");
break;
case 3:
System.out.println("c is the greatest");
break;
default:
System.out.println("Cannot be determined");
}
}
}
Output: c is the greatest
Iteration Statements:
Iteration statements cause statements (or compound statements) to be executed zero or
more times, subject to some loop-termination criteria. When these statements are compound
statements, they are executed in order, except when either the break statement or the continue
statement is encountered.
Loops are basically means to do a task multiple times, without actually coding all
statements over and over again. For example, loops can be used for displaying a string many
times, for counting numbers and of course for displaying menus.

Page 25
J2SE (Core JAVA) Notes

Loops in Java are mainly of three types:-


I. 'while' loop.
II. 'do while' loop
III. 'for' loop
1. while loop statements:
The while statement is a looping construct control statement that executes a block of code
while a condition is true. You can either have a single statement or a block of code within the
while loop. The loop will never be executed if the testing expression evaluates to false. The loop
condition must be a boolean expression.
Syntax:
while(expression){
<statement>;
...;
...;
}
EX:4
public class WhileLoopDemo {

public static void main(String[] args) {


int count = 1;
System.out.println("Printing Numbers from 1 to 10");
while (count <= 10) {
System.out.println(count++);
}
}
}
Output:
Printing Numbers from 1 to 10
1
.
.
10
2. Do while loop Statement:
The do-while loop is similar to the while loop, except that the test is performed at the end
of the loop instead of at the beginning. This ensures that the loop will be executed at least once.
A do-while loop begins with the keyword do, followed by the statements that make up the body
of the loop. Finally, the keyword while and the test expression completes the do-while loop.
When the loop condition becomes false, the loop is terminated and execution continues with
the statement immediately following the loop. You can either have a single statementor a block
of code within the do-while loop.
Syntax:

Page 26
J2SE (Core JAVA) Notes

do{
<statement>;
...;
...;
}while (expression);
EX: 5
public class DoWhileLoopDemo {

public static void main(String[] args) {


int count = 1;
System.out.println("Printing Numbers from 1 to 10");
do {
System.out.println(count++);
} while (count <= 10);
}
}
Output:
Printing Numbers from 1 to 10
1
.
.
10
3. for loop statements:
This is also a loop statement that provides a compact way to iterate over a range of
values. From a user point of view, this is reliable because it executes the statements within this
block repeatedly till the specified conditions is true .
Syntax:
for (initialization; condition; increment or decrement){
<statement>;
...;
...;
}
initialization: The loop is started with the value specified.
condition: It evaluates to either 'true' or 'false'. If it is false then the loop is terminated.
increment or decrement: After each iteration, value increments or decrements.
Ex: 6
public class ForLoopDemo {

public static void main(String[] args) {


System.out.println("Printing Numbers from 1 to 10");
for (int count = 1; count <= 10; count++) {

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

3. OBJECT ORIENTED PROGRAMMING WITH JAVA

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.

OOPs (Object oriented programming) Principles:


1) Class.
2) Object.
3) Abstraction.
4) Encapsulation.
5) Inheritance.
6) Polymorphism.
1. Class:
In Java a class is a blueprint, template, or prototype that defines and describes the static
attributes and dynamic behaviors common to all objects of the same kind.
Any JAVA program if we want to develop then that should be developed with respective
class only i.e., without class there is no JAVA program.
A class can be visualized as a three-compartment box, as illustrated:
1. Name (or identity): identifies the class.
2. Variables (or attribute, state, field): contains the static attributes of the class.
3. Methods (or behaviors, function, operation): contains the dynamic behaviors of the class.
In other words, a class encapsulates the static attributes (data) and dynamic behaviors (operations
that operate on the data) in a box.

Page 29
J2SE (Core JAVA) Notes

Syntax for class:


[AccessControlModifier] Class <clsname>
{
Variable declaration;
Methods definition;
….
};
Class contains two parts namely variable declaration and method definitions. Variable
declaration represents what type of data members which we use as a part of the class. Method
definition represents the type of methods which we used as the path of the class to perform an
operation.
Ex: 7
public class Circle // class name
{
double radius; // variables
String color;
double getRadius()
{
……
….. // methods
}
double getArea()
{
........
………
}
}
Brief Summary
 A class is a programmer-defined, abstract, self-contained, reusable software entity that
mimics a real-world thing.
 In JAVA memory space for the data members will be creating on heap memory
(Dynamic memory).

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.

Creating Instances of a Class:


To create an instance of a class, you have to:
1. Declare an instance identifier (instance name) of a particular class.
2. Construct the instance (i.e., allocate storage for the instance and initialize the instance)
using the "new" operator.
For examples, suppose that we have a class called Circle, we can create instances of Circle as
follows:

Syntax to create an object:


'new' constructor
// Declare 3 instances of the class Circle, c1, c2, and c3
Circle c1, c2, c3;
// Allocate and construct the instances via new operator
c1 = new Circle();
c2 = new Circle(2.0);
c3 = new Circle(3.0, "red");
// You can declare and construct in the same statement
Circle c4 = new Circle();
There are three steps when creating an object from a class:
 Declaration: A variable declaration with a variable name with an object type.
 Instantiation: The 'new' key word is used to create the object.

Page 31
J2SE (Core JAVA) Notes

 Initialization: The 'new' keyword is followed by a call to a constructor. This call


initializes the new object.
3. Abstraction:
Abstraction is the concept of exposing only the required essential characteristics and
behavior with respect to a context.
Abstraction in java is achieved by using interface and abstract class. Interface give 100%
abstraction and abstract class give 0-100% abstraction.

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.

3. Programmatically instance data 3. Programmatically static data


members declaration should not be preceded by a member declaration must be preceded
keyword static. by static keyword.
Syntax: - Syntax: -
Data type v1, v2, v3 ………. Vn; static data type v1, v2, v3 ………. Vn;
4. Each and every instance data member must be 4. Each and every static data member must be access
access with respective object name. with respective class name.
Ex: - Ex: -
Objname.instance data member name Class name.static data member name

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:

public class ExampleMinNumber{

public static void main(String[] args) {


int a = 11;
int b = 6;
int c = minFunction(a, b);
System.out.println("Minimum Value = " + c);
}

/** returns the minimum of two numbers */


public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;

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.

Syntax: <access-specifiers> static <return type> <method name>(<arguments>);


Eg: public static void main(String args[])

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";

public MyStaticMethods(String n){


this.name = n;
}

Page 35
J2SE (Core JAVA) Notes

public static void testStaticMethod(){


System.out.println("Hey... I am in static method...");
//you can call static variables here
System.out.println(MyStaticMethods.staticStr);
//you can not call instance variables here.
}
public void testObjectMethod(){
System.out.println("Hey i am in non-static method");
//you can also call static variables here
System.out.println(MyStaticMethods.staticStr);
//you can call instance variables here
System.out.println("Name: "+this.name);
}
public static void main(String a[]){
//By using class name, you can call static method
MyStaticMethods.testStaticMethod();
MyStaticMethods msm = new MyStaticMethods("Java2novice");
msm.testObjectMethod();
}
}
Output: Hey... I am in static method...
STATIC-STRING
Hey i am in non-static method
STATIC-STRING
Name: Java2novice
Constructor:
Constructor is a special type of method that is used to initialize the object. When you
create a new instance (a new object) of a class using the new keyword, a constructor for that
class is called. Constructors are used to initialize the instance variables (fields) of an object.
Constructor method has the same name as that of class, they are called or invoked when an
object of class is created and can't be called explicitly.
Rules for creating constructor:
There are basically two rules defined for the constructor.
1. Constructor name must be same as its class name
2. Constructor must have no explicit return type
Types of constructors:
There are two types of constructors:
1. default constructor (no-arg constructor)
2. parameterized constructor.
Default Constructor

A constructor that have no parameter is known as default constructor.

Page 36
J2SE (Core JAVA) Notes

Syntax:
<class_name>(){}

Example of default constructor 10: Student.java

class Student {

Student (){System.out.println("Student is created");}

public static void main(String args[]){


Bike b=new Bike();
}
}
Output: Student is created
In the above example, we are creating the no-arg constructor in the Bike class. It will be
invoked at the time of object creation.
Note: If there is no constructor in a class, compiler automatically creates a default constructor

Parameterized constructor:

 A constructor that have parameters is known as parameterized constructor.


 Parameterized constructor is used to provide different values to the distinct objects.
Example of parameterized constructor: 11

class Student{
int id;
String name;

Student(int i,String n){


id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student s1 = new Student(111,"Ramu");
Student s2 = new Student(222,"Raju");
s1.display();
s2.display();
}
}
Output:
111 Karan

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.

Difference between constructor and method:


Constructor Method
Method is used to expose behaviour of an
Constructor is used to initialize the state of an object.
object.
Constructor must not have return type. Method must have return type.
Constructor is invoked implicitly. Method is invoked explicitly.
The java compiler provides a default constructor if you don't Method is not provided by compiler in
have any constructor. any case.
Method name may or may not be same as
Constructor name must be same as the class name.
class name.

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.

Example 12: use this keyword


class Student{
int id;
String name;

student(int id,String name){


this.id = id;
this.name = name;
}

Page 38
J2SE (Core JAVA) Notes

void display(){System.out.println(id+" "+name);}


public static void main(String args[]){
Student s1 = new Student(111,"Raju");
Student s2 = new Student(222,"ravi");
s1.display();
s2.display();
}
}
Output: 111 Raju
222 ravi

 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.

Non Access Modifiers:


Java provides a number of non-access modifiers to achieve many other functionality.
 The static modifier for creating class methods and variables
 The final modifier for finalizing the implementations of classes, methods, and variables.
 The abstract modifier for creating abstract classes and methods.
 The synchronized and volatile modifiers, which are used for threads.
Copying object:
Copying the values of one object to another:
There are many ways to copy the values of one object into another. They are:
 By constructor
 By assigning the values of one object into another
 By clone () method of Object class
Example 13: we are going to copy the values of one object into another using constructor
class Student{
int id;
String name;
Student(int i,String n){
id = i;
name = n;
}

Student(Student s){
System.out.println("Copy constructor called");
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student s1 = new Student(111,"Raju");
Student s2 = new Student(s1);

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);}

public static void main(String args[]){


Student s1 = new Student(111,"Karan");
Student s2 = new Student();
s2.id=s1.id;
s2.name=s1.name;
s1.display();
s2.display();
}
}
Output: 111 Karan
111 Karan

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.

Java supports two types of castings

Page 41
J2SE (Core JAVA) Notes

I. primitive data type casting.


II. Object casting (reference casting)
Casting Primitive Types:
Java data type casting comes with 3 flavors.
 Implicit casting (widening conversion)
 Explicit casting (narrowing conversion)
 Boolean casting
Implicit casting (widening conversion):
A data type of lower size (occupying less memory) is assigned to a data type of higher
size. This is done implicitly by the JVM. The lower size is widened to higher size. This is also
named as automatic type conversion.

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

Explicit casting (narrowing conversion):


A data type of higher size (occupying more memory) cannot be assigned to a data type of
lower size. This is not done implicitly by the JVM and requires explicit casting; a casting
operation to be performed by the programmer. The higher size is narrowed to lower size.

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.

Ex: boolean x = true;


int y = x; // error

Object casting (reference casting):


Java permits to assign objects of different classes one to another subject to some
conditions.
 Same class objects can be assigned one to another

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{

public void finalize(){System.out.println("object is garbage collected");}

public static void main(String args[]){

Page 43
J2SE (Core JAVA) Notes

Simple s1=new Simple();


Simple s2=new Simple();
s1=null;
s2=null;
System.gc();
}
}
Output: object is garbage collected
object is garbage collected

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.

 Inheritance represents the IS-A relationship, also known as Parent-Child relationship.

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

public class Vehicle{


}
public class Car extends Vehicle{
}
public class Bike extends Vehicle {
}
public class BMW extends Car {
}

Based on the above example


 Vehicle is the superclass of Car class.

 Vehicle is the superclass of Bike class.

 Car and Bike are subclasses of Vehicle class.

 BMW is the subclass of both Car and Vehicle classes.


Advantages of INHERITANCE:
 Application development time is very less.
 Redundancy (repetition) of the code is reducing. Hence we can get less memory cost and
consistent results.
 Instrument cost towards the project is reduced.
 We can achieve the slogan write one’s reuse/run anywhere (WORA) of JAVA.

Page 45
J2SE (Core JAVA) Notes

Types of INHERITANCES (Reusable techniques):


In JAVA we have five types of inheritances. They are as follows:

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

Multi Level Inheritance:


Multi level inheritance is one which there exist single base class, single derived class and
n number of intermediate base classes.

A
Base Class

B
Intermediate class

D
Derived Class

Multilevel inheritance is an indirect way of implementing multiple inheritance.


Hierarchical Inheritance:

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

Child cobj = new Child();


cobj.a1(); //method of Child class
cobj.p1(); //method of Parent class
}
}
Output:
Child method
Parent method

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);

Calling the Base Class Constructor


Example 17:
class Animal {
public Animal(String aType) {
type = new String(aType);
}
public String toString() {
return "This is a " + type;
}
private String type;
}
class Dog extends Animal {
public Dog(String aName) {
super("Dog");
name = aName;
breed = "Unknown";
}
public Dog(String aName, String aBreed) {
super("Dog");
name = aName;
breed = aBreed;

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).

1) Super is used to refer immediate parent class instance variable:


Example 16:
class Vehicle{
int speed=50;
}

class Car extends Vehicle{


int speed=100;

void display(){

System.out.println(super.speed); //will print speed of Vehicle now


}
public static void main(String args[]){
Car c=new Car ();
c.display();

}
}
Output:50

2) super is used to invoke parent class constructor:


The super keyword can also be used to invoke the parent class constructor as given
below:

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.

 Java classes declared as final cannot be extended. Restricting inheritance!

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:

Public static final String STUDENT = “student”;

STUDENT = new String("student") //invalid compilation error

Final variables are by default read-only.

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

resolved during run-time and they are bonded on compile time

Example 18:

class Bike{

final void run(){System.out.println("running");}

class Honda extends Bike{

void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){

Honda honda= new Honda();

honda.run();

Output: Compile Time Error

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:

final class PersonalLoan{

class CheapPersonalLoan extends PersonalLoan{

//compilation error: cannot inherit from final class

Important points on final in Java:


 Final keyword can be applied to member variable, local variable, method or class in Java.

Page 51
J2SE (Core JAVA) Notes

 Final class can not be inheritable in Java.

 All variable declared inside java interface are implicitly final.

 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

e.g. private final int COUNT=10;

why java does not support pointers?


Java does not support pointers explicitly. This greatly reduces the burden of dynamic
memory management while coding from programmers. in order to make it more secure ,it
doesn't allow pointers directly(Manually).Pointers works internally in java.
To reference objects in java you use references. In other languages like C/C++ you use
pointers. Pointers and references are used to point to objects in a program.

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.

Why use Aggregation?

 For Code Reusability.

Example:

class Student
{

Page 52
J2SE (Core JAVA) Notes

String name;
Address ad;
}

Here you can say that Student has-a Address.

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;

public class AggregationAddress {


String city,state,country;

public AggregationAddress(String city, String state, String country) {


this.city = city;
this.state = state;
this.country = country;
}
}
AggregationEmp.java

package inharitence;

Page 53
J2SE (Core JAVA) Notes

public class AggregationEmp {


int id;
String name;
AggregationAddress address;

public AggregationEmp(int id, String name, AggregationAddress address){


this.id = id;
this.name = name;
this.address = address;
}
void display(){
System.out.println(id+" "+name);
System.out.println(address.city+" "+address.country+" "+address.state);

}
public static void main(String[] args) {
AggregationAddress address = new AggregationAddress("W.G", "A.P", "India");
AggregationAddress address1 = new AggregationAddress("Hyderabad", "T.G", "India");

AggregationEmp emp1 = new AggregationEmp(100, "Raj", address);


AggregationEmp emp2 = new AggregationEmp(101, "Ramesh", address1);

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.

When to use Inheritance and Aggregation?


When you need to use property and behaviour of a class without modifying it inside your
class. In such case Aggregation is a better option. Whereas when you need to use and modify
property and behaviour of a class inside your class, its best to use Inheritance.

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.

 Compile time polymorphism (static binding or method overloading)


 Runtime polymorphism (dynamic binding or method overriding)

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.

Different ways of Method overloading:


There are two different ways of method overloading

I. Method overloading by changing data type of Arguments:


Example 19:
class Calculate
{
void sum (int a, int b)

System.out.println("sum is"+(a+b)) ;

void sum (float a, float b)

System.out.println("sum is"+(a+b));

Public static void main (String[] args)

Calculate cal = new Calculate();

cal.sum (8,5); //sum(int a, int b) is method is called.

cal.sum (4.6, 3.8); //sum(float a, float b) is called.

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.

II. Method Overloading – Different Number of parameters in argument list


Example 19:
class DisplayOverloading

public void disp(char c)

System.out.println(c);

public void disp(char c, int num)

System.out.println(c + " "+num);

class Sample{

public static void main(String args[])

DisplayOverloading obj = new DisplayOverloading();

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.

How to overload Constructor in Java:


Constructor overloading is not complex you just need to create another constructor, obviously
same name as of class but different signature but there are certain rules related
to Constructor overloading

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

public static void main(String a[]){


MyOverloading mco = new MyOverloading();
MyOverloading spmco = new MyOverloading(10);
MyOverloading dpmco = new MyOverloading(10,20);
MyOverloading dpmco = new MyOverloading("java2novice");
}
}
Output: Inside default constructor
Inside single parameter constructor with int value
Inside double parameter constructor
Inside single parameter constructor with String object

Important points related to Constructor overloading:


 Constructor overloading is similar to method overloading in Java.
 You can call overloaded constructor by using this() keyword in Java.
 Overloaded constructor must be called from another constructor only.
 Make sure you add no argument default constructor because once compiler will not add if
you have added any constructor in Java.
 If an overloaded constructor called , it must be first statement of constructor in java.

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.

 Method Overriding is used for Runtime Polymorphism

Rules for Method Overriding

 method must have same name as in the parent class


 method must have same parameter as in the parent class.
 must be IS-A relationship (inheritance).
Example of method overriding 21:

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");}

public static void main(String args[]){


Bike obj = new Bike();
obj.run();
}
Output:Bike is running safely

Real time example:


Bank is a class that provides functionality to get rate of interest. But, rate of
interest varies according to banks. For example, SBI, ICICI and AXIS banks could provide 8%,
7% and 9% rate of interest.

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

Output: SBI Rate of Interest: 8


ICICI Rate of Interest: 7

AXIS Rate of Interest: 9

Rules for method overriding:

 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 method declared final cannot be overridden.

 A method declared static cannot be overridden but can be re-declared.

 If a method cannot be inherited, then it cannot be overridden.

 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.

Difference Between Overloading And Overriding


Overloading Overriding
Overloaded methods let you reuse the Any time you have a class that inherits a method
same method name in a class, but with from a superclass, you have the opportunity to
different arguments and optionally, a override the method
different return type
Overloaded methods must change the The argument list must be same.
argument list.
Overloaded methods can change the The return type must be same in jdk 1.4 but in
return type. jdk 1.5 it should be co-varient returns.

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.

1) Simplicity and Cleanliness:

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

Abstract Classes and Interfaces:


Abstraction:
Abstraction is a process of hiding the implementation details and showing only functionality to
the user. For example sending sms, you just type the text and send the message. You don't know the
internal processing about the message delivery.
Ways to achieve Abstaction
There are two ways to achieve abstraction in java
1. Abstract class (0 to 100%)
2. Interface (100%)
Abstract Class:
A class that is declared as abstract is known as abstract class. It needs to be extended and
its method implemented. It cannot be instantiated.
Abstract classes are declared with the abstract keyword. Abstract classes are used to
provide a template or design for concrete subclasses down the inheritance tree. Abstract classes
cannot be instantiated; they must be subclassed, and actual implementations must be provided for
the abstract methods. Any implementation specified can, of course, be overridden by additional
subclasses. An object must have an implementation for all of its methods.

Syntax of abstract class


abstract class <class_name>{}
Example 23:
abstract class A
{
abstract void callme();
}
class B extends A
{
void callme()
{
System.out.println("this is callme.");
}
public static void main(String[] args)
{
B b=new B();
b.callme();
}
}
Abstract method:

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{}

public abstract class Employee


{
private String name;
private String address;
private int number;
public abstract double computePay();
//Remainder of class definition
}
Interface:
An interface is a collection of abstract methods. A class implements an interface, thereby
inheriting the abstract methods of the interface.
An interface is not a class. Writing an interface is similar to writing a class, but they are
two different concepts. A class describes the attributes and behaviors of an object. An interface
contains behaviors that a class implements.
Unless the class that implements the interface is abstract, all the methods of the interface need to
be defined in the class.
An interface is similar to a class in the following ways:
 An interface can contain any number of methods.
 An interface is written in a file with a .java extension, with the name of the interface
matching the name of the file.
 The bytecode of an interface appears in a .class file.
 Interfaces appear in packages, and their corresponding bytecode file must be in a
directory structure that matches the package name.
Syntax:
1. <modifier> interface <interface-name>{
2. //members and methods()
3. }
Example:
interface Animal {

public void eat();


public void travel();
}
Example 24:
package Example1;
interface Vehicle {

Page 63
J2SE (Core JAVA) Notes

void showMaxSpeed();

//must be implemented in all classes which implement this interface


}

class Bus implements Vehicle {

public void showMaxSpeed() {


System.out.println("Bus max speed: 100 km/h");
}
}

class Truck implements Vehicle {

public void showMaxSpeed() {


System.out.println("Truck max speed: 80 km/h");
}
}

public class InterfaceExample {

public static void main(String[] args) {


Vehicle bus = new Bus();
Vehicle truck = new Truck();
bus.showMaxSpeed();
truck.showMaxSpeed();
}
}
OUTPUT: Bus max speed: 100 km/h
Truck max speed: 80 km/h
Extending Interfaces:
An interface can extend another interface, similarly to the way that a class can extend another
class. The extends keyword is used to extend an interface, and the child interface inherits the
methods of the parent interface.
The following Sports interface is extended by Hockey and Football interfaces.
//Filename: Sports.java
Example 25:
public interface Sports
{
public void setHomeTeam(String name);
public void setVisitingTeam(String name);
}

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.

A class uses the implements keyword to implement an interface. The implements


keyword appears in the class declaration following the extends portion of the declaration.
Example 26:
public class MammalInt implements Animal{

public void eat(){


System.out.println("Mammal eats");
}

public void travel(){


System.out.println("Mammal travels");
}
public int noOfLegs(){
return 0;
}

Page 65
J2SE (Core JAVA) Notes

public static void main(String args[]){


MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}
Output: Mammal eats
Mammal travels

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.

Package are categorized into two forms


Built-in Package:-Existing Java package for example java.lang , java.util etc.
User-defined-package:- Java package created by user to categorized classes and interface
Since the package creates a new namespace there won't be any name conflicts with names
in other packages. Using packages, it is easier to provide access control and it is also easier to
locate the related classes
Creating a package:
When creating a package, you should choose a name for the package and put
a package statement with that name at the top of every source file that contains the classes,
interfaces, enumerations, and annotation types that you want to include in the package.
The package statement should be the first line in the source file. There can be only one
package statement in each source file, and it applies to all types in the file.
Ex:
package mypack;
public class employee
{
...statement;
}
Package Structure:

CLASSPATH - For Locating Classes:


CLASSPATH is an environment variable (i.e., global variables of the operating system
available to all the processes) needed for the Java compiler and runtime to locate the Java
packages used in a Java program. (Why not call PACKAGEPATH?) This is similar to another
environment variable PATH, which is used by the CMD shell to find the executable programs.

Page 67
J2SE (Core JAVA) Notes

CLASSPATH can be set in one of the following ways:


1. CLASSPATH can be set permanently in the environment: In Windows, choose control
panel ⇒ System ⇒ Advanced ⇒ Environment Variables ⇒ choose "System Variables"
(for all the users) or "User Variables" (only the currently login user) ⇒ choose "Edit"
(if CLASSPATH already exists) or "New" ⇒ Enter "CLASSPATH" as the variable name
⇒ Enter the required directories and JAR files (separated by semicolons) as the value
(e.g., ".;c:\javaproject\classes;d:\tomcat\lib\servlet-api.jar"). Take note that you need to
include the current working directory (denoted by '.') in theCLASSPATH.
To check the current setting of the CLASSPATH, issue the following command:
> SET CLASSPATH
2. CLASSPATH can be set temporarily for that particular CMD shell session by issuing the
following command:
3. > SET CLASSPATH=.;c:\javaproject\classes;d:\tomcat\lib\servlet-api.jar
4. Instead of using the CLASSPATH environment variable, you can also use the command-
line option -classpath or -cp of the javac and java commands, for example,
> java –classpath c:\javaproject\classes com.abc.project1.subproject2.MyClass3
The Directory Structure of Packages:
Two major results occur when a class is placed in a package:
 The name of the package becomes a part of the name of the class, as we just discussed in
the previous section.
 The name of the package must match the directory structure where the corresponding
bytecode resides.
Here is simple way of managing your files in Java:
Put the source code for a class, interface, enumeration, or annotation type in a text file whose
name is the simple name of the type and whose extension is .java.

Example of package 27:


//save as Simple.java
package mypack;

public class Simple{


public static void main(String args[]){
System.out.println("Welcome to package");
}
}

compile the Package (if not using IDE):


syntax : javac -d directory javafilename

For example: javac -d . Simple.java

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

Output: Welcome to package


The -d is a switch that tells the compiler where to put the class file i.e. it represents
destination. The . represents the current folder.

How to access package from another package?


There are three ways to access the package from outside the package.
I. import package.*;
II. import package.classname;
III. fully qualified name.
Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.
The import keyword is used to make the classes and interface of another package accessible to
the current package.

Example of package that import the packagename.*


//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
Example of package by import package.classname

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:

double[] myList; // preferred way.


or
double myList[]; // works but not preferred way.

Creating Arrays:
You can create / Instantiate an array by using the new operator with the following syntax:
dataType[] arrayRefVar = new dataType[arraySize];

The above statement does two things:


 It creates an array using new dataType[arraySize];
 It assigns the reference of the newly created array to the variable arrayRefVar.

Example:
Following statement declares an array variable, myList, creates an array of 10 elements
of double type and assigns its reference to myList:

double[] myList = new double[10];

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

public class TestArray {

public static void main(String[] args) {


double[] myList = {1.9, 2.9, 3.4, 3.5};

// Print all the array elements


for (int i = 0; i < myList.length; i++) {
System.out.println(myList[i] + " ");
}
// Summing all elements
double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
System.out.println("Total is " + total);
// Finding the largest element
double max = myList[0];
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
}
System.out.println("Max is " + max);
}
}
Output: 1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5
The foreach Loops:
JDK 1.5 introduced a new for loop known as foreach loop or enhanced for loop, which
enables you to traverse the complete array sequentially without using an index variable.
Example 28:
public class TestArray {

public static void main(String[] args) {


double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (double element: myList) {
System.out.println(element);

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{

public static void main(String args[]){


char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.'};
String helloString = new String(helloArray);
System.out.println( helloString );

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";

string str = "Java";

string str2 = s.concat(str);

String str1 = "Hello".concat("Java"); //works with string literals too.

2) Using + operator

string str = "Rama";

string str1 = "Krishna";

string str2 = str + str1;

string st = "Rama"+" Krishna ";


String Methods:
The following methods are some of the most commonly used methods of String class.
charAt():
charAt() function returns the character located at the specified index.
String str = "milkyway";

System.out.println(str.charAt(3));
Output : k

length():

length() function returns the number of characters in a String.

Page 74
J2SE (Core JAVA) Notes

String str = "Count me";

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.

String str = " hello ";

System.out.println(str.trim());

Output : hello

Java- String Buffer & String Builder Classes:


Problem with String in Java:
One of its biggest strength Immutability is also biggest problem of Java String if not used
correctly. many a times we create a String and then perform a lot of operation on them e.g.
converting string into uppercase, lowercase , getting substring out of it , concatenating with other
string etc. Since String is an immutable class every time a new String is created and older one
is discarded which creates lots of temporary garbage in heap. If String are created using String
literal they remain in String pool. To resolve this problem Java provides us two
Classes StringBuffer and StringBuilder. String Buffer is an older class but StringBuilder is

Page 75
J2SE (Core JAVA) Notes

relatively new and added in JDK 5.


String Buffer & String Builder:
 The StringBuffer and StringBuilder classes are used when there is a necessity to make a
lot of modifications to Strings of characters.

 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).

 It is recommended to use StringBuilder whenever possible because it is faster than


StringBuffer. However if thread safety is necessary the best option is StringBuffer
objects.

Difference Between String , StringBuilder and StringBuffer Classes

String StringBuffer StringBuilder

Storage Area Constant String Pool Heap Heap

Modifiable No (immutable) Yes( mutable ) Yes( mutable )


Thread Safe
Yes Yes No
Performance
Fast Very slow Fast

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.

Primitive data type


Wrapper class
byte Byte
short Short
int Integer
long Long
float Float
double Double

Page 76
J2SE (Core JAVA) Notes

char Character
boolean Boolean

 All the methods of the wrapper classes are static.


 The Wrapper class does not contain constructors.
 Once a value is assigned to a wrapper class instance it can not be changed, anymore.

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

Integer intObject = 34;


int x=intObject;
int x = intObject + 7;

Page 77
J2SE (Core JAVA) Notes

The above statements are equivalent to the following set of statements

Before Java 1.5 we was force to write

Integer intObject = new Integer (34);


int x = intObject.intValue();
int x = intObject .intValue()+ 7;

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.

Example of Autoboxing and Unboxing:


package TopPrograms;

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);

Integer i=new Integer(50);


int b=i;

System.out.println(b);
}
}
OutPut: 50 5
50

Example of Autoboxing and Unboxing:


class Test
{
public static void main(String[] args)
{
Integer iob = 100; //Autoboxing of int
int i = iob; //unboxing of Integer

Page 78
J2SE (Core JAVA) Notes

System.out.println(i+" "+iob);

Character cob = 'a'; /Autoboxing of char


char ch = cob; //Auto-unboxing of Character
System.out.println(cob+" "+ch);
}
}

Output :
100 100
aa

The simple words


 Converting an int to Integer is called boxing.
 Converting an Integer to int is called unboxing
And so on for conversion between other primitive types and their corresponding Wrapper
classes.
 Since java 5, it will automatically do the required conversions for you(autoboxing).
 Wrapper class provides many methods while using collections like sorting, searching etc.
Benefits of Autoboxing / Unboxing:

 No need of conversion between primitives and Wrappers manually so less coding is


required.
 We don't have to perform Explicit typecasting.
 It helps prevent errors, but may lead to unexpected results sometimes. Hence must be
used with care.

Autoboxing / Unboxing in Expressions:


Whenever we use object of Wrapper class in an expression, automatic unboxing and boxing is
done by JVM.

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.

There are three types of exception.

1) Checked exceptions or IOException:


Checked exceptions are checked at compile-time. It means if a method is throwing a
checked exception then it should handle the exception using try-catch block or it should declare
the exception using throws keyword, otherwise the program will give a compilation error. It is
named as checked exception because these exceptions are checked at Compile time. For
example, if a file is to be opened, but the file cannot be found, an exception occurs.
Example : 30
import java.io.*;
class Example {
public static void main(String args[])
{
FileInputStream fis = null;
/*This constructor FileInputStream(File filename) throws FileNotFoundException which
* is a checked exception*/
fis = new FileInputStream("B:/myfile.txt");

Page 80
J2SE (Core JAVA) Notes

int k;

/*Method read() of FileInputStream class also throws a checked exception:*/


while(( k = fis.read() ) != -1)
{
System.out.print((char)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

2) Runtime Exceptions or Unchecked exceptions:


A runtime exception occurs simply because the programmer has made a mistake.
Unchecked exceptions are not checked at compile time. It means if your program is throwing an
unchecked exception and even if you didn’t handle/declare that exception, the program won’t
give a compilation error. Most of the times these exception occurs due to the bad data provided
by user during the user-program interaction. It is up to the programmer to judge the conditions in

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.

1 & 2) Using try and catch:


Try is used to guard a block of code in which exception may occur. This block of code is
called guarded region. A catch statement involves declaring the type of exception you are trying
to catch. If an exception occurs in guarded code, the catch block that follows the try is checked,
if the type of exception that occured is listed in the catch block then the exception is handed over
to the catch block which then handles it.
Syntax of try block:
try
{

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

Throwableinstance is either an object of type throwable or a sub-class of throwable.


Note:
int, char and non-throwable classes such as Strings and objects cannot be used as exceptions.

There are two ways to obtain throwable object:


 Using a parameter into a catch
 Creating one with a new operator.
Example: 32
import java.io.*;
class Chk
{
public static void main(String s[])
{
System.out.println("Just to show working of 'throw' keyword!");
try
{
throw new ArithmeticException();
}
catch(ArithmeticException e)
{
System.out.println("just throw an Arithmetic Exception object using 'throw' keyword!");
}
}
}
OUTPUT:
Just to show working of 'throw' keyword!
just throw an Arithmetic Exception object using 'throw' keyword!

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
}

5.2) Using ‘finally’ with try-catch combination


A finally block can be used with a combination of try-catch blocks, see the example below.
try{
// java code lines
}
catch(Exception e){
}
finally{
// java code lines that would always be executed, no matters what happened inside try block
}
Example: 34
Class ExceptionTest
{
public static void main(String[] args)
{
int a[]= new int[2];
System.out.println("out of try");
try
{
System.out.println("Access invalid element"+ a[3]);
/* the above statement will throw ArrayIndexOutOfBoundException */
}
finally
{
System.out.println("finally is always executed.");
}
}}
Output:
Out of try
finally is always executed.
Exception in thread main java. Lang. exception array Index out of bound exception.

Page 87
J2SE (Core JAVA) Notes

Declaring you own Exception:


Sometimes it is required to develop meaningful exceptions based on application
requirements. You can create your own exceptions in Java. Keep the following points in mind
when writing your own exception classes:
 All exceptions must be a child of Throwable.
 If you want to write a checked exception that is automatically enforced by the Handle or
Declare Rule, you need to extend the Exception class.
 If you want to write a runtime exception, you need to extend the RuntimeException class.
We can define our own Exception class as below:
class MyException extends Exception{
}
For defining a user defined (custom build exception). we have three steps.
 Create an exception subclass and extend exception class.
 throw the exception
 catch it
Example 35: Exception which is thrown if the mark entered is <0 and >100

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

OUTPUT: Exception in marks: Mark entered is not valid!

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

Important notes about Exception Handling in Java:


 A ‘try’ block must be followed by a catch or a finally block.
 A ‘try’ block can contain any number of catch block, but these catch blocks must
represent distinct Exception Class that too in narrow to broad order.
 A ‘catch’ or ‘finally’ block cannot be used without a ‘try’ block.

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.

Thread t1 = new Thread();


In the above statement t1 thread is created but is not eligible for microprocessor
time as it is inactive. To make the thread active, call start() method on the thread object as
t1.start(). This makes the thread active and now eligible for processor time slices. This state can
be compared with start() method of applets.
2) Runnable state:
The thread is in runnable state after invocation of start() method, but the thread scheduler
has not selected it to be the running thread.
3) Running State:
A Thread is called in running state when it is in its execution mode. In this state control
of CPU is given to the Thread. To execute a Thread the scheduler select the specified thread
from runnable pool.

Page 92
J2SE (Core JAVA) Notes

4) Non-Runnable (Blocked State):


A Thread is called in blocked state when it is not allowed to enter in runnable and/or
running state. A thread is in blocked state when it is suspend, sleep or waiting.
Example :
Thread thread = new Thread();
thread.sleep();
5) Terminated:
A Thread is called in dead state when its run() method execution is completed. The life
cycle of Thread is ended after execution of run() method. A Thread is moved into dead state if it
returns the run() method.

How to create thread:


There are two ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface.

Thread class or Runnable interface:


Thread class provide constructors and methods to create and perform operations on a
thread. Thread class extends Object class and implements Runnable interface.
The Runnable interface should be implemented by any class whose instances are intended
to be executed by a thread. Runnable interface have only one method named run().
public void run(): is used to perform action for a thread.

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.

Create Thread by Implementing Runnable Interface:


If your class is intended to be executed as a thread then you can achieve this by
implementing Runnable interface. You will need to follow three basic steps:
Step 1:
As a first step you need to implement a run() method provided by Runnable interface. This
method provides entry point for the thread and you will put you complete business logic inside
this method. Following is simple syntax of run() method:
public void run( )
Step 2:
At second step you will instantiate a Thread object using the following constructor:
Thread(Runnable threadObj, String threadName);

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...");
}

public static void main(String args[]){


Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
t1.start();
}
}
Output: thread is running...

Create Thread by Extending Thread Class:


The second way to create a thread is to create a new class that extends Thread class
using the following two simple steps. This approach provides more flexibility in handling
multiple threads created using available methods in Thread class.
Step 1
You will need to override run( ) method available in Thread class. This method
provides entry point for the thread and you will put you complete business logic inside this
method. Following is simple syntax of run() method:
public void run( )
Step 2
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: 38
class Multi extends Thread{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();

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.

Example 39: Multithreading example with Synchronization:

class ThreadSynchronization
{
public static void main(String args[])

Page 95
J2SE (Core JAVA) Notes

MyThread thread1 = new MyThread("thread1: ");


MyThread thread2 = new MyThread("thread2: ");
thread1.start();
thread2.start();
boolean thread1IsAlive = true;
boolean thread2IsAlive = true;
do {
if (thread1IsAlive && !thread1.isAlive()) {
thread1IsAlive = false;
System.out.println("Thread 1 is dead.");
}
if (thread2IsAlive && !thread2.isAlive()) {
thread2IsAlive = false;
System.out.println("Thread 2 is dead.");
}
} while(thread1IsAlive || thread2IsAlive);
}
}
class MyThread extends Thread
{
static String message[] =
{ "Java", "is", "hot,", "aromatic,", "and", "invigorating."};
public MyThread(String id)
{
super(id);
}
public void run()
{
SynchronizedOutput.displayList(getName(),message);
}
void randomWait()
{
try {

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.

Example of Deadlock in java 40:

public class TestDeadlockExample1 {


public static void main(String[] args) {
final String resource1 = "ratan jaiswal";
final String resource2 = "vimal jaiswal";
// t1 tries to lock resource1 then resource2
Thread t1 = new Thread() {
public void run() {
synchronized (resource1) {
System.out.println("Thread 1: locked resource 1");

Page 98
J2SE (Core JAVA) Notes

try { Thread.sleep(100);} catch (Exception e) {}

synchronized (resource2) {
System.out.println("Thread 1: locked resource 2");
}
}
}
};

// t2 tries to lock resource2 then resource1


Thread t2 = new Thread() {
public void run() {
synchronized (resource2) {
System.out.println("Thread 2: locked resource 2");

try { Thread.sleep(100);} catch (Exception e) {}

synchronized (resource1) {
System.out.println("Thread 2: locked resource 1");
}
} }
};

t1.start();
t2.start();
}
}

Output: Thread 1: locked resource 1


Thread 2: locked resource 2

Inter-thread communication in Java:


Inter-thread communication or Co-operation is important when you develop an
application where two or more threads exchange some information.

Cooperation (Inter-thread communication) is a mechanism in which a thread is paused


running in its critical section and another thread is allowed to enter (or lock) in the same critical
section to be executed. It is implemented by following methods of Object class:

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.

Syntax: public final void notify()

3) notifyAll() method:

Wakes up all threads that are waiting on this object's monitor.


Syntax: public final void notifyAll()

Difference between wait and sleep?


Let's see the important differences between wait and sleep methods.

wait() sleep()
wait() method releases the lock sleep() method doesn't release the lock.

is the method of Object class is the method of Thread class

is the non-static method is the static method

is the non-static method is the static method


should be notified by notify() or notifyAll() after the specified amount of time, sleep is
methods completed.

Example of inter thread communication in java (41 ):

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;

public synchronized void Question(String msg) {


if (flag) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(msg);
flag = true;
notify();
}

public synchronized void Answer(String msg) {


if (!flag) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

System.out.println(msg);
flag = false;
notify();
}
}

class T1 implements Runnable {


Chat m;
String[] s1 = { "Hello", "How are you ?", "I am also doing fine!" };

public T1(Chat m1) {


this.m = m1;
new Thread(this, "Question").start();
}

public void run() {


for (int i = 0; i < s1.length; i++) {
m.Question(s1[i]);
}
}
}

class T2 implements Runnable {


Chat m;

Page 101
J2SE (Core JAVA) Notes

String[] s2 = { "Hi", "I am good, what about you?", "Great!" };

public T2(Chat m2) {


this.m = m2;
new Thread(this, "Answer").start();
}

public void run() {


for (int i = 0; i < s2.length; i++) {
m.Answer(s2[i]);
}
}
}
public class TestThread {
public static void main(String[] args) {
Chat m = new Chat();
new T1(m);
new T2(m);
}
}

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

Introduction to IO Stream class:

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.

Introduction to Reader and Writer classes:


Reader classes are similar to input streams, and writer classes are similar to output
streams. Reader classes descend from the abstract Reader class, whereas the Writer classes
descend from the abstract Writer class.

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;

public class CopyFile {


public static void main(String args[]) throws IOException
{
FileInputStream in = null;
FileOutputStream out = null;

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:

This is test for copy file.


As a next step, compile above program and execute it, which will result in creating output.txt file
with the same content as we have in input.txt.
Character Streams:

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:

This is test for copy file.


As a next step, compile above program and execute it, which will result in creating output.txt file
with the same content as we have in input.txt.

Program to read from a file using BufferedReader class

import java. Io *;

class ReadTest

public static void main(String[] args)

try

File fl = new File("d:/myfile.txt");

BufferedReader br = new BufferedReader(new FileReader(fl)) ;

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

Random Access File:


The streams what you have learnt can read or write sequentially only (i.e byte by byte in
sequence). We cannot jump to any part of a file. That is, with these streams we cannot
access(either read or write) a file randomly. Java designers introduced a special class,
RandomAccessFile. I call it a special class for the following reasons:

 It can go to any point in a file.

 Unlike earlier streams(that can read only or write only), this class can read and write also.

 It can read or write at any particular point, very precisely.

 This class is not included in java.io. package.

Public class RandomAccessFile extends Object implements DataInput and DataOutput

Modes of opening a file with RandomAccessFile:

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.

Some special methods that come with RandomAccessFile:

public void seek(long skipbytes) : skip the specified bytes in a file


public long getFilePointer( ) : returns the location of file pointer in the file.
Reading starts from the file pointer
position.
Serialization:
Introduction to Object Serialization:

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;

public class Employee implements java.io.Serializable


{
public String name;
public String address;
public transient int SSN;
public int number;
public void mailCheck()
{
System.out.println("Mailing a check to " + name
+ " " + address);
}
}
Notice that for a class to be serialized successfully, two conditions must be met:
 The class must implement the java.io.Serializable interface.

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.*;

public class SerializationSample


{
public static void main(String [] args)
{
Employee e = new Employee();
e.name = "Raj kumar sing";
e.address = "MilkywayINS Hyderabad";
e.SSN = 11122333;
e.number = 101;
try
{
FileOutputStream fileOut =
new FileOutputStream("E:\\employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in E:\\employee.ser");
}catch(IOException i)
{
i.printStackTrace();
}
}
}

Output: Serialized data is saved in E:\employee.ser

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.*;

public class DeserializeDemo


{
public static void main(String [] args)
{
Employee e = null;

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);
}
}

Output: Deserialized Employee...


Name: Raj kumar King
Address: MilkywayINS Hyderabad
SSN: 0
Number: 101

Page 110
J2SE (Core JAVA) Notes

Transient Fields and Java Serialization


The transient keyword is a modifier applied to instance variables in a class. It specifies
that the variable is not part of the persistent state of the object and thus never saved during
serialization.
You can use the transient keyword to describe temporary variables, or variables that contain
local information,
such as a process ID or a time lapse.
EXAMPLE:
class studentinfo implements Serializable
{
String name;
transient int rid;
static String contact;
}
 Making a data member transient will prevent its serialization.
 In this example rid will not be serialized because it is transient, and contact will also
remain unserialized because it is static.
Serialization Real-time scenarios:

Lets see couple of different scenarios (examples) where we use serialization.

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.

The collections framework was designed to meet several goals.


 The framework had to be high-performance. The implementations for the fundamental
collections (dynamic arrays, linked lists, trees, and hashtables) are highly efficient.
 The framework had to allow different types of collections to work in a similar manner
and with a high degree of interoperability.
 Extending and/or adapting a collection had to be easy.
Towards this end, the entire collections framework is designed around a set of standard
interfaces. Several standard implementations such as LinkedList, HashSet, and TreeSet, of
these interfaces are provided that you may use as-is and you may also implement your own
collection, if you choose.

What Is a Collections Framework?


A collections framework is a unified architecture for representing and manipulating
collections. All collections frameworks contain the following:
 Interfaces: These are abstract data types that represent collections. Interfaces allow
collections to be manipulated independently of the details of their representation. In
object-oriented languages, interfaces generally form a hierarchy.
 Implementations, i.e., Classes: These are the concrete implementations of the collection
interfaces. In essence, they are reusable data structures.
 Algorithms: These are the methods that perform useful computations, such as searching
and sorting, on objects that implement collection interfaces. The algorithms are said to be
polymorphic: that is, the same method can be used on many different implementations of
the appropriate collection interface.
In addition to collections, the framework defines several map interfaces and classes.
Maps store key/value pairs. Although maps are not collections in the proper use of the term, but
they are fully integrated with collections.

Page 112
J2SE (Core JAVA) Notes

Benefits of Collections Framework


The Collections Framework provides the following benefits.

 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.

Drawbacks of the Collections Framework


Historically, collections frameworks have been quite complex, which gave them a
reputation for having a steep learning curve. We believe that Java's new Collections Framework
breaks with this tradition, as you will learn for yourself in this appendix.

Page 113
J2SE (Core JAVA) Notes

Core Collection Interfaces:


The core collection interfaces are used to manipulate collections and to
pass them from one method to another. The basic purpose of these interfaces is to allow
collections to be manipulated independently of the details of their representation. The core
collection interfaces are the heart and soul of the Collections Framework. When you understand
how to use these interfaces, you know most of what there is to know about the framework

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.*;

public class LinkedListDemo {

public static void main(String args[]) {


// create a linked list
LinkedList ll = new LinkedList();
// add elements to the linked list
ll.add("F");

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);

// remove elements from the linked list


ll.remove("F");
ll.remove(2);
System.out.println("Contents of ll after deletion: "
+ ll);

// remove first and last elements


ll.removeFirst();
ll.removeLast();
System.out.println("ll after deleting first and last: "
+ ll);

// get and set a value


Object val = ll.get(2);
ll.set(2, (String) val + " Changed");
System.out.println("ll after change: " + ll);
}
}
Output:
Original contents of ll: [A, A2, F, B, D, E, C, Z]
Contents of ll after deletion: [A, A2, D, E, C, Z]
ll after deleting first and last: [A2, D, E, C]
ll after change: [A2, D, E Changed, C]

The List Interface:


The List interface extends Collection and declares the behavior of a collection that
stores a sequence of elements.

 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.*;

public class CollectionsDemo {

public static void main(String[] args) {


List a1 = new ArrayList();
a1.add("Ramu");
a1.add("Raju");
a1.add("Ravi");
System.out.println(" ArrayList Elements");
System.out.print("\t" + a1);

List l1 = new LinkedList();


l1.add("Ramu ");
l1.add("Raju");
l1.add("Ravi");
System.out.println();
System.out.println(" LinkedList Elements");
System.out.print("\t" + l1);
}
}
Output: ArrayList Elements
[Ramu, Raju, Ravi]
LinkedList Elements
[Ramu, Raju, Ravi]

The Set Interface:


A Set is a Collection that cannot contain duplicate elements. It models the mathematical
set abstraction.
The Set interface contains only methods inherited from Collection and adds the
restriction that duplicate elements are prohibited.
Set also adds a stronger contract on the behavior of the equals and hashCode operations,
allowing Set instances to be compared meaningfully even if their implementation types differ.
Here is first a simple Java Set example to give you a feel for how sets work:
Set setA = new HashSet();
String element = "element 1";
setA.add(element);
System.out.println( set.contains(element) );
This example creates a HashSet which is one of the classes in the Java APIs that implement the
Set interface. Then it adds a string object to the set, and finally it checks if the set contains the
element just added.
Generic Sets:

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.*;

public class SetDemo {

public static void main(String args[]) {


int count[] = {34, 22,10,60,30,22};
Set<Integer> set = new HashSet<Integer>();
try{
for(int i = 0; i<5; i++){
set.add(count[i]);
set.iterator();
}
System.out.println(set);

TreeSet sortedSet = new TreeSet<Integer>(set);


System.out.println("The sorted list is:" + sortedSet);

System.out.println("The First element of the set is: "+


(Integer)sortedSet.first());
System.out.println("The last element of the set is: "+
(Integer)sortedSet.last());

}
catch(Exception e){}
}
}

Output: [34, 22, 10, 30, 60]


The sorted list is: [10, 22, 30, 34, 60]

The First element of the set is: 10


The last element of the set is: 60

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.*;

public class SetDemo {

public static void main(String args[]) {


int count[] = {34, 22,10,60,30,22};
Set<Integer> set = new HashSet<Integer>();
try{
for(int i = 0; i<5; i++){
set.add(count[i]);
}
System.out.println(set);

TreeSet sortedSet = new TreeSet<Integer>(set);


System.out.println("The sorted list is:");
System.out.println(sortedSet);

System.out.println("The First element of the set is: "+


(Integer)sortedSet.first());
System.out.println("The last element of the set is: "+
(Integer)sortedSet.last());
}
catch(Exception e){}
}
}
OutPut: [34, 30, 60, 10, 22]
The sorted list is:
[10, 22, 30, 34, 60]
The First element of the set is: 10
The last element of the set is: 60

Difference between HashSet and TreeSet:


HashSet TreeSet

 In HashSet elements are unordered  In TreeSet elements are in sorted ordered


 In HashSet you can add different types  In TreeSet you can’t add different types of

Page 119
J2SE (Core JAVA) Notes

of object object; you can add only similar types of


object.
 It extends AbstractSet and implements
 It extends AbstractSet SortedSet.
 The operations like insertion, deletion and
modifications take very less time.

 The operations like insertion, deletion


and modifications takes more amount
of time.

The Map Interface:

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.*;

public class CollectionsDemo {

Page 120
J2SE (Core JAVA) Notes

public static void main(String[] args) {


Map m1 = new HashMap();
m1.put("Zara", "8");
m1.put("Mahnaz", "31");
m1.put("Ayan", "12");
m1.put("Daisy", "14");
System.out.println();
System.out.println(" Map Elements");
System.out.print("\t" + m1);
}
}
Output: Map Elements

{Mahnaz=31, Ayan=12, Daisy=14, Zara=8}

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.*;

public class SortedMapExample {

public static void main(String[] args) {

SortedMap map = new TreeMap();


// Add some elements:
map.put("2", "Two");
map.put("1", "One");
map.put("5", "Five");
map.put("4", "Four");
map.put("3", "Three");

// Display the lowest key:


System.out.println("The lowest key value is: " + map.firstKey());

// Display the highest key:


System.out.println("The highest key value is: " + map.lastKey());

// Display All key value

Page 121
J2SE (Core JAVA) Notes

System.out.println("All key value is:\n" + map);

// Display the headMap:


System.out.println("The head map is:\n" + map.headMap("4"));

// Display the tailMap:


System.out.println("The tail map is:\n" + map.tailMap("4"));

// 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

Difference between HashMap and HashTable


HashMap HashTable
 HashMap is a class in collection frame  HashTable is a legacy class which was
work. reengineered as collection frame work
class.
 Object of HashMap are not synchronized  Object of HashTable are synchronized by
by default default
 HashMap allows null key and null values  HashTable doesn’t allow null key and null
values.
Enumeration Interface (legacy interface):
The Enumeration interface defines the methods by which you can enumerate (obtain one
at a time) the elements in a collection of objects.
This legacy interface has been superceded by Iterator. Although not deprecated,
Enumeration is considered obsolete for new code. However, it is used by several methods

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.

The Collection Classes:


List interface three concrete subclasses :
 Linked list
 Array list
 Vector

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)

Difference between array list and linked list :

Array list Linked list

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

Set has three subclasses:


 HashSet
 TreeSet
 LinkedHashSet

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.

Source code of HashSet:


public HashSet(int initialCapacity) {
map = new HashMap<E,Object>(initialCapacity);
}

Example:

import java.util.*;
public class HashSetDemo {

public static void main(String args[]) {


// create a hash set
HashSet hs = new HashSet();
// add elements to the hash set
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");

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

 HashMap is a class in collection frame  HashTable is a legacy class which was


work. reengineered as collection frame work
class.
 Object of HashMap are not synchronized
by default  Object of HashTable are synchronized
by default
 HashMap allows null key and null
values  HashTable doesn’t allow null key and
null values.

Page 126
J2SE (Core JAVA) Notes

Similaritys on HashMap and HashTable:


 Both are used to store key value pairs.
 Both allows duplicate values
 Both doesn’t allow duplicate key
 Both allows different types of object as key
 Both are unordered.

Difference between HashMap and TreeMap:


HashMap TreeMap

 HashMap is unordered  TreeMap elements are in sorted ordered in


 HashMap allows null keys. term of keys.
 HashMap allows different type of  TreeMap doesn’t allow null keys.
keys.  TreeMap allows only similar types of keys

Similaritys on HashMap and TreeMap:

 Both are used to store key value pairs

 Both are allow null value.

 Both doesn’t allows duplicate key.

 Both allow duplicate values.

Difference between iterator and enumeration:


Iterator Enumeration
 Iterator is a collection framework.  Enumeration is a legacy interface

 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.

Advantage of properties file:

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.

Method of Collections class for sorting List 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.

Syntax of compare method


public int compare(Object obj1,Object obj2): compares the first object with second object.
New Features in Java

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:

There are two ways to use assertion. First way is:


assert expression;

and second way is:


assert expression1 : expression2;

Example of Assertion in java:


import java.util.Scanner;

class AssertionExample{
public static void main( String args[] ){

Scanner scanner = new Scanner( System.in );


System.out.print("Enter ur age ");

int value = scanner.nextInt();


assert value>=18:" Not valid";

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.

Compile it by: javac AssertionExample.java

Run it by: java -ea AssertionExample

Output: Enter ur age 11

Exception in thread "main" java.lang.AssertionError: Not valid

Where not to use Assertion:

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)

 Static Import (Java 5)

 Autoboxing and Unboxing (Java 5)

 Enum (Java 5)

 Covariant Return Type (Java 5)

 Annotation (Java 5)

 Generics (Java 5)

For-each loop (Advanced or Enhanced For loop):

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.

Advantage of for-each loop:


 It makes the code more readable.

Page 130
J2SE (Core JAVA) Notes

 It elimnates the possibility of programming errors.

Syntax of for-each loop:

1. for(data_type variable : array | collection){}

Variable Argument (Varargs):

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:

return_type method_name(data_type... variableName){}

Example of Varargs:

class VarargsExample1{

static void display(String... values){


System.out.println("display method invoked ");
}

public static void main(String args[]){

display();//zero argument
display("my","name","is","varargs");//four arguments
}
}

Rules for varargs:


While using the varargs, you must follow some rules otherwise program code won't
compile. The rules are as follows:
 There can be only one variable argument in the method.
 Variable argument (varargs) must be the last argument.

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.

Advantage of static import:


 Less coding is required if you have access any static member of a class oftenly.

Disadvantage of static import:


 If you overuse the static import feature, it makes the program unreadable and
unmaintainable.

Example of static import:


import static java.lang.System.*;

class StaticImportExample{

public static void main(String args[]){

out.println("Hello");//Now no need of System.out


out.println("Java");

}
}

Output: Hello

Java

What is the difference between import and static import?


The import allows the java programmer to access classes of a package without package
qualification whereas the static import feature allows to access the static members of a class
without the class qualification. The import provides accessibility to classes and interface whereas
static import provides accessibility to static members of the class.

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.

Points to remember for Enum:


 enum improves type safety

Page 132
J2SE (Core JAVA) Notes

 enum can be easily used in switch


 enum can be traversed
 enum can have fields, constructors and methods
 enum may implement many interfaces but cannot extend any class because it internally
extends Enum class

Example of enum in java:


class EnumExample1{

public enum Season { WINTER, SPRING, SUMMER, FALL }

public static void main(String[] args) {


for (Season s : Season.values())
System.out.println(s);

}
}
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.

5. It may assign a default value to the method.

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.

Advantage of Java Generics:


There are mainly 3 advantages of generics. They are as follows:

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

2) Type casting is not required: There is no need to typecast the object.

Before Generics, we need to type cast.


List list = new ArrayList();
list.add("hello");
String s = (String) list.get(0);//typecasting
After Generics, we don't need to typecast the object.

List<String> list = new ArrayList<String>();


list.add("hello");
String s = list.get(0);

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.

List<String> list = new ArrayList<String>();


list.add("hello");
list.add(32);//Compile Time Error

Syntax to use generic collection


ClassOrInterface<Type>

Example to use Generics in java

ArrayList<String>

Example of Generic class:


package Collections;

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

String s=list.get(1);//type casting is not required


System.out.println("element is: "+s);

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

You might also like