Topics that are going to be covered…
Java Introduction, Structure of Java Application, JVM
Java Buzz Words, Data Types
Class, Objects, Naming Conventions
Control Statements, Scanner Class
Access Modifiers, Type Casting
Strings, Wrapper Classes
Introduction to OOPs
‘Constructor’, ‘Super’ & ‘This’ Key words, Garbage Collection
‘Method Over Loading’ & ‘Method Over Riding’
‘Static’ & ‘Final’ Key Words, ‘Abstract Classes’ & ‘Interfaces’
‘Arrays’, ‘Threads’, ‘Packages’, ‘Exceptions’, ‘Collections’
Working With Files, Applets, AWT, Swings, Networking
Java History
Computer language innovation and development occurs for
two fundamental reasons:
1) to adapt to changing environments and uses
2) to implement improvements in the art of programming
The development of Java was driven by both in equal
measures.
Many Java features are inherited from the earlier languages:
B → C → C++ → Java
Before Java: C
Designed by Dennis Ritchie in 1970s.
Before C: BASIC, COBOL, FORTRAN, PASCAL
C- structured, efficient, high-level language that could replace
assembly code when creating systems programs.
Designed, implemented and tested by programmers.
Before Java: C++
Designed by Bjarne Stroustrup in 1979.
Response to the increased complexity of programs and
respective improvements in the programming paradigms and
methods:
1) high-level language
2) structured programming
3) object-oriented programming (OOP)
OOP – methodology that helps organize complex programs
through the use of inheritance, encapsulation and
polymorphism.
C++ extends C by adding object-oriented features.
Java: History
In 1990, Sun Microsystems started a project called Green.
Objective: to develop software for consumer electronics.
Project was assigned to James Gosling, a veteran of classic
network software design. Others included Patrick Naughton,
ChrisWarth, Ed Frank, and Mike Sheridan.
The team started writing programs in C++ for embedding into
– toasters
– washing machines
– VCR’s
Aim was to make these appliances more “intelligent”.
Java: History (contd.)
C++ is powerful, but also dangerous. The power and popularity of
C derived from the extensive use of pointers. However, any
incorrect use of pointers can cause memory leaks, leading the
program to crash.
In a complex program, such memory leaks are often hard to
detect.
Robustness is essential. Users have come to expect that Windows
may crash or that a program running under Windows may crash.
(“This program has performed an illegal operation and will be
shut down”)
However, users do not expect toasters to crash, or washing
machines to crash.
A design for consumer electronics has to be robust.
Replacing pointers by references, and automating memory
management was the proposed solution.
Java: History (contd.)
Hence, the team built a new programming language called Oak, which
avoided potentially dangerous constructs in C++, such as pointers,
pointer arithmetic, operator overloading etc.
Introduced automatic memory management, freeing the programmer to
concentrate on other things.
Architecture neutrality (Platform independence)
Many different CPU’s are used as controllers. Hardware chips are
evolving rapidly. As better chips become available, older chips become
obsolete and their production is stopped. Manufacturers of toasters and
washing machines would like to use the chips available off the shelf, and
would not like to reinvest in compiler development every two-three
years.
So, the software and programming language had to be architecture
neutral.
Java: History (contd)
It was soon realized that these design goals of consumer electronics perfectly suited
an ideal programming language for the Internet and WWW, which should be:
❖ object-oriented (& support GUI)
❖ – robust
❖ – architecture neutral
Internet programming presented a BIG business opportunity. Much bigger than
programming for consumer electronics.
Java was “re-targeted” for the Internet
The team was expanded to include Bill Joy (developer of Unix), Arthur van Hoff,
Jonathan Payne, Frank Yellin, Tim Lindholm etc.
In 1994, an early web browser called WebRunner was written in Oak. WebRunner
was later renamed HotJava.
In 1995, Oak was renamed Java.
A common story is that the name Java relates to the place from where the
development team got its coffee. The name Java survived the trade mark search.
Key Points
James Gosling, Mike Sheridan, and Patrick Naughton
commenced the Java language project in June 1991.
The small team of sun engineers called Green Team.
The first name of java is “Green Talk” later changed to “OAK”
which was changed to “JAVA” in the year 1995.
The first extension of java program is ‘.gt’
The first browser which was developed using java language is
“Hot Java Browser”.
The first version of java is JDK 1.0 and the latest version is
Java SE 16
Java Version History
Version Release Date
JDK 1.0 January 23, 1996
JDK 1.1 February 19, 1996
J2SE 1.2 December 8, 1998
J2SE 1.3 May 8, 2000
J2SE 1.4 February 6, 2002
J2SE 5.0 September 30, 2004
Java SE 6 December 11, 2006
Java SE 7 July 28, 2011
Java SE 8 March 18, 2014
Java SE 9 September 21, 2017
Java SE 10 March 20, 2018
Java SE 11 September , 2018
Java SE 12 March 19, 2019
Java SE 15 September 2020
Java SE 13 September 17, 2019
Java SE 16 March 2021
Java SE 14 March 17, 2020
C Vs C++ Vs Java
Feature C C++ Java
Developed By (&) Dennis Ritchie Bjarne Stroustrup James Gosling
Year 1972 1979 1991
Model Procedural Object Oriented Object Oriented
Platform Dependent Dependent Independent
Dependency
Keywords 32 63 50 (goto & const are
reserved keywords)
Pre-processor Supported (#include, Supported (#include, Not Supported
directives #define) #define)
Inheritance Not Supported Supported Multiple Inheritance
is not supported
Pointers Supported Supported Eliminated & are
replaced with
references
Note: reference is the address of the memory location where the object is stored
Types of Applications
Generally all the Projects or Applications are divided in to ‘3’
types.
1. Console Based applications
2. Standalone / Desktop applications
3. Web Based applications
Console Based Applications :-
A console based application is a computer program designed
to be used with the help of command line interface of some
operating systems.
A user typically interacts with a console application using only
a keyboard and display screen, as opposed to GUI
applications, which normally require the use of a mouse or
other pointing device.
As the speed and ease-of-use of GUIs applications have
improved over time, the use of console applications has
greatly diminished, but not disappeared.
Standalone / Desktop applications :-
An application that can only be executed in local system
with local call is called an Standalone / Desktop
applications .
These can be executed independently.
We don’t require an web server or application server for
executing these applications.
Web Based applications :-
Web Based applications 100% requires browser
support and an application server for their execution.
Web based application refers to any program that is
accessed over a network using HTTP (Hyper Text Transfer
Protocol).
These are usually based on the client-server architecture
Basic java programming elements
Syntax for Class: Syntax for Interface: Syntax for enum:
class <className> interface <interfaceName> enum <enumName>
{ { {
----; ----; ----;
----; ----; ----;
} } }
Understanding JVM
What is JVM in Java ?
Different components of JVM ?
Difference between JVM, JRE, and JDK?
INTRO:
➢ Java Virtual Machine (JVM) is an virtual machine that resides on your computer and
provides a runtime execution environment for the Java bytecode to get executed.
➢ The basic function of JVM is to execute the compiled .class files (i.e. the bytecode) and
generate an output.
➢ JVM is PLATFORM DEPENDENT where as JAVA is PLATFORM IN-DEPENDENT
Internal architecture of JVM
Class Loader:
The class loader subsystem is used for loading/reading the .class files and saving the
bytecode in the JVM method area. It performs three basic activities in following order
• Loading (imports the data)
• Linking (performs verification)
• Initialization (Invokes class variables)
Class / Method Area:
This component holds the class level data of each .class file such as metadata,static
variables, the code for the methods etc.
Heap Area:
This component is a part of JVM memory where all the objects and its corresponding
instance variables and arrays are stored.
Stack Area:
While running a method, it needs some more memory to store the data and results. This
memory is allotted on Java Stacks. [This area plays an important role during the method
invocation and returns.]
PC Registers:
This component holds the address of the JVM instruction which is currently executing. Each
thread in Java has its own PC register to hold the address of the currently executing
instruction
Native Method Stacks:
This component is written in a different language and holds the native method information.
Execution Engine:
This component executes the bytecode which is assigned to the runtime data areas and has
two major sub-components i.e.:
• Interpreter: This component reads the bytecode instructions and executes them
in a sequential manner.
• Garbage Collection: This component is a part of execution engine which frees
up the memory by collecting and removing the unreferenced objects
Native Method Interface:
This allows the Java code to call or be called by the libraries and the native
applications (i.e. the programs specific to the hardware and the OS of a system).
Native Method Libraries:
This component is a collection of native C, C++ libraries which are required by the
execution engine.
JVM vs. JRE vs. JDK
Java Virtual Machine (JVM):
JVM is a virtual machine which provides a runtime environment for executing the Java
bytecode
Java Runtime Environment (JRE):
JRE is an environment within which the JVM runs and has class libraries and other files
that Java Virtual Machine uses at the time of execution.
JRE = Java Virtual Machine (JVM) + Libraries to run the application
Java Development Kit (JDK):
JDK is the parent set of the JRE and has everything that JRE contains along with the
development tools such as a compiler, debugger etc.
JDK = Java Runtime Environment (JRE) + Development tools
The Java Buzzwords
The key considerations were summed up by the Java team
in the following list of buzzwords:
❖ Simple
❖ Object-oriented
❖ Robust
❖ Multithreaded
❖ Architecture-neutral
❖ Interpreted & High performance
❖ Distributed
❖ Dynamic
❖ Secure
❖ Portability
CLASS
• Class is blue print or an idea of an Object
• From One class any number of Instances can be
created
• It is an encapsulation of attributes and methods
class
Flower
Ob1 Ob3
Rose Ob2 Lilly
Jasmine
Understanding Object class
Object class, is present in the java.lang package, is the
first class in the java class hierarchy.
Every class either Predefined or User Defined is the sub
class for Object class.
Object class has "11" important methods, As this is the
super class for all the classes we can use (Override) those
methods in all the class.
In those “11” methods there are “5” final methods for
which we can’t provide override.
Method Name Description
public int hashCode() Returns a hash code value for the object
protected void finalize() throws
Called by the garbage collector
Throwable
public boolean equals(Object obj) Used for comparing two Objects
protected Object clone() throws
Creates exact copy of the object
CloneNotSupportedException
Returns a string representation of the
public String toString()
object.
public final Class getClass() Returns present class reference
public final void notify()
public final void notifyAll()
All these methods are used in java
public final void wait()
multithreading, which plays a crucial
public final void wait(long timeout) role in synchronization.
public final void wait(long timeout, int
nanos)
Object:
Objects are created from a class
To create an object of a Class, specify the class name, followed
by the object/reference name, and use the keyword “new” (We
can initialize that object by using constructors).
We can create multiple objects of one class.
Note: reference is the address of the memory location where the
object is stored
Variable:
A variable provides identity to memory location
Using variables we can process the information easily
Variables can also be called as References & Identifiers
Understanding Identifier :
➢ A name in JAVA program is called identifier.
➢ It may be class name, method name, variable name.
Rules [8]:
✓ The only allowed characters in java identifiers are:
1) a to z
2) A to Z
3) 0 to 9
4) _(underscore) and $
✓ If we are using any other symbols we will get compile time error.
✓ We can’t start a JAVA Identifier with number.
✓ Java Identifiers are case sensitive (Actually JAVA itself is a case sensitive)
✓ We can take our own length for the name of an JAVA identifier.
✓ We can’t use JAVA language keywords (50) as identifiers.
✓No space is allowed between the characters of an identifier
✓ All predefined JAVA class names and interface names we can use as identifiers (X)
Which of the following are valid Java Identifiers?
➢ _$_
➢ Mou$e
➢ Java4All
➢ Student@NareshIt
➢ 999aaa
➢ Display#
➢ String
➢ Byte
➢ byte
➢ Integer
➢ pro1
Understanding Separators
Separator Description
; Semicolon Terminates statements
, Comma Separates consecutive identifiers in a variable declaration.
{} Braces Define a block of code, for classes, methods and values of arrays
Parentheses Parameters in methods, Precedence in expressions,
()
Control statements
[] Brackets Declare array types, dereference array values
Period is used to separate package, sub-packages and classes, variable
.
or method from reference
Understanding Java Method
• The only required elements of a method declaration are the method's return type,
method name, a pair of parentheses-(), and a body between braces - {}.
• The method declarations have six components, in order:
1. Modifiers :- such as public, private, protected and default.
2. The return type :- the data type of the value returned by the method, or void if
the method does not return a value.
3. The method name :- The rules for field names apply to method names as well
4. The parameter list in parenthesis :- a comma is used if you are giving more than
one parameter. If there are no parameters, you must use empty parentheses.
5. An exception list :- to be discussed later.
6. The method body, enclosed between braces :- the method's code or logic.
• In general there are two types of methods, User defined and predefined methods.
Returning a Value from a Method
• A method returns to the code that invoked it when it:
➢ Completes all the statements in the method,
➢ Reaches a return statement, or
➢ throws an exception (covered later),
-Which ever occurs first
Rules:
1. We can declare a method's return type in its method declaration.
2. Inside the body of the method, we should use the 'return' statement to return the
value of the return type.
3. Any method declared as 'void' doesn't return any value.
4. void methods don't require any return statement.
5. Any method that is not declared as void must contain a return statement
with its corresponding return value.
6. The data type of the return value must match the method's declared return
type.
7. Method return types can be 8 Primitive Datatypes + Void + Class And
Objects
Note: return statement need not to be last statement in a method, but it must
be last statement to execute in a method.
Understanding java main() method
• The Syntax of main method is ===> public static void main(String []args)
public : Anything declared as public can be accessed from anywhere, main method
should be available for other classes in the project. So main method “has” to be public
static : Static methods can be called directly with out creating a class object. So
when java execution starts, JVM will be able to start the main method.
void: A java program execution starts from main() method and ends with main()
method. So if main() method returns something there is no way of catching that
return statement. So always main() method return type is void.
main: This is the name of java main() method. It’s fixed and when we start a java
program, JVM checks for the main method.
String []args: Java main method accepts a “single” argument of type String array. This
is also called as java command line arguments.
Which of the following main() method syntax are valid?
1. public static void main(String[] args)
2. public static void main(String []args)
3. public static void main(String [] args)
4. public static void main(String args [])
5. public static void main([]String args)
6. public static void main(String[] Kishan)
7. static public void main(String[] args)
8. public static int main(String[] args)
9. public final static void main(String[] args)
10. Public static void main(String[] args)
11. final public static void main(String[] args)
12. Final public static void main(String[] args)
13. public static void main(String… args)
14. public static void mian(String[] args)
15. public static void main(String[8] args)
16. public static void main(int[] args)
17. public static void main()
18. public void main(String[] args)
19. public static void Main(String[] args)
Java Data Types
Data type specifies the size and type of values that can be
stored in an identifier
They are use full to represent how much memory is
required to hold the data.
Represents what type of data to be allowed.
Java data types are classified in to 2 types
--->Primitive Data types
---> User Defined Data types (Reference)
(String, Array, class, abstract class, interface…etc)
byte:
Size: 1byte (8bits)
➢
➢ Max-value: +127
➢ Min-value:-128
➢ Range:-128to 127[-27 to 27-1]
short:
➢ Size: 2 bytes
➢ Range: -32768 to 32767(-215 to 215-1)
int:
➢ Size: 4 bytes
➢ Range:-2147483648 to 2147483647 (-231 to 231-1)
long:
➢ Size: 8 bytes
➢ Range:-263 to 263-1
float:
➢ If we want 5 to 6 decimal places of accuracy then we
should go for float.
➢ Size:4 bytes.
➢ By default, floating point numbers are double in Java. (
you need to cast them explicitly or suffix with 'f' or 'F')
double:
➢ If we want to 14 to 15 decimal places of accuracy then we
should go for double
➢ Size:8 bytes
➢ double takes more space than float in Java
boolean:
➢ Either true or false
char:
➢ Size:2 bytes
➢ Range: 0 to 65535
Note:
➢Arithmetic operations return result in integer format
(int/long).
Understanding Java Keywords
There are 50 Java language keywords.
We cannot use any of the following as identifiers in your
programs.
1) Keywords for data types: (8)
2) Keywords for flow control:(11)
3) Keywords for modifiers:(11)
4) Keywords for exception handling:(6)
5) Class related keywords:(6)
6) Object related keywords:(4)
7) Void keyword(1)
8) Enum (1)
9) Reserved keywords (2)
,case
void--->It’s a return Type Keyword
goto & const ----> Not used in java (Reserved Keywords)
enum ---> It is used to define group of named constants
Comments:
In Java, comments are preceded by two slashes (//) in a line,
or enclosed between /* and */ in one or multiple lines.
When the compiler sees //, it ignores all text after // in the
same line.
When it sees /*, it scans for the next */ and ignores any text
between /* and */.
Variables:
Variables are nothing but reserved memory locations to
store values.
Variables are divided in to three types
1. Instance variables
2. Static variables
3. Local variables
Instance Variable:
The variables which are declared within the class but
outside of any method or block or constructor are called
“Instance Variables”
Instance variables can’t be accessed from static area
Static Variable:
A variable which is declared static is known as static variable.
Static variables will be created at the time of class loading and
destroyed at the time of class unloading hence the scope of the
static variable is exactly same as the scope of the .class file.
Static variables can never be local variables.
Static variables can be accessed from both instance and static
areas directly.
Local Variable:
Variables which are declared inside a method or block or
constructors such type of variables are called local
variables.
Scope of the local variables is exactly same as scope of
the block in which we declared.
The only valid modifier for local variables is final.
NOTE
➢ For the static and instance variables it is not required to
perform initialization explicitly, JVM will provide default
values. But for the local variables JVM won't provide any
default values compulsory we should perform
initialization explicitly before using that variable.
Understanding Java Constructor
“Constructor is a special type of method that is used to
initialize the object”.
Constructor is invoked at the time of object creation.
It constructs the values i.e. provides data for the object
that is why it is known as constructor.
Rules for creating constructor
There are basically two rules defined for the constructor.
➢ Constructor name must be same as its class name
➢ Constructor must have no return type
Types of Constructors:
Default Constructor:
➢ A constructor that have no parameter is known as default
constructor.
Parameterized Constructor:
➢ A constructor that have parameters is known as
parameterized constructor.
Key points:
Constructor can have all ‘4’ access modifiers (public, protected, private,
default).
If there is no constructor in a class, compiler automatically creates a default
constructor.
The access modifier for the default constructor provided by the compiler will
be SAME as the access modifier as class. (If the class is public then
constructor is also public OR If the class is default then constructor is also
default).
The default constructor given by the compiler will have only ‘2’ access
modifiers ie., public & default.
Compiler will provide a default constructor when there are no constructors in
the class.
We can code/write default constructor (or) parameterized constructor basing
upon our programming requirements.
If we declare a constructor as ‘private’ then we can restrict the object
creation of our class in other classes.
A Constructor is called simultaneously at the time of object creation by
using ‘new’ keyword.
In constructor we can write a ‘return’ statement without returning any value
(Just like void method).
We can create a class object by using “new” keyword and “available
constructor” .
CONSTRUCTOR OVERLOADING IS POSSIBLE OVERRIDDING IS
NOT POSSIBLE.
Constructor Vs Method
Constructor Method
Constructor is used to initialize the Method is used to expose
state of an object. behaviour of an object.
Constructor must not have return Method must have return type.
type.
Constructor is invoked implicitly. Method is invoked explicitly.
The java compiler provides a Method is not provided by
default constructor if you don't compiler in any case.
have any constructor.
Constructor name must be same as Method name may or may not be
the class name. same as class name.
Different modifiers allowed for variables and methods
Understanding Operators:
In java there are mainly ‘4’ types of operators. They are
➢Increment & Decrement Operators
➢Arithmetic Operators
➢Relational Operators
➢Logical Operators
Increment & Decrement operators (2)
➢ ++ is used as Increment operator (increases value by 1)
➢ -- is used as Decrement operator (decreases by 1)
➢ Both Increment & Decrement operators are classified in to
2 types.
Arithmetic Operators (5)
These are used to perform common mathematical
operations.
Operator Name Description Example
+ Addition Adds together x+y
two values
Subtracts one
- Subtraction value from x-y
another
* Multiplication Multiplies two x*y
values
Divides one value
/ Division from another x/y
Returns the x%y
% Modulus division
remainder
Relational Operators (6):
Relational Operators are used to compare two values
Operator Name Example
== Equal to x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y
Logical Operators (3)
These are used to determine the logic between variables.
Operator Name Description Example
Returns true if both
&& Logical and x < 5 && x < 10
statements are true
Returns true if one
|| Logical or of the statements is x < 5 || x < 4
true
Reverse the result,
! Logical not returns false if the !(x < 5 && x < 10)
result is true
Understanding Static
The static keyword is used in java mainly for memory
management.
It is used to define common functionalities of a java
application.
We may apply static keyword with variables, methods, blocks.
The static keyword belongs to the class rather than instance of
the class.
The static can be:
➢Variable
➢Method
➢Block
➢Main Method
Static Variable:
If you declare any variable as static, it is known static variable.
The static variable can be used to refer the common property of all objects.(eg:
company name of employees).
In java applications it is possible to access the static variables either by using the
respective class object reference (or) by using respective class name directly.
Static variables never be ‘local variables’.
JVM executes static members according to their priorities.
Static block and static variable will have equal priorities, so these execute in
defined order.
If a static variable and a local variable is having same name, Then compiler will
first search for local variable and then static variable.
For the static variables it is not required to perform
initialization explicitly jvm will always provide default
values.
If we declare a static variable as final then 100% we
should perform initialization explicitly whether we are
using or not otherwise we will get compile time error.
For final static variables JVM won't provide any default
values, JVM will provide default values only for static
variables.
Final static variables can be initialized inside a static
block. (any where else we will be getting compile time
error)
Static Method
If you apply static keyword with any method, it is known as static method
A static method can be invoked without the need for creating an instance of
a class.
static method can access static data member and can change the value of it.
In java applications it is possible to access the static methods either by
using the respective class object reference (or) by using respective class
name directly.
Restrictions for static method:
➢ The static method can not use non static data member or call non-static
method directly.
Static Method Vs Instance Method
Static Method Instance Method
A method i.e. declared as static is known as A method i.e. not declared as static is
static method. known as instance method
Object is not required to call static method. Object is required to call instance methods.
Non-static (instance) members cannot be static and non-static variables both can be
accessed in static context (static method, accessed in instance methods.
static block and static nested class) directly.
Static Block:
Is used to initialize the static data member.
We can not invoke a static block, rather JVM invokes the static block at the time of
class loading.
It is executed before main method at the time of class loading.
We can define more than one static block in the java program.
public class Demo
{
static
{
System.out.println("hi Static block is Invoked");
System.exit(0);
}
public static void main(String[] args)
{
System.out.println("hi from main method");
}
}
Understanding Type Casting
➢Converting one data type into another data type is
called casting.
➢In general there are two types of casting procedures.
✓ Implicit Type Casting
✓ Explicit Type Casting
Implicit Type Casting:
➢ Converting smaller data type to larger data types is called
“Implicit Type Casting”.
➢ It is also known as Widening or Casting-Upwards.
➢ There is no lose of information in this type casting.
byte -> short, int, long, float, double
short -> int, long, float, double
char -> int, long, float, double
int -> long, float, double
long -> float, double
float -> double
Explicit Type Casting
Converting larger data type to smaller data types is called “Explicit
Type Casting”.
It is also known as Narrowing or Casting-Downwards.
There may be a chance of lose of information in this type casting.
<Destination DataType> <variableName>=(DataType) <SourceType>
Ex: int i=90;
byte b = (byte)i;
byte -> char
short -> byte, char
char -> byte, short
int -> byte, short, char
long -> byte, short, char, int
float -> byte, short, char, int, long
double -> byte, short, char, int, long, float
In casting what happens if source variable has value
greater than the destination variable type range?
We will not get any compile time error or runtime error,
assignment will be performed by reducing its value in the
range of destination variable type range.
We can know the value by using the below formula
[minimumRange + (result - maximumRange - 1)]
Overview of Typecasting
Note: We can assign a number variable to character datatype but it should be in the
range between 0 to 65535 (Uni code character set range)
Understanding Wrapper Classes
In java technology if we want to represent a group of
objects in the form of an object then we have to use
“Collection objects”, like
➢ Array List
➢ Vector
➢ Stack
In java applications collections objects are able to allow
only group of other objects, not primitive data directly.
If we want to store primitive data in collection objects,
first we need to convert the primitive data in object
form then we have to store, that object data in collection
objects.
Java Technology has provided the following ‘8’ number of
Wrapper classes w.r.t to ‘8’ number of primitive data
types.
Points to remember…
All most all wrapper classes define 2 constructors one can
take corresponding primitive as argument and the other
can take String as argument.
(except Character)
Character class defines only one constructor which can
take char primitive as argument there is no String
argument constructor.
If we are passing String as an argument in Boolean
wrapper class then :
---> If the argument is true then the result also will be true
irrespective of the data and case sensitiveness
---> If the argument is false then the result also will be false
irrespective of the data and case sensitiveness
---> Other than true/false any other data will give you the
result as false.
Understanding Control Statements
Control flow statements, change or break the flow of
execution by implementing decision making, looping, and
branching your program to execute particular blocks of code
based on the conditions.
Java Provides ‘3’ types of control statements.
Selection Statements
Java selection statements allow to control the flow of
program’s execution based upon conditions known
only during run-time.
Java provides four selection statements:
1) if
2) if-else
3) if-else-if
4) switch
Understanding ‘if’ statement
The argument passing to the ‘if’ statement should be boolean
Syntax:
if(condition)
{
//executes this block if the result is ‘true’
}
else
{
//executes this block if the result is ‘false’
}
Both ‘else’ and braces are optional in if.
If we don’t write braces after if, we can write only one statement
which is dependent on ‘if’.
We should not declare any statement in that sentence.
Understanding Switch Statement
Unlike ‘if’ and ‘if-else’ statements, the switch
statement can have a number of possible execution
paths.
Switch accepts byte, short, char, and int
(1.4v) primitive data types, After jdk 1.5v it started
accepting its corresponding ‘wrapper classes’ also.
From jdk 1.7v switch started accepting ‘String’ also.
Switch case should be present in side a loop.
All the ‘cases’ and ‘default’ are optional in switch
statement.
Independent statements are not allowed inside switch.
Contd…
Every case label should be “compile time constant”.
We can use expressions in the switch statements and in
case labels also.
Case labels range should be with in the range of the
data type.
Switch will not allow duplicate case labels.
In the switch statement if any case got triggered then
from that case onwards all statements will be executed
until end of the switch (or) break
We can write default case only once.
The default statement is optional and can appear anywhere
inside the switch block.
Arrange the following such that the program output is 4 1 2.
switch(input) --------------1
{ --------------2
case 2: --------------3
System.out.print("2 "); --------------4
} --------------5
int input = 4; --------------6
// break; --------------7
case 1: --------------8
System.out.print("1 "); --------------9
default: --------------10
System.out.print(4); --------------11
Iteration Statements
Java iteration statements enable repeated execution of part of
a program until a certain termination condition becomes
true.
Java provides four iteration statements:
1) while
2) do-while
3) for
4) for each loop
Understanding while loop
while loop first checks the condition then enters in to the
loop
Just like ‘if’ statement, the argument should return
boolean value ie., true or false.
If we don’t write braces after while, we can write only one
statement which is dependent on ‘while’.
We should not declare any statement in that sentence.
Understanding do-while loop
do-while first enter the loop and then check the condition.
In do-while after the while condition we should write
semicolon Ex: while (i==0);
Understanding for loop
For loop consists of '3' statements ( Initilization, Test Condition, Increment /
Decrement operator)
In initialization section we can take any valid java statement.
Initialization will be executed only once in a loop.
In condition statement we can take any java expression which returns 'boolean' as
result.
If we are not taking any expression compiler will give 'true' as default value.
All 3 statements are optional in for loop.
If we our condition is always true then the code written out side the loop will be "Un-
reachable code" (Compile time error).
If we our condition is always false then the code written in side the loop will be "Un-
reachable code" (Compile time error).
Understanding for-each loop
For each Introduced in 1.5version, It acts as an alternative to
for loop, while loop etc for retrieving the elements in the array.
By using for-each loop we can easily retrieve the elements
easily from the arrays.
It cannot traverse the elements in reverse order because it does
not work on index values
For-each also acts as alternative for iterator when retrieving
elements from collections.
Syntax:
Step 1 :-Declare a variable that is the same type as the base type of
the array
Step 2 :-Write the Colon (:)
Step 3 :-Then write the array name
Step 4 :-In the loop body we have to use the variable which we
have created
Jump Statements
Java jump statements enable transfer of control to other
parts of program.
Java provides three jump statements:
1) break
2) continue
3) return
In addition, Java supports exception handling that can also
alter the control flow of a program.
Understanding break statement
The break statement is used to jump out of a loop.
When the break statement is encountered inside a
loop, the loop is immediately terminated and the
program control resumes at the next statement
following the loop.
We can us break statement inside "switch", "loops" &
"labeled blocks"., other than this if you are using any
where you will be getting an compile time error.
Understanding continue statement
Continue statement is used to skip current iteration and
continue for the next iteration in the loop.
We can us continue statement inside "loops" & "labeled
blocks"., other than this if you are using any where you will be
getting an compile time error.
Understanding Scanner Class
In java using different classes we can collect input from the
users.
Scanner class is available in ‘util’ package.
We can read input from the console using scanner class
It has been introduced in java 1.5 version.
Scanner class is capable of reading information from different
sources.
Steps:
1. import java.util.Scanner
2. create object of Scanner class
3. use pre-defined methods in the Scanner class to take input
--->nextInt();
--->next();
Scanner Class Methods
Package in Java
A package is a group of similar types of classes, interfaces and sub-packages.
Package can be categorized in two form, built-in package and user-defined
package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io,
util, sql etc.
Java API is having nearly 5000 pre defined packages.
Package statement will be the first statement in a java program.
We can access the members of one class from another class of same package.
‘import’ statement is used to connect classes in java application of different
packages.
Some Important Packages
Package Description
java.lang Lang stands for ‘language’ ,this got primary classes and interfaces essential for
developing a basic java program
java.util Util stands for ‘utility’, This package contains useful classes and interfaces like
Stack, LinkedList, Hashtable, etc … These classes are called collections.
java.io Io stands for ‘input and output’. This package contains streams.
java.awt awt stands for ‘abstract window toolkit’. This package helps to develop GUI.
javax.swing This package helps to develop GUI like java.awt. The ‘x’ in javax represents that
it is an extended package.
java.net net stands for ‘network’. Client-Server programming can be done by using this
package.
java.applet Applets are programs which came from a server into a client and get executed
on the client machine on a network.
java.text This package has two important classes, DateFormat and NumberFormat.
java.sql Sql stands for ‘structured query language’. This package helps to connect to
databases.
Structure of a package
Simple example of package
The package keyword is used to create a package.
//save as Simple.java
package mypack;
public class Simple
{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
How to access package from another package?
There are three ways to access the package from outside
the package.
✓import packageName.*;
✓import packageName.classname;
✓fully qualified Classname
Using packagename.*
If you use packagename.* 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.
//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 packagename.classname then only declared class
of this package will be accessible.
//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.
//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
Understanding Access Modifiers
Access modifiers determine whether other classes can use
a particular field or invoke a particular method.
There are '2' levels of access modifiers.
1. At Class level: public & default
2. At member level: public, private, protected and default
At Class level:
➢ If a class is declared as public then that is visible to all the
classes everywhere.
➢ If a class is declared as default (package-private)then that is
visible to only within its own package.
At Member level:
At the member level, we can also use the public or default
(package-private) just as with class level, and with the same
meaning.
PUBLIC:
If a method, variable or constructor is declared as public then
we can access them from anywhere.
When we are accessing the public member its class also should
be public otherwise will be getting compile time error.
DEFAULT:
If a method, variable or constructor is declared as default then
we can access them from current package only. So it is also
called "PACKAGE -PRIVATE“
PRIVATE:
If a method, variable or constructor is declared as private then
we can access them in the current class only.
Private is the most restricted access modifier.
If a constructor is declared as private we can’t create a object
for that class in other classes.
PROTECTED:
If a method, variable or constructor is declared as
protected then we can access them with in the current
package.
We can use PROTECTED members outside the package
only in child class, and we can access them by using child
class reference only not from parent class reference.
Understanding ‘this’ Keyword
There will be situations where a method wants to refer
to the object which invoked it.
To perform this we use ‘this’ keyword.
'this' is used to refer current class instance variable (which
resolves ambiguity problem).
'this' is used to invoke current class method.
'this' is used to invoke current class parameterized
constructor from a default constructor() and vice versa.
'this' is used to return the current class instance from the
method.
Understanding Arrays
An array is an indexed collection of fixed number of
homogeneous data elements.
An array stores multiple data items of the same data type,
in a continuous block of memory, divided into a number
of slots.
The main advantage of arrays is we can represent multiple
values with the same name so that readability of the code
will be improved.
The main disadvantage of arrays is its fixed length.
It means once we created an array there is no chance of
increasing or decreasing the size based on our requirement
that is to use arrays compulsory, we should know the size
in advance which may not possible always.
We can resolve this problem by using collections.
How to declare an Array?
To declare an array, write the data type, followed by a set
of square brackets[], followed by the identifier name.
int []rollNumber; //valid
int rollNumber[];//valid
At the time of declaration we can't specify the size of an
array.
int []rollNumber;
int [5]rollNumber; //error
How to Instantiate an array?
To instantiate (or create) an array, write the new keyword and
the datatype of the array, followed by the square brackets
containing the number of elements you want the array to have.
Every array in java is an object hence we can create by using
new keyword.
int []rollNumber;
rollNumber=new int[5]; //valid 1st way
(or)
int []rollNumber=new int[5];// valid 2nd way
(or)
int []rollNumber=new int[]{10,20,30,40,50};// valid 3rd way
(or)
int []rollNumber={10,20,30,40,50}; //valid 4th way
• The length of an array starts with ‘1’
• The index position of an array starts with ‘0’
Rules for Array Instantiation:
1. At the time of array initializing an array compulsory we
should specify the size otherwise we will get compile
time error.
2. We can give array size as zero also.
3. We can’t have negative values as array size.
4. The allowed data types to specify array size are byte,
short, char, int.
5. The maximum allowed array size in java is maximum
value of int size.
6. Whenever we are creating an array every element is
initialized with default value automatically
Note: Anonymous array is an array without reference.
Eg: new int[]{10,20,30}.length;
How to access an array element?
To access an array element, or a part of the array, you use
a number called an index or a subscript.
Difference between length Vs length():
length length()
It is the final variable applicable only for It is a final method applicable for String
arrays. objects.
It represents the size of the array It returns the number of characters
present in the String
int[] rollNumber=new int[30]; String s=“Java";
Syso(rollNumber.length());//error Syso(s.length);//error
Syso(rollNumber.length);//30 Syso(s.length());//4
Multidimensional Array
class Testarray3
{
public static void main(String args[])
{ int[][] a;
int [][]a;
int arr[][]={{1,2,3},{4,5,6},{7,8,9}};
int a[][]; All are valid.(6 ways)
for(int i=0;i<3;i++) int[] []a;
{ int[] a[];
for(int j=0;j<3;j++)
{ int []a[];
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
}
Understanding String Handling
“A String represents group of characters”. Strings are
represented as String objects in java.
After creating a String object, we can't perform any
changes to the existing object.
If we are trying to perform any changes to that string,
those changes will be appended to a new object will be
created.
This behavior is called immutability of the String object.
String objects are immutable.
Creating Strings:
We can declare a String variable and directly store a String literal
using assignment operator.
String str = "Hello";
We can create String object using new operator with some data.
String s1 = new String ("Java");
We can create a String by using character array also.
char arr[] = { 'p','r','o',’g’,’r’,’a’,’m’};
We can create a String by passing array name to it, as:
String s2 = new String (arr);
We can create a String by passing array name and specifying which
characters we need:
String s3 = new String (arr 2, 3);
Here starting from 2nd character a total of 3 characters are copied
into String s3.
Merging of two strings is known as ‘String
Concatenation’.
We can perform concatenation operation by using ’+’
operator or by using concat().
If we are creating a String in the following way
String s=new String(“Java");
then two objects will be created one is in the heap memory
the other one is String constant pool (SCP).
The identifier ‘s’ will be pointing towards the object
which is present in the heap memory.
If we are creating a String in the following way
String s=“Java";
Then only one object will be created in SCP and ‘s’ will
be always referring that object.
Object creation in SCP is always optional 1st JVM will check
is any object already created with required content or not. If it
is already available then it will reuse existing object instead of
creating new object.
If it is not already there then only a new object will be created.
Hence there is no chance of existing 2 objects with same
content on SCP that is duplicate objects are not allowed in SCP.
Garbage collector can't access SCP area hence even though
object doesn't have any reference still that object is not eligible
for GC if it is present in SCP.
All un referenced/null SCP objects will be destroyed at the time
of JVM shutdown automatically.
In SCP If an object is already available it will reuse the
existing object instead of creating new object.
In SCP there is no chance of duplicate objects.
When ever we are using new operator compulsory a new
object will be created in the Heap Memory.
There may be a chance of duplicate objects in heap
memory but there is no chance duplicate objects in SCP.
Advantage of SCP:
Instead of creating a separate object for every requirement
we can create only one object and we can reuse same object
for every requirement. This approach improves performance
and memory utilization.
Disadvantage of SCP:
As several references pointing to the same object, if we
change the value of one reference all other references
pointing to that object will be reflected with that, in order to
prevent this Strings are immutable.
String Class Methods:
Method Description
String concat (String str) Concatenates calling String with str.
Note: + also used to do the same
int length () Returns length of a String
char charAt (int index) Returns the character at specified
location ( from 0)
boolean equals (String str) Returns true if calling String equals
str.
boolean startsWith( String prefix ) Returns true if calling String starts
with prefix
String toLowerCase () converts all characters into lowercase
String toUpperCase () converts all characters into uppercase
Method Description
This method is used to get corresponding SCP
intern() object with the help of heap object reference.
This method is used for content comparison
boolean equalsIgnoreCase(String s) where case is not important.
String substring(int begin) Return the substring from begin index to end of
the string
String substring(int begin, int end) Returns the substring from begin index to end-1
index.
String replace(char old, char new) To replace every old character with a new
character.
String trim() This method is used to remove blank spaces
present at beginning and end of the string but not
blank spaces present at middle of the String.
int indexOf(char ch) returns index of 1st occurrence of the specified
character if the specified character is not available
then return -1
Method Decription
int lastIndexOf(Char ch); returns index of last occurrence of the
specified character if the specified
character is not available then return -1.
String Buffer:
• If a user wants to change the content frequently then it is
recommended to go for StringBuffer.
• StringBuffer objects are mutable, so they can be modified.
• We can create a StringBuffer object by using new operator and
pass the string to the object, as:
StringBuffer sb = new StringBuffer (“Sujatha");
• The default initial capacity of a StringBuffer is"16".
• After reaching its maximum limit it will be increased to
(currentcapacity+1)*2. ie; (16+1)*2.
StringBuffer Methods
Method Description
int length() Return the no of characters present in
the StringBuffer
int capacity() Returns how many characters a
StringBuffer can hold
char charAt(int index) Returns the character located at
specified index.
void setCharAt(int index, char ch) Replaces the character locating at
specified index with the provided
character.
delete(int begin,int end) Deletes characters from begin index to
end n-1 index.
deleteCharAt(int index) Deletes the character locating at
specified index
reverse() Reverses the given StringBuffer
Method Description
void setLength(int length) Consider only specified no of
characters and remove all the
remaining characters
void ensureCapacity(int To increase the capacity dynamically
initialcapacity); based on our requirement.
Differences b/w String, StringBuffer & String Builder
➢ String is immutable while StringBuffer and StringBuilder is mutable object.
➢ StringBuffer is synchronized while StringBuilder is not which makes
StringBuilder faster than StringBuffer.
➢ Use String if you require immutability use Stringbuffer in java if you need
mutable + thread-safety and use StringBuilder in Java if you require mutable +
without thread-safety.
How to create an immutable class?
Class must be public and final.
Properties must be private and final.
Initialization of these variables must be done using a
parameterized Constructor.
Public setter methods are allowed.
Public getters are allowed to access the information of
Immutable object.
Introduction to OOPs
Languages like Pascal, C, FORTRAN, and COBOL are called
procedure-oriented programming languages. Since in these
languages, a programmer uses procedures or functions to
perform a task. When the programmer wants to write a
program, he will first divide the task into separate sub tasks,
each of which is expressed as functions/ procedures. This
approach is called procedure-oriented approach.
The languages like C++ and Java use classes and object in their
programs and are called Object Oriented Programming
languages. The main task is divided into several modules and
these are represented as classes. Each class can perform some
tasks for which several methods are written in a class. This
approach is called “Object Oriented approach”.
OOP Vs POP
OOP POP
Definition OOP stands for Object-oriented POP stands for Procedure-oriented
programming it focuses on data programming, focuses on
rather than the algorithm. procedural abstractions.
Programs Divided into small chunks called Divided into small parts based on
objects which are instances of the functions.
classes.
Accessing Four accessing modes are used No such accessing mode is required
Mode in OOP to access attributes or
methods – ‘Private’, ‘Public’,
‘default’ , and ‘Protected’
Execution Various methods can work Follows a systematic step-by-step
simultaneously approach to execute functions.
Security It is of high secure because of it There is no such way of data hiding
data hiding feature in POP, thus making it less secure.
Features of OOP
There are mainly ‘4’ features of OOP’s are there, which
are listed below.
1. Encapsulation
2. Abstraction
3. Inheritance
4. Polymorphism
Encapsulation: Wrapping up of data (variables) and methods
into single unit is called Encapsulation. Class is an example for
encapsulation. Encapsulation can be described as a protective
barrier that prevents the code and data being randomly
accessed by other code defined outside the class. Encapsulation
is the technique of making the fields in a class private and
providing access to the fields via methods. If a field is declared
private, it cannot be accessed by anyone outside the class.
Abstraction: Providing the essential features without its inner
details is called abstraction (or) hiding internal implementation
is called Abstraction. Abstraction provides security
Encapsulation Vs Abstraction
Encapsulation Abstraction
Encapsulation is a technique which is used Abstraction shows only the necessary details
for hide the code and data. to the user.
Encapsulation = Datahiding + Abstraction
We can implement Encapsulation using We can implement abstraction using
private and protected access modifier interfaces and abstract class
For simplicity Encapsulation means hiding For simplicity Abstraction means hiding
data using getters and setters etc implementation using abstract
class/interfaces
What is a POJO class?
POJO stands for Plain Old Java Object.
It is an ordinary Java class/object, not bound by any
special restriction.
POJOs are used for increasing the readability and re-
usability of a program.
Rules:
A pojo should not
❖Implement any predefined interfaces (excluding java)
❖Extend any predefined class (excluding java)
What is a java Bean?
JavaBeans are reusable software components for Java
A JavaBean is a Java object that satisfies below rules:
➢ The JavaBean class must implement either Serializable or
Externalizable;
➢ The JavaBean class must have a public default constructor.
➢ All JavaBean properties must have public setter and getter
methods.
➢ All JavaBean instance variables should be private.
Understanding Encapsulation:
Generally there are two forms of encapsulation in OOP.
First Form:
Encapsulation is a technique that packages related data and
behaviors into a single unit.
Here, the common characteristics and behaviors of a student
are packaged into a single unit: the Studentclass.
This is the process of encapsulation.
Encapsulation hides implementation details of the Student class
from other objects.
Second Form:
Encapsulation is the technique of making the fields in a class
private and providing access to the fields via methods.
If a field is declared private, it cannot be accessed by anyone
outside the class.
Such that we provide security to the data from outside world
without misusing it, which is commonly known as
‘Information Hiding’ or ‘Data Hiding’.
In process of Information Hiding, the other objects cannot
access the data directly. Instead, they have to invoke the getters
which are designed to protect the data from misuse or
unwanted changes.
What is the need for Encapsulation?
Flexibility: It’s more flexible and easier to change the
encapsulated code with new requirements.
Reusability: Encapsulated code can be reused throughout the
application or across multiple applications.
Maintainability: If an application is encapsulated in separate
units (classes, interfaces, methods, setters, getters, etc) then it’s
easy to change or update a part of the application without
affecting other parts, which reduces the time of maintenance.
Understanding Inheritance
Inheritance is the ability of a class inheriting data and
behaviors from another class.
It is also called “Is-A” relation.
The main advantage of inheritance is code reusability.
By using "extends" keyword we can implement IS-A
relationship.
After inheriting the complete functionality of super class Sub
class can access the super class methods with its reference
object.
Common Terminology:
Parent class – Child class
Base class - Derived class
Super class - Sub class
All the data and methods which were present in parent
class is by default available to child class, but the reverse
is not applicable.
Hence by using child class reference we can call both
parent and child class methods.
But by using parent reference we can call only methods
available in the parent class and we can't call child class
specific methods.
Parent class reference can be used to hold child class
object, but Child class reference cannot be used to hold
parent class object.
For all the java classes including predefined and user
defined classes Object class acts as the super class to be
precise java.lang.Object class is superclass of all classes.
When a class extends another class, the subclass inherits
all the public and protected members of the super class.
The default members are inherited only in the same
package.
Constructors are not inherited in to the sub class during
inheritance, we can call the constructors of super class by
invoking super class object.
Types Of Inheritance:
Java supports ‘3’ types of inheritance.
1. Single Inheritance
2. Multi-Level Inheritance
3. Hierarchal Inheritance
Single Inheritance
Every java class by default inherits from “java.lang.Object” class.
By this extension only, every user object gets the behavior of real
Object.
Hence every java class exhibits by default “Single Inheritance”.
Single Inheritance enables a derived class(Sub class) to inherit
properties and behavior from a single parent class
Multi-Level Inheritance
Accessing the functionality of objects in more than one
level is called “Multi-Level Inheritance”.
Child class accessing the functionality of grand parent.
Hierarchal Inheritance
Sharing the properties of object to multiple child objects is
called “Hierarchal Inheritance”.
Understanding ‘Super’
It is a keyword which is predefined and non-static
variable.
It is used to access the complete functionality of the parent
class.
It must be used in non-static context.
this vs super
this super
It is Keyword It is a Keyword
Non-static variable Non-static variable
Used to access current class object Used to access the parent object
functionality functionality from child class
Must be used in non-static context. Must be used in non-static context.
It holds object address It doesn’t hold any object address
super() vs this()
super() this()
Used to invoke parent class constructor Used to invoke current class constructor
Must be used only inside the child class Must be used inside another constructor of
constructor. same class.
It must be first statement It must be first statement
super() , this() Vs super, this
super(),this() super, this
These are constructors calls. These are keywords
We can use these to invoke super class & We can use refers parent class and current
current constructors directly class instance members.
We should use only inside constructors as We can use anywhere (i.e., instance area)
first line, if we are using outside of except static area , other wise we will get
constructor we will get compile time error compile time error .
Understanding Method Signature
A method signature represents method name, method
return type and its parameter.
It is useful to uniquely identify different methods.
JVM identifies a method separately when the following
differences are found
➢ Different number of parameters in both methods
➢ Different data types of parameters in both methods
➢ Different in the return type in both methods
Method Overloading
“Writing two or more methods with the same name but
with different method signature is called Method
Overloading”.
It is also known as ‘early-binding’ or ‘compile-time’
polymorphism .
Method calls are resolved at compile time.
Rules for performing overloading :
✓ Must have different argument lists.
✓ May have different return types, as long as the argument lists are
also different.
✓ May have different access modifiers.
✓ May throw different exceptions.
Constructor over loading is possible.(We can’t write
constructors inside an interface).
Recursion in java is a process in which a method calls itself
continuously, when we are trying to achieve recursion by
using constructor overloading, we will be getting compile
time error as “Recursive constructor invocation”.
Can we overload main method? (Y/N)
Can we declare overloaded method as final? (Y/N)
Can we over load two methods if one method is static and
other is non-static method? (Y/N)
Can we achieve method overloading by changing the
return -type? (Y/N)
Method Overriding
“Writing two or more methods in super and sub classes with the same name
and same signature is called Method Overriding”.
It is also known as ‘late-binding’ or ‘run-time’ polymorphism.
The method present in super class is called overridden method and the
method present in the sub class is called over ridding method.
When an overridden method is called through a super class reference, Java
determines which version of that method is to be executed based upon the
type of the object being referred to at the time the call occurs. Thus, this
determination is made at run time. That is the reason it is called Run-time
polymorphism.
Overridden Rules
➢ The argument list must exactly match that of the overridden
method.
➢ The return type should exactly match that of the overridden
method (upto 1.4V).
➢ After jdk 1.5 return types may not be same in co-variant return
types. (Co-variant return type concept is applicable only for
object types but not for primitives)
➢ The access level must not be more restrictive that that of the over
ridden method. (private < default < protected < public)
➢ If a method can’t be inherited we cannot override it (Ex: private).
➢ We can't override a static method as non static methods and
vice versa.
➢ When var-arg method is overridden it should be done with
other var-arg method only.
➢ If you are over ridding two static methods then it will be
“method hiding”.
➢ The overriding method must not throw new broader checked
exceptions than those declared by the overridden method .
➢ For unchecked exceptions there are no restrictions.
Overloading Vs Overriding
Method Overloading Method Overriding
It occurs with in the same class It occurs with in the super class and sub
class
Inheritance is not involved since it deals Inheritance is involved because it occurs
with only one class between Super and Sub classes
In Overloading Return type need not be In Overriding Return type must be same
the same
Parameters must be different when we do Parameters must be same
Overloading
In Overloading one method can’t hide In Overriding sub class method hides the
another method super class methods
Understanding Java Abstraction
Abstraction:
“Abstraction is a process of hiding the
implementation details and showing only
functionality to the user”.
Another way, it shows only important things to the user
and hides the internal details for example sending a
WhatsApp message, we just type the text and send the
message. We don't know the internal processing about the
message delivery. Abstraction lets you focus on what the
object does instead of how it does it.
Ways to achieve ‘Abstraction’:
In general there are two ways to achieve Abstraction:
✓Abstract class (0 to 100%)
✓Interface (100%)
Understanding ‘Abstract Method’
An abstract method should end with semi colon(;).
It should not have any method body (or) method
implementation.
An abstract method should be over ridden to provide
implementation.
If we can’t inherit a method that method can’t be an abstract
method.
Syntax
abstract return_type <method_name>();//no braces{}
Understanding ‘Abstract Class’
A class that is declared as abstract is known as abstract
class.
abstract class <class_name>{}
It needs to be extended for its methods (abstract)
implemented.
Abstract class cannot be instantiated, i.e. we can’t create
an object for the abstract class either directly or indirectly.
An abstract class can have data member, abstract method,
method body, constructor and even main() method.
If there is any abstract method in a class, that class must be
abstract.
If you are extending any abstract class that have abstract
method, you must either provide the implementation of the
method or make this class abstract.
Abstract Class can have one or none abstract methods.
Variables, blocks & Constructors can’t be declared as
abstract.
Invalid combinations with ‘abstract’
Questions on Abstract Class
➢ Can abstract class have constructors?
➢ Can abstract class be final in Java?
➢ Can you create instance of abstract class?
➢ Abstract class must have only abstract methods.(T/F)?
➢ Can abstract class contains main method in Java?
➢ Can main method be abstract?
➢ Is it compulsory for a class which is declared as abstract to
have at least one abstract method?
➢ Can we use “abstract” keyword with constructor?
➢ Can we instantiate a class which does not have even a single
abstract methods but declared as abstract?
➢ Can we use public, protected and default modifiers with
abstract method?
➢ Can we declare abstract method In Non-abstract class?
➢ Can there be any abstract method without abstract class?
Understanding Interfaces
An interface in the Java programming language is an abstract type that is used
to specify a behavior that classes must implement.
class interface
We can instantiate a class, i.e. we can create an We can’t instantiate an interface.
object reference for a class
A class is declared using a keyword ‘class’ An interface is declared by using a keyword
class <class name> { } ‘interface’.
interface <interface name>{ }
The members of a class can have the access The members of an interface are
modifiers like public, private, protected. always public. Up to (1.7v)
Inside a class you can have method In interfaces we can’t write method body,
implementation. because all the methods are by default
public abstract methods. Up to (1.7v)
Multiple inheritance is not possible Multiple inheritance is possible
We can have constructor. We can’t have constructors
An interface is a blueprint of a class.
Interface is a mechanism to achieve fully abstraction in java.
There can be only abstract methods in the interface (up-to
1.7v).
It is used to achieve fully abstraction and multiple inheritance
in Java.
Interface fields are public, static and final by default, and
methods are public and abstract.
For variables present in the interface we should provide
initialization at the time of declaration only.
Interfaces should have only abstract methods. (we can check
the internal implementation by using javap .className).
We can declare a class inside the interface.
We can write main method in interface from jdk 1.8v
If we want to inherit an interface from a class we need to
use the keyword ‘implements’ not ‘extends’.
If we want to inherit an interface from another interface
we need to use the keyword ‘extends’ not ‘implements’.
We can achieve multiple inheritance in java by using interfaces.
We can extends multiple classes from a class at a time (T/F)
We can implement any number of interfaces from a interface at
a time (T/F)
We can implement only one interface from a class at a time
(T/F)
When implementing an interface , if a class cant provide
the implementation of all the abstracts methods present in
that interface then make that class as abstract class.
Marker Interface:
A marker interface in Java is an interface with no fields or
methods. To be precise, an empty interface in Java is called
a marker interface.
Examples of marker interfaces are Serializable, Cloneable
etc
Multi-Threading in Java
Multitasking:
Multitasking is a process of performing multiple tasks
simultaneously using single processor.
We use multitasking to optimize the utilization of CPU.
Multitasking can be achieved by two ways:
• Process-based Multitasking(Multiprocessing)
• Thread-based Multitasking(Multithreading)
Process-based Multitasking (Multiprocessing):
Each process have its very own location in memory for example
each process designates separate memory zone
Process is heavy weight.
Cost of communication between the process is high.
Switching from one process to another (Context-Switching)
consumes lot of time.
Thread-based Multitasking (Multithreading):
Threads share the same address space.
Thread is lightweight, a smallest unit of processing.
Cost of communication between the thread is low.
They don't allocate separate memory area so context-
switching between the threads takes less time than
processes.
Note:
At least one process is required for each thread.
Multithreading is mostly used in games, animation etc.
How to create thread ?
There are two ways to create a thread:
➢ By extending Thread class
➢ By implementing Runnable interface
Thread class:
Thread class is the sub class of 'Object' class and it implements Runnable interface
(by default).
Thread class will be having constructors and methods to perform operations on
thread.
When a class is extending the Thread class, it overrides the run() method from the
Thread class to define the code executed by the thread.
Runnable interface:
Runnable interface will have only one method named run().
It is mostly recommended to use when creating thread.
public void run(): is used to perform action for a thread.
Steps for creating a thread
1) Write a class that extends Thread class or implements
Runnable interface this is available in lang package.
2) Write public void run () method in that class, this is the
method by default executed by any thread.
3) Create an object to that class (Inside main()).
4) Create a thread and attach it to the object.
5) Start running the thread.
Creating Thread by implementing Runnable interface
public class ClassA implements Runnable
{
public void run() t.start();
{ t.run();
for(int i=0;i<5;i++) tt.start();
System.out.println("Run method"); tt.run();
}
public static void main(String[] args)
{
ClassA a=new ClassA();
Thread t=new Thread(a);
Thread tt=new Thread();
System.out.println("Java is awesome");
}
}
t.start()
New Thread will be generated which is responsible for the
execution of ClassA run() method.
t.run()
No new Thread will be generated but ClassA run() method will
be called just like a normal method call.
tt.start()
A new Thread will be generated which is responsible for the
implementation of Thread class run()method
tt.run()
No new Thread will be generated but Thread class run()
method will be called just like a normal method call.
Creating Thread by extending Thread class
public class ClassA extends Thread
{
public void run()
{
for(int i=0;i<5;i++)
System.out.println("Run method");
}
public static void main(String[] args)
{
ClassA a=new ClassA();
a.start();
System.out.println("Java is awesome");
}
}
Life Cycle of a Thread
New Thread is created but not yet started.
Runnable A thread in the Runnable state is executing in the Java virtual
machine but it may be waiting for other resources from the
operating system such as processor
Blocked A thread in the blocked state is waiting to enter a synchronized
block/method or reenter a synchronized block/method.
Waiting A thread will be in waiting state for a unspecified period of
time, due to calling one of the methods like wait(),join() etc
Timed_waiting A thread will be in waiting state for another thread for a
specified waiting time is in this state
Terminated The thread has completed execution
A thread can be in only one state at a given point in time. Thread.getState()
Types of Thread Application
In general there are two type of thread applications
1. Single Threaded Application
2. Multi Threaded Application
Single Threaded Application:
When we invoke java application, JVM by default creates a
thread is called “main thread”.
In single threaded application, execution starts at main thread
and end at the same thread.
All the methods of single thread executes sequentially.
Multi threaded Application:
Creating a user thread from main thread referred as multi
threaded application.
Multi threaded application execution starts at main thread
only.
Program execution completes, when all the running
threads moved to dead state.
Understanding join() method
The join method allows the thread to wait for the
completion of another thread.
Every join() method throws InterruptedException, hence
compulsory we should handle either by try catch or by
throws keyword. Otherwise we will get compile time
error.
Understanding sleep() method:
If we want a thread to pause performing any actions for a given amount of
time then we should use sleep() method.
This is an efficient means of making processor time available to the other
threads of an application.
we can pause the execution of a thread by using '2'predefined methods.
1)Thread.sleep() //specified time in milliseconds.
2)Thread.sleep(long millisecs, int nanosec) //specified milliseconds and
nanoseconds. The allowed nano second value is between 0 and 999999
However, these sleep times are not guaranteed to be precise, because they are
limited by the facilities provided by the underlying OS.
Understanding interrupt() method
An interrupt is an indication to a thread that it should stop what
it is doing and do something else.
For the interrupt mechanism to work correctly, the interrupted
thread must be in either sleep state or wait state.
If the selected Thread is not in sleep mode then interrupt() will
wait until it went in to sleep mode, and then it will cause
interruption for that thread.
Example:
ClassA a=new ClassA();
Thread t=new Thread(a);
t.start();
t. interrupt();
Understanding yield() method
yield() provides a mechanism to inform the “thread
scheduler” that the current thread is willing to hand over
its current use of processor, but it'd like to be scheduled
back soon as possible.
If we are using the yield method then the selected thread
will give a chance for other threads with same priority to
execute.
If there are several waiting Threads with same priority,
then we can't expect exactly which Thread will get chance
for its execution.
We can’t guess again when the yielded thread will resume
its execution.
Getting and setting name of a Thread:
Every Thread in java has some name it may be provided
explicitly by the programmer or automatically generated
by JVM.
Thread class defines the following methods to get and set
name of a Thread.
✓ public final String getName()
✓ public final void setName(String name)
Understanding Thread Priorities
In the Java programming language, every thread has a
priority.
We can increase or decrease the priority of any thread by
using setPriority(int newPriority) method.
We can get the priority of the thread by using getPriority()
method
Priority can either be given by JVM (5) while creating the
thread or it can be given by programmer explicitly.
Accepted value of priority for a thread is in range of 1 to
10.
Thread priorities are highly system-dependent we should
always keep in mind that underlying platform should
provide support for scheduling based on thread priority.
There are 3 static variables defined in Thread class for
priority.
public static int MIN_PRIORITY --->1
public static int NORM_PRIORITY --->5
public static int MAX_PRIORITY --->10
Understanding Synchronization
Synchronization in java controls multiple threads from
accessing the same shared resource in order to prevent an
inconsistent state.
Java Synchronization is done when we want to allow only one
thread to access the shared resource.
In other words Synchronization is a process of making only
one thread access a resource, where multiple threads are trying
to access the same resource, and moving all the remaining
threads in to waiting state.
Advantage:- Resolves Thread Interference & Memory
Consistency problems
Disadvantage:- Increases Thread waiting time.
We can use Synchronization in two ways, a method can be
synchronized and a block can be synchronized.
We can't synchronize a complete class.
Understanding Deadlocks
Deadlock describes a situation where two or more threads
are blocked forever, & waiting for each other.
In other words it is a condition which occurs when two or
more threads get blocked, waiting for each other for an
infinite period of time to release the resources they hold.
Interthread Communication:
Two Threads can communicate with each other by using
wait(), notify() and notifyAll() methods.
Method Name Description
Causes the current thread to wait until
public final void wait() either another thread invokes the notify()
method or the notifyAll() , or a specified
amount of time has elapsed.
Wakes up a single thread that is waiting
public final native void notify()
Wakes up all threads that are waiting
public final void notifyAll()
Understanding Exception Handling
An error in a program is called bug. Removing errors from
program is called debugging. There are basically three types of
errors in the Java program:
Compile time errors: Errors which occur due to syntax or
format is called compile time errors. These errors are detected
by java compiler at compilation time. Desk checking is solution
for compile-time errors.
Runtime errors: These are the errors that represent computer
inefficiency. Insufficient memory to store data or inability of
the microprocessor to execute some statement is examples to
runtime errors. Runtime errors are detected by JVM at runtime.
Logical errors: These are the errors that occur due to bad logic
in the program. These errors are rectified by comparing the
outputs of the program manually.
Exception:
An abnormal event in a program is called Exception.
All Exceptions occur at runtime only but some are detected at
compile time and some are detected at runtime.
Exceptions that are checked at compile time by the java
compiler are called “Checked exceptions”.
eg: ClassNotFoundException, NoSuchMethodException, NoSuchFieldException etc.
Exceptions that are checked at run time by the JVM are called
“Unchecked exceptions”.
eg: ArrayIndexOutOfBoundsException, ArithmeticException, NumberFormatException etc.
object
Some common exceptions scenarios
Scenario where ArithmeticException occurs :
If we divide any number by zero, there occurs an ArithmeticException.
int a=50/0;//ArithmeticException
Scenario where NullPointerException occurs :
If we have null value in any variable, obtaining the length of that variable
occurs an NullPointerException.
String s=null;
System.out.println(s.length());//NullPointerException
Scenario where ArrayIndexOutOfBoundsException occurs
If you are inserting any value in the wrong index, it would result
ArrayIndexOutOfBoundsException as shown below:
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
List of important built-in exceptions
Exception Class Meaning
ArithmeticException Thrown when an exceptional condition
has occurred in an arithmetic operation
ArrayIndexOutOfBoundsException Thrown to indicate that an array has
been accessed with an illegal index
ClassNotFoundException Thrown when we try to access a class
whose definition is not found
FileNotFoundException Raised when a file is not accessible or
does not open
IOException Thrown when an input-output operation
failed or interrupted
NoSuchFieldException Thrown when a class does not contain the
field(or variable) specified
NullpointerException Raised when referring to the members of a
null object
List of important built-in exceptions
Exception Class Meaning
NumberFormatException Raised when a method could not convert a
string in to a numeric format
RuntimeException This represents any exceptions which
occurs during runtime
StringIndexOutOfBoundsException Thrown by String class methods to
indicate that an index is either negative
or greater than the size of the string
Exception Handling
An exception can be handled by the programmer where as
an error cannot be handled by the programmer.
Exception handling doesn't mean fixing an exception, We
need to provide an alternative solution for the free flow of
program.
What happens when Exception has occurred?
➢ Exception occurs only either inside the block or a method.
➢ When exception has raised, that block or method creates
an exception object which contains the complete
information of that exception including.
o Name of the Exception
o Explanation of the Exception
o State of the Exception (Stack Trace)
➢ Once object has been created, it passes to JVM, then JVM handles
that exception with the help of Default Exception Handler.
➢ Default Exception Handler checks whether the method contains
any exception handling code or not. If method won't contain
any handling code then JVM terminates that method
abnormally and removes corresponding entry form the stack.
➢ Default Exception Handler just prints the basic information about the
exception which has occurred and terminates the method abruptly.
When there is an exception the programmer should do the
following tasks:
If the programmer suspects any exception in program
statements, he should write them inside try block.
try
{
statements;
}
Within the try block if anywhere an exception raised then rest
of the try block won't be executed even though we handled that
exception.
When there is an exception in try block JVM will not terminate
the program abnormally.
JVM stores exception details in an exception stack and then
JVM jumps into catch block.
The programmer should display exception details and any
message to the user in catch block.
catch ( ExceptionClass obj)
{
statements;
}
Programmer should close all the files and databases by
writing them inside finally block.
Finally block is executed whether there is an exception
or not.
finally
{
statements;
}
Performing above tasks is called Exception Handling.
Methods To Display Exception
Information
Throwable class defines the following methods to print
exception information to the console.
Method Name Description
printStackTrace() Name of the exception: description of exception
Stack trace
toString() Name of the exception: description of exception
getMessage() Only Description
Important points to remember
Default exception handler can handle only one exception at a time
and that is the most recently raised exception
There should not be any statements b/w try, catch and finally.
We can handle multiple exceptions by writing multiple catch
blocks.
A single try block can be followed by several catch blocks.
Catch block does not always exit without a try, but a try block exit
without a catch block.
Finally block is always executed whether there is an exception or
not.
There should be only one finally block for a try block.
We should follow try-catch-finally order.
Until 1.6 version try should be followed by either catch or finally
but 1.7 version we can take only try with resource without catch or
finally
try(FileInputStream input = new FileInputStream("file.txt"))
From 1.7 we can use multiple catch blocks in one statement only
Which one is valid?
try try
{ {
…….; ……..;
…….; ……..;
…….; ……..;
} }
catch(Exception e) catch(ArithematicException ae)
{ {
………; ………;
} }
catch(Throwable t) catch(RuntimeException re)
{ {
………; ………;
} }
catch(NullpointerException ne) catch(Exception e)
{ {
………; ………;
} }
Understanding ‘throw’ keyword
The throw keyword is mainly used to throw custom exceptions
(User defined exceptions).
We can throw either checked or unchecked exception.
All methods use the throw statement to throw an exception.
The throw statement requires a single argument: a throwable
object.
Throwable objects are instances of any subclass of the
Throwable class.
Syntax:
throw is followed by an object (new type)
used inside the method
By using throw keyword we can't throw multiple exceptions
Understanding ‘throws’ clause
The "throws" keyword is used to declare an exception, It is
used to indicates what exception type may be thrown by a
method.
Except for methods & constructors we can’t use "throws" else
where.
"throws" keyword can be used only for Throwable types.
"throws" keyword is required only for checked exceptions.
How to create Own Exception Class?
Create a new class and extends one of the exceptions which are
subtypes of the java.lang.Exception class
Generally, a user defined exception class always extends directly
from the Exception class.
Create a constructor with a String parameter which is the detail
message of the exception.
In this constructor, simply call the super constructor and pass the
String parameter.
Understanding ‘Final’ keyword
The final keyword in java is used to restrict the user.
‘final’ keyword is used in three ways:
It is used to declare constants as:
✓ Final double Pi=3.14159; //PI is constant
It is used to prevent inheritance as:
✓ Final class A // sub class to A cant be created
It is used to stop method Overriding as:
✓ Final sum() // sum() method can’t be overridden
The final can be:
➢Variable
➢Method
➢Class
‘final’ Variable:
If you make any variable as final, you cannot change the
value of final variable(It will be constant).
‘final’ Method:
If you make any method as final, you cannot override it.
Because they are not available to sub classes. So only
overloading is possible.
‘final’ Class:
If you make any class as final, you cannot extend it. It
means sub classes can’t be created to final class
Understanding Singleton class
A singleton class is a class that can have only one object (an instance of
the class) at a time.
We can create a singleton class by following steps:
1)Write a class & then Create a static object for the class.
2)Write a private constructor in the class
3)Create a static method which returns the static instance which you have
created in the 1st step.
Garbage Collection
Understanding Java Garbage Collection
Garbage collection is a mechanism of re-Acquiring the heap space
by destroying the objects which are eligible for "Garbage
Collection".
Garbage collector always running in the background of a java
application for removing useless objects, So that the chance of
failing java program is very rare because of memory problems.
All Java objects reside in an area called the heap.
The heap is created when the JVM starts up and may increase or
decrease in size while the application runs.
When the heap becomes full, garbage (Unused Objects) is collected
by Garbage Collector.
During the garbage collection objects that are no longer used
are cleared, thus making space for new objects.
The algorithm used by Garbage collector is "Mark & Sweep".
Garbage Collection is not a process of collecting and discards
dead objects, It is more like marking the "live" objects (all
objects that are reachable from Java threads, native methods
and other root sources) and everything else designated as
garbage.
In java objects are deleted by Garbage Collector implicitly.
When an Object is available for Garbage Collection ?
Below mentioned are the four possible ways where a java
object eligible for garbage collection
By Re-assigning the reference variable
By Nullifying the reference variable
All Objects created inside method
Island of Isolation in Java
By Re-assigning the reference variable:-
If we are reassigning an object reference to another object then automatically the first
object is available for Garbage collection.
By Nullifying the reference variable:-
If we assign null value to the object reference, then that particular object is eligible for
Garbage collection.
All Objects created inside method:
All objects created inside any method are by default eligible for Garbage Collection,
provided after completion of the method implementation.
Island of Isolation in Java:
In java, if Object 1 references Object 2 and Object 2 references Object 1. Neither Object
1 nor Object 2 is referenced by any other object then that scenerio is called "Island of
Isolation". If an object doesn't have any reference then it always eligible for GC.
How to call Garbage Collector
manually?
We can call the Garbage collector manually in '2' ways
1. By using System Class (System.gc()---> Its a static method)
2. By Using Runtime Class
Runtime r=Runtime.getRuntime();
r.gc();
IO Streams
In java a stream represents a sequence of objects (byte,
characters, etc.) which we can access them in a sequential
order.
In java, I/O streams represents either an Input source or an
output destination.
There are mainly '4' types of streams
Name Description
Byte Streams Read and write stream of data in byte format
Character Read and write stream of data in Character format
Streams
Data Streams Handles I/O streams of primitive data types
Object Streams Handles object streams (Serialization)
Understanding Byte Streams
In byte streams data will be transferred in the form of bytes.
In byte streams the length of each data packet is 1 byte.
All byte stream classes are sub classes for InputStream &
OutputStream classes which are abstract classes. (present in
'java.io.InputStream' & 'java.io.OutputStream’ )
We use extensions like "FileInputStream" and
"FileOutputStream" classes in the coding.
java.io.InputStream java.io.OutputStream
FileInputStream Class:
FileInputStream Class is a normal class which extends
InputStream class which is a abstract class.
This class is always used to open the file in read mode.
(int read() is an abstract method in InputStream class, in
FileInputStreamClass it has been overridden).
Syntax:
FileInputStream fis=new FileInputStream("abc.txt");
In the above syntax if the file is not available at the given
URL the FileInputStream object will throw a
FileNotFoundException
The read() method on success will returns the ASCII value
of the character(ie., int datatype), If failed returns '-1'
FileOutputStream Class
FileOutputStream class is a normal class which extends
OutputStream class which is a abstract class.
This class is always used to open the file in write mode.
Syntax:
FileOutputStream(String filePath)
FileOutputStream(File fileObject)
FileOutputStream(String filePath,boolean append)
If we are trying to write some data in to the file by using write()
method, then compiler will check if there is any file present in that
given URL.
If the file is present then the file will be opened and the existing
content will be deleted in the file.
If the file is not present then a new file will be created with the name
given in the path.
While using FileOutputStream if we don’t want to override the
existing data in the file the we should use append mode.(set it as
true).
1) WAP to copy the contents of source file in to the destination file.
2) WAP to write the file using FileOutputStream and use append
mode.
3) WAP to copy source Image in to destination Image.
Understanding Character Streams:
In character Streams data is transferred in the form of
characters.
In character Streams the length of each data packet is 2
bytes.
All character stream classes are sub classes for Reader &
Writer classes which are abstract classes. (present in
'java.io.Reader' & 'java.io.Writer' )
FileReader Class:
It is the child class for InputStreamReader.
We can use this class to read the data character by character from the stream.
Data like images, audio, video etc we can't read by using FileReader class.
(We are supossed to use Byte Streams)
FileReader fr=new FileReader ("abc.txt");
FileWriter Class:
It is the child class for OutputStreamWriter.
We can use this class to write the data character by character in the from of
stream in to destination file.
Same as FileOutput Stream class in FileWriter Class also We can use append
mode.(By setting the second parameter as ‘true’).
FileWriter fw=new FileWriter ("abc.txt");
Byte Streams Vs Character Streams
Understanding Data Streams:
These Streams handle binary I/O operations on primitive data types.
DataInputStream and DataOutputStream are filter streams (A filter stream
filters data as it's being read or written to the stream)that let you read or write
primitive data types
DataInputStream and DataOutputStream implement the DataInput and
DataOutput interfaces, respectively.
These interfaces define methods for reading or writing the Java primitive
types, including numbers and Boolean values.
DataOutputStream encodes these values in a machine-independent manner
and then writes them to its underlying byte stream.
DataInputStream is created with a FileInputStream as source for its data.
DataOutputStream is created with a FileOutputStream as source for its data.
Understanding Buffered Streams:
A Buffer is a portion in the memory that is used to store a
stream of data.
In I/O operations each read or write request is handled directly
by the underlying OS.
This can make a program much less efficient, since each such
request often triggers disk access, network activity, or some
other operation that is relatively expensive.
To reduce this kind of overhead, the Java platform
implemented buffered I/O streams.
Buffered input streams read data from a memory area known as
a buffer.
Buffered output streams write data to a buffer.
Buffered streams are same like Byte & Character Streams but
with more efficiency.
There are four buffered stream classes used to wrap unbuffered
streams
BufferedInputStream and BufferedOutputStream create buffered byte
streams
BufferedReader and BufferedWriter create buffered character
streams.
Syntax:
BufferedInputStream:
BufferedInputStream br=new BufferedInputStream(new FileInputStream(“FilePath"));
BufferedOutputStream:
BufferedOutputStream br=new BufferedOutputStream(new FileOutputStream(“FilePath"));
flush() : When you write data to a stream, it is not
written immediately, and it is buffered. So use flush()
when you need to be sure that all your data from buffer is
written.
BufferedReader:
BufferedReader br=new BufferedReader(new FileReader(" FilePath "));
BufferedWriter :
BufferedWriter bw= new BufferedWriter(new FileWriter(" FilePath "));
Understanding Serialization
The process of saving (or) writing state of an object to a file is called
serialization.
In other words it is a process of converting an object from java
supported version to network supported version (or) file supported
version.
ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream(“File Path"));
By using FileOutputStream and ObjectOutputStream classes we can
achieve serialization.
The process of reading state of an object from a file is called
DeSerialization.
By using FileInputStream and ObjectInputStream classes we can
achieve DeSerialization.
ObjectInputStream ois=new ObjectInputStream(new FileInputStream(“File Path"));
Important Points to remember
We can perform Serialization only for Serializable objects.
An object is said to be Serializable if and only if the
corresponding class implements Serializable interface.
Serializable interface present in java.io package and does not
contain any methods. It is marker interface. The required
ability will be provided automatically by JVM.
We can add any no. Of objects to the file and we can read all
those objects from the file, but in which order we wrote objects
in the same order only the objects will come back ie, reterving
order is important.
If we are trying to serialize a non-serializable object then we
will get RuntimeException saying "NotSerializableException".
Transient keyword
‘transient’ is the modifier applicable only for variables.
While performing serialization if we don't want to save the
value of a particular variable to meet security constraints
such type of variable , then we should declare that variable
with "transient" keyword.
At the time of serialization JVM ignores the original value
of transient variable and save default value to the file.
Working With Files
File is a java class available in java.io.package used to work
with files and directories.
The instances of File class represents a File or Directory.
To work with files or directories we must create object of File
class.
With the help predefined methods we can perform operations
on the files
Syntax
File f=new File(“FileName”);
File Class Methods
Method Description
f.exists() Returns true if file exists.
f.isFile() Returns true if this is a normal file.
f.isDirectory() true if “f ” is a directory.
f.getName() Returns name of the file or directory.
f.isHidden() Returns true of file is hidden.
f.lastModified() Returns time of last modification.
f.length() Returns number of bytes in file.
f.getPath() Path name.
f.delete() Deletes the file.
f.renameTo(F2) Renames f to File f2. Returns true if successful.
f.createNewFile() Creates a file and may throw IOException.
COLLECTION FRAMEWORK
Introduction
In java if we want to store multiple items of homogenous data
types we can use “Arrays”.
Arrays can hold both primitive data types and objects.
Example:
int i[]=new int[100];
Object o[]=new Object[10];
Arrays don’t have underlying data structures and algorithms.
The Length of the arrays is fixed.
Arrays can hold duplicate elements also.
We can’t store heterogeneous elements in an array.
Inserting element at the end of array is easy but at the middle is
difficult.
After retrieving the elements from the array, in order to process
the elements we don't have any methods.
To overcome the above mentioned limitations we prefer
Collections Framework.
Collections size is not fixed based on our requirement, We
can increase or decrease the size of a collection.
Collections can hold both homogeneous and
heterogeneous objects
Every collection class is implemented based on some
standard data structure & algorithms so predefined method
support is available.
Arrays Vs Collections
Arrays Collections
Arrays are fixed in size Collections are growable in nature
Arrays can hold only homogeneous data Collections can hold both homogeneous
types elements. and heterogeneous elements.
There is no underlying data structure. Every collection class is implemented
based on some standard data structure.
Arrays can hold both object and primitive Collection can hold only object types
Memory wise-> Recommended Memory wise->Not Recommended
Performance Wise---> Not Performance Wise---> Recommended
Recommended
COLLECTION HIERARCHY
Map Hierarchy
Collection Object
A collection object is an object which can store group of other
objects.
A collection object has a class called Collection class or
Container class.
All the collection classes are available in the package called
'java.util’ (util stands for utility).
Group of collection classes is called a Collection Framework.
All the collection classes in java.util package are the
implementation classes of different interfaces.
In General Collection Framework consists of ‘3’ parts
1. Algorithms (Rules)
2. Interfaces (abstract datatypes)
3. Implementations (Concrete versions of these Interfaces)
Overview of Set, List, Queue, Map
Set: A Set represents a group of elements (objects) arranged
just like an array. The set will grow dynamically when the
elements are stored into it. A set will not allow duplicate
elements.
List: Lists are like sets but allow duplicate values to be stored.
Queue: A Queue represents arrangement of elements in FIFO
(First In First Out) order. This means that an element that is
stored as a first element into the queue will be removed first
from the queue.
Map: Maps store elements in the form of key value pairs. If
the key is provided its corresponding value can be obtained.
Retrieving Elements from Collections:
Following are the ways to retrieve any element from a
collection object:
✓Using Iterator interface.
✓Using ListIterator interface.
✓Using Enumeration interface.
Iterator Interface: Iterator is an interface that contains
methods to retrieve the elements one by one from a collection
object. It retrieves elements only in forward direction. It has 3
methods:
Method Description
boolean hasNext() returns true if the iterator has more elements.
element next() returns the next element in the iterator.
void remove() removes the last element from the collection
returned by the iterator.
ListIterator Interface:
ListIterator is an interface that contains methods to
retrieve the elements from a collection object, both in
forward and reverse directions. It can retrieve the elements
in forward and backward direction.
It has the following important methods:
Method Description
boolean hasNext() returns true if the ListIterator has more elements
when traversing the list in forward direction.
element next() returns the next element.
void remove() removes the list last element that was returned by the
next () or previous () methods.
boolean hasPrevious() returns true if the ListIterator has more elements
when traversing the list in reverse direction
element previous() returns the previous element in the list.
Enumeration Interface:
This interface is useful to retrieve elements one by one
like Iterator.
It has 2 methods.
Method Description
boolean hasMoreElements() This method tests Enumeration has any
more elements.
element nextElement() This returns the next element that is
available in Enumeration.
Understanding Collection Interface
The root interface in the collection hierarchy.
A collection represents a group of objects, known as
its elements.
Some collections allow duplicate elements and others do
not.
Some are ordered and others unordered.
The JDK does not provide any direct implementations of
this interface.
Important Collection Interface methods
Method Name Description
int size() Returns the number of elements in this collection
boolean isEmpty() Returns true if this collection contains no
elements
int hashCode() Returns the hash code value for this collection.
void clear() Removes all of the elements from this collection.
(Collection will be empty)
boolean contains(Object o) Returns true if this collection contains the
specified element
boolean containsAll(Collection c) Returns true if this collection contains all of the
elements in the specified collection.
boolean add(Object o) Returns true if this collection changed as a result
of the call. Returns false if this collection does not
permit duplicates and already contains the
specified element.
Method Name Description
boolean addAll(Collection c) Adds all of the elements in the specified
collection to this collection
boolean remove(Object o) true if an element was removed as a result of
this call.
boolean removeAll(Object c) Removes all of this collection's elements that
are also contained in the specified collection
boolean retainAll(Collection c) Retains only the elements in this collection
that are contained in the specified collection
All the above mentioned methods are the most common general methods
which can be applicable for any Collection object
Understanding List Interface
The Java.util.List is a child interface of Collection.
A List is an ordered Collection of elements in which insertion ordered
is preserved.
Lists allows duplicate elements.
ArrayList :
ArrayList is available since jdk1.2V
It allows duplicates & insertion order is maintained.
Default capacity when creating an ArrayList is 10.
If the ArrayList is full then its capacity will be increased automatically.
New capacity=(current capacity*3/2)+1
It is not synchronized by default.
ArrayList al=new ArrayList();
List al=collections.synchronizedList(al);
To overcome the problems of "TypeCasting" & "Type-Safety" in
collections, “GENERICS” have been introduced from jdk1.5v.
ArrayList Class Methods:
Method Description
This method appends the specified
boolean add (element obj) element to the end of the ArrayList.
Returns true if succeeded
inserts the specified element at the
void add(int position,element obj) specified position in the ArrayList
removes the element at the specified
element remove(int position) position in the ArrayList and returns it
This method removes the first occurrence
boolean remove (Object obj) of the specified element obj from the
ArrayList, if it is present.
Returns number of elements in the
int size () ArrayList.
returns the element available at the
element get (int position) specified position in the ArrayList.
Vector Class:
Vector is available since jdk1.0V
It allows duplicates & insertion order is maintained.
Default capacity when creating an Vector is 10.
Its capacity increases by (CurrentCapacity*2).
It is synchronized by default.
Vector v=new Vector();
Vector v=new Vector(int capacity);
Vector v=new Vector(int capacity, int incrementalcapacity);
Vector Methods
Method Description
addElement(Object o); Adds the specified component to the end of
this vector, increasing its size by one.
removeElement(Object o); Removes the first (lowest-indexed) occurrence
of the argument from this vector.
removeElementAt(int index); Deletes the component at the specified index.
removeAllElements(); Removes all components from this vector and
sets its size to zero.
Object elementAt(int index); Returns the component at the specified index.
Object lastElement(); Returns the last component of the vector.
Object firstElement(); Returns the first component (the item at
index 0) of this vector.
LinkedList Class:
LinkedList is available since jdk1.2V.
It allows duplicates, null & insertion order is maintained.
Default capacity when creating an LinkedList is 0.
In linked list elements are stored in the form of nodes.
Each node will have three fields, the data field contains data
and the link fields contain references to previous and next
nodes.
It occupies more memory than ArrayList and Construction time
is also high. Syntax: LinkedList ll=new LinkedList();
node node node
Linked List
Node Structure
LinkedList Methods
Description
Methods
Object getFirst(); Returns the first element in this list
Object getLast(); Returns the last element in this list
Object removeFirst(); Removes and returns the first element from this list
Object removeLast(); Removes and returns the last element from this list.
void addFirst(Element e); Inserts the specified element at the beginning of this
list.
addLast(Element e); Appends the specified element to the end of this list.
Understanding Set Interface
It is the child interface of Collection.
A Set is a Collection that cannot contain duplicate elements
The Set interface contains only methods inherited
from Collection and adds the restriction that duplicate elements are
prohibited.
HashSet:
HashSet is available since jdk1.2V
Underlying data structure for HashSet is HashTable.
It doesn’t allows duplicates & insertion order is not maintained.
Default capacity when creating an HashSet is 16.
Load Factor for HashSet is 0.75 (No of elements/ Size of the hashTable)
HashSet is not synchronized by default.
Accepts ‘null’ value for only once.
HashSet hs=new HashSet();
HashSet hs=new HashSet(int initialcapacity);
LinkedHashSet:
The only difference between HashSet & LinkedHashSet is
Hash set doesn't maintain the insertion order where as
LinkedHashSet maintains it.
LinkedHashSet is available since jdk1.4V.
It inherits HashSet class and implements Set interface.
LinkedHashSet lhs=new LinkedHashSet();
TreeSet:
TreeSet maintains sorting order of inserted elements.
TreeSet is available since jdk1.2V.
It will arrange the elements in ascending order using balanced
binary search tree algorithm.
TreeSet will not allow to insert Heterogeneous objects
It doesn’t allows duplicates & insertion order is not maintained.
TreeSet t=new TreeSet();
All the three class doesn’t accept duplicates elements.
TreeSet methods
descendingSet(); Returns a reverse order view of the elements
contained in this set
descendingIterator(); Returns an iterator over the elements in this set in
descending order.
headSet(E toElement); Returns the elements less than to the specified
element
tailSet(E toElement); Returns the elements greater than or equal to the
specified element
Queue Interface
The implementation classes for Queue Interface are
LinkedList & PriorityQueue.
In Queue elements are stored in FIFO order.
If we are creating an object for LinkedList with
LinkedList reference variable, then we can access
complete functionality of Queue & List.
From 1.5v onwards LinkedList also implements Queue
interface.
Queue Interface Methods
Method Description
Offer(Object o); Add an element in to Queue
To remove and return first element of the Queue (returns
Object poll() ; null if the queue is empty)
To remove and return first element of the Queue
Object remove(); (NoSuchElementException when the queue is empty)
Object peek(); To return first element of the Queue without removing it
PriorityQueue
It doesn’t maintains insertion order and returns the elements in
ascending order (Smallest Number first).
In PriorityQueue the top element is always the smallest
element.
It doesn’t accept null.
PriorityQueue is available since jdk1.5V.
It allows duplicate values, default capacity is 11.
PriorityQueue q=new PriorityQueue();
PriorityQueue q=new PriorityQueue(int initialcapacity);
Understanding Map Interface
In Map elements are stored in the form of Key-Value pairs.
Keys are unique in Map interface, duplicate keys are not allowed but
duplicate values are allowed.
Each key can map to at most one value.
Each key-value pair is called "one entry“.
Duplicates will be replaced but they are not rejected.
Map interface is not child interface of Collection interface.
Some map implementations have restrictions on the keys and values
they may contain.
Map Interface Methods
Method Description
int size(); Returns the number of key-value mappings in this map
boolean isEmpty(); Returns true if this map contains no key-value mappings
boolean containsKey Returns true if this map contains a mapping for the
(Object key); specified key.
boolean containsValue Returns true if this map maps one or more keys to the
(Object value); specified value
V get(Object key) Returns the value to which the specified key is mapped
V put(K key, V value) Associates the specified value with the specified key in
this map
V remove(Object key) Removes the mapping for a key from this map if it is
present
Set<K> keySet() Returns a Set view of the keys contained in this map
HashMap:
HashMap is available since jdk1.2V.
It is available in java.util package.
It allows duplicate values with unique keys & insertion order is not
maintained. (Duplicate keys are replaced)
Default capacity is 16 & load factor is 0.75.
HashMap is not synchronized by default.
HashMap m=new HashMap();
HashMap m=new HashMap(int initialcapacity);
LinkedHashMap:
The only difference between HashMap & LinkedHashMap is HashMap
doesn't maintain the insertion order where as LinkedHashMap maintains it.
LinkedHashMap is available since jdk 1.4
TreeMap:
In TreeMap keys are maintained in ascending order.
TreeMap uses balanced binary trees algorithm internally.
Insertion order is not maintained.
TreeMap is available since jdk1.2V.
Null keys are not allowed where as null values are accepted.
Duplicates values are accepted, If duplicate key is there the previous key-
value will be replaced.
♪ HashMap doesn’t maintain insertion order
♪ Linked HashMap maintains Insertion Order
♪ TreeMap Maintains Ascending order of keys
Hashtable
Hashtable is available since jdk1.2V.
Insertion order is not preserved.
Heterogeneous objects are allowed for both keys and values.
Null key (or) null value is not allowed.
It allows duplicate values with unique keys.
Every method present inside Hashtable is synchronized
Default capacity is 16 & load factor is 0.75.
Hashtable h=new Hashtable();
Hashtable h=new Hashtable(int initialcapacity);
HashMap Vs LinkedHashMap Vs TreeMap Vs Hashtable
Property HashMap LinkedHashMap TreeMap Hashtable
Not Maintained
Insertion order Not Maintained (But keys are Not
Maintained sorted in Maintained
ascending order)
Null
Keys/Values Allowed Allowed Not Allowed Not Allowed
(Null Values are
allowed)
Synchronization Not Not Not Synchronized
Synchronized Synchronized Synchronized
Important Differences in
‘Collections’
Set (Vs) List
Set List
A set represents a collection of elements A List represents ordered collection of
Order of the elements may change in the elements. List preserves the order of
set. elements in which they are entered.
Set will not allow duplicate values to be List will allow duplicate values.
stored.
Accessing elements by their index Accessing elements by index is possible
(position number) is not possible in case in lists.
of sets.
ArrayList (Vs) Vector
ArrayList Vector
ArrayList object is not synchronized Vector object is synchronized by
by default. default.
Incase of a single thread, using In case of multiple threads, using
ArrayList is faster than the Vector. Vector is advisable. With a single
thread, Vector becomes slow.
ArrayList increases its size every time Vector increases its size every time by
by 50 percent (half). doubling it.
HashMap (Vs) HashTable
HashMap HashTable
HashMap object is not synchronized by Hashtable object is synchronized by
default. default.
In case of a single thread, using HashMap In case of multiple threads, using
is faster than the Hashtable. Hashtable is advisable, with a single
thread, Hashtable becomes slow.
HashMap allows null keys and null values Hashtable does not allow null keys or
to be stored. values.
Understanding Applets & AWT
Applets allows java programmer to implement GUI in the
programming.
An applet is a Java program that runs in the context of a web page.
Like an image or hyperlink it "owns" some rectangular area of the
user's screen.
The java.applet.Applet class defines the core functionality of an
applet.
Every user defined applet class must extends pre-defined Applet
class.
Syntax:-
public class FirstApplet extends Applet
{
//statements
}
Abstract Window Tool Kit (AWT):
AWT contains large number of pre defined (abstract)classes,
methods & Interfaces that allows you to create and manage
graphical user interface ( GUI ) applications.
The java.awt package provides classes for AWT api such as
TextField, Label, TextArea, RadioButton, CheckBox, Choice,
List etc.
First Applet Program:
Applets are defined to be embedded in to HTML
pages.(Most of the browsers now stopped support for
applets).
Applet do not use main() because when applet is loaded it
automatically calls certain methods of applet class to start
and executes the applet code.
Applets and Servlets do not start their own process.
Instead they run inside a container.
Therefore, they do not need a static main method (which
starts the process).
public void paint() method is the pre-defined method in
Applet class.
Graphics class is the predefined class in java.awt
Applet Life Cycle:
GUI based java application can be invoked either by
"appletviewer" or "browser interpreter".
When an applet execution starts, it will be instantiated
implicitly.
We can check the instantiation by using a default constructor in
the Applet class.
Methods participate in Applet Life Cycle:
❖ Constructor()
❖ init()
❖ start()
❖ paint()
❖ stop()
❖ destroy()
Diagrammatic Representation
Components:
The objects or elements which are displayed on the applet
window are called "Components" (Ex: Button, Checkbox,
Radio button etc).
All the Component classes are available in java.awt
package only.
Event Listeners:
An Event is a action which is performed by a component.
When an action is performed Component fires an event.
Listener can collect event information and react according to
the defined logic.
Listener is a predefined interface having different sub
interfaces like, ActionListener, TextListener, MouseListener
etc.
Swings API
Swings acts as an updated API for developing standalone
GUI applications.
The classes which are available in applet package are
platform dependent.
Applet components are generally of heavy weight.
Swing components are platform independent, because the
entire logic for the components are written in java
language only.
Swing components are of light weight components.
If you want to create standalone GUI application by using
Swings API then your class should extends “JFrame”
Applets Vs Swings
Applets Swings
Applet components are platform Swing Components are platform
dependent Independent
Native code & Native methods are used
Purely Written in java
in Applets
Applet components are of heavy weight Swing Components are light weight
Visibility of Applet changes from OS to
Visibility will remain same
OS
Network Programming
There are generally ‘2’ types of Network protocols are
there in the computer networks in order to communicate.
Transmission Control Protocol (TCP)
User Datagram Protocol (UDP)
TCP is a connection based protocol that provides
reliable flow of data between two computers.
UDP sends independent data packets called datagrams,
and there is no guarantee of arrival.
Ip address:
An Internet Protocol address is a numerical label assigned
to each device which are connected in the network.
We can send information to specific system in the network
using IP-address only.
There are 2 version of IP-address
Internet Protocol Version 4 (IPv4)
Internet Protocol Version 6 (IPv6)
Socket Overview
A socket forms the interface between the protocol and the
client.
Java socket forms the base for data transfer between two
computers using TCP/IP.
The socket specifies the site address and the connection port.