Java NOTES PDF
Java NOTES PDF
Java NOTES PDF
Introduction
Java is a programming language and computing platform first released by Sun
Microsystems in 1995.
Java is a programming language and a platform.
Java is a high level, robust, secured and object-oriented programming language.
Platform: Any hardware or software environment in which a program runs, is
known as a platform. Since Java has its own runtime environment (JRE) and API,
it is called platform.
Features of JAVA
Following are the features of Java:
1.Simple
2.Object-Oriented
3.Portable
4.Platform independent
5.Secured
6.Robust
7.Architecture neutral
8.Dynamic
9.Interpreted
10.High Performance
11.Multithreaded
12.Distributed
1.Simple
According to Sun, Java language is simple because:
Syntax is based on C++ (so easier for programmers to learn it after C++)
Removed many confusing and/or rarely-used features e.g. explicit pointers,
operator overloading etc.
No need to remove unreferenced objects because there is Automatic Garbage
Collection in java
2.Object-oriented
Object-oriented means we organize our software as a combination of different
types of objects that incorporates both data and behaviour.
Object-oriented programming(OOPs) is a methodology that simplify software
development and maintenance by providing some rules.
Basic concepts of OOPs are:
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
3.Platform-independent
A platform is the hardware or software environment in which a program runs.
There are two types of platforms software-based and hardware-based. Java
provides software-based platform.
The Java platform differs from most other platforms in the sense that it is a
software-based platform that runs on the top of other hardware-based platforms.
It has two components:
1.Runtime Environment
2.API(Application Programming Interface)
Java code can be run on multiple platforms e.g. Windows, Linux, Sun Solaris,
Mac/OS etc. Java code is compiled by the compiler and converted into bytecode.
This bytecode is a platform-independent code because it can be run on multiple
platforms i.e. Write Once and Run Anywhere(WORA).
4.Secured
Java is secured because:
a) No explicit pointer
C/C++ language uses pointers, which may cause unauthorized access to memory
blocks when other programs get the pointer values. Unlike conventional C/C++
language, Java never uses any kind of pointers. Java has its internal mechanism
for memory management. It only gives access to the data to the program if has
appropriate verified authorization.
b)Byte code
Every time when a user compiles the Java program, the Java compiler creates a
class file with Bytecode, which are tested by the JVM at the time of
program execution for viruses and other malicious files.
5.Robust
Robust simply means strong. Java uses strong memory management. There are
lack of pointers that avoids security problem. There is automatic garbage
collection in java. There is exception handling and type checking mechanism in
java. All these points makes java robust.
6.Architecture-neutral
There is no implementation dependent features e.g. size of primitive types is
fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit
architecture and 4 bytes of memory for 64-bit architecture. But in java, it
occupies 4 bytes of memory for both 32 and 64 bit architectures.
7.Portable
We may carry the java byte code to any platform.
8.High-performance
Java is faster than traditional interpretation since byte code is "close" to native
code still somewhat slower than a compiled language (e.g., C++)
8.Distributed
We can create distributed applications in java. RMI and EJB are used for creating
distributed applications. We may access files by calling the methods from any
machine on the internet.
9.Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java
programs that deal with many tasks at once by defining multiple threads. The
main advantage of multi-threading is that it doesn't occupy memory for each
thread. It shares a common memory area. Threads are important for multi-
media, Web applications etc.
JVMs are available for many hardware and software platforms. JVM, JRE and JDK
are platform dependent because configuration of each OS differs. But, Java is
platform independent.
The JVM performs following main tasks:
Loads code
Verifies code
Executes code
Provides runtime environment
JRE (Java Runtime Environment)
JRE is an acronym for Java Runtime environment.It is used to provide runtime
environment.It is the implementation of JVM. It physically exists. It contains set
of libraries + other files that JVM uses at runtime.
Implementation of JVMs are also actively released by other companies besides
Sun Micro Systems.
The jre directory contains the Java Runtime Environment facilities that are used
when you execute a
Java program. The classes in the Java libraries are stored in the jre\lib directory.
JDK(Java Development Kit.)
JDK is an acronym for Java Development Kit.It physically exists.It contains JRE +
development tools.
Class
A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created. It is a logical entity. It can't be
physical.
A class in Java can contain:
fields
methods
constructors
Class is a template or blueprint from which objects are created. So object is the
instance(result) of a class.
Examples
1.class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
}
}
Explanation:
class keyword is used to declare a class in java.
Public keyword is an access modifier which represents visibility, it means
it is visible to all.
Static is a keyword, if we declare any method as static, it is known as
static method. The core advantage of static method is that there is no need
to create object to invoke the static method. The main method is executed
by the JVM, so it doesn't require to create object to invoke the main
method. So it saves memory.
Void is the return type of the method, it means it doesn't return any value.
Main represents startup of the program.
String[] args is used for command line argument.
System.out.println() is used print statement.
2. class Student{
int id=10;
String name=”Sachin”;
Variables in Java
There are three types of variables in java:-
local
instance
static
1) Local Variable
A variable which is declared inside the method is called local variable.
2) Instance Variable
A variable which is declared inside the class but outside the method, is called
instance variable . It is not declared as static.
3)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
(that is not unique for each object) e.g. company name of
employees,college name of students etc.
The static variable gets memory only once in class area at the time of
class loading.
return min;
}
}
OOPs (Object Oriented Programming System)
Concepts
Following are the Oops concepts:
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
1.Object
Any entity that has state and behavior is known as an object. For example: chair,
pen, table, keyboard, bike etc. It can be physical and logical.
2.Class
Collection of objects is called class. It is a logical entity.
3.Inheritance
When one object acquires all the properties and behaviours of parent
object i.e. known as inheritance. It provides code reusability. It is used to
achieve runtime polymorphism.
Class Animal{
String food=”nonveg”;
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
String drink=”milk”;
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
System.out.println(d.food);
d.bark();
d.eat();
}}
4.Polymorphism
When one task is performed by different ways i.e. known as polymorphism.
For example: to convince the customer differently, to draw something e.g. shape
or rectangle etc.
In java, we use method overloading and method overriding to achieve
polymorphism.
Another example can be to speak something e.g. cat speaks meaw, dog barks
woof etc.There are two types of polymorphism compiletime
polymorphism(method overloading) and runtime polymorphism(method
overriding).
Method overloading
If a class has multiple methods having same name but different signatures, it is
known as Method Overloading. Different signatures means the parameters of
methods may differ in:
a) no of arguments
b) their data types
b) their sequence
Example
1.differ in no of arguments
class Adder{
public int add(int a,int b){return a+b;}
public int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
Adder r=new Adder();
System.out.println(r.add(11,11));
System.out.println(r.add(11,11,11));
}}
Method overriding
Runtime polymorphism or Method overriding is a process in which a call to
an overridden method is resolved at runtime rather than compile-time.
In this process, an overridden method is called through the reference variable of
a superclass. The determination of the method to be called is based on the object
being referred to by the reference variable.
Class Bike{
void run(){System.out.println("running");
}
class Splender extends Bike{
void run(){System.out.println("running safely with 60km");}
public static void main(String args[]){
Bike b =new Splender();//upcasting
b.run();
}
}
6.Encapsulation
Binding (or wrapping) code and data together into a single unit is known
as encapsulation. For example: capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated
class because all the data members are private here.
String Handling
Generally, string is a sequence of characters. But in java, string is an object that
represents a sequence of characters.
Each time you create a string literal, the JVM checks the string constant pool
first. If the string already exists in the pool, a reference to the pooled instance is
returned. If string doesn't exist in the pool, a new string instance is created and
placed in the pool. For example:
1. String s1="Welcome";
2. String s2="Welcome";//will not create new instance
In the above example only one object will be created. Firstly JVM will not find
any string object with the value "Welcome" in string constant pool, so it will
create a new object. After that it will find the string with the value "Welcome" in
the pool, it will not create new object but will return the reference to the same
instance.
Types of string
1.Immutable string
2.Mutable string
1.Immutable String
In java, string objects are immutable. Immutable simply means unmodifiable
or unchangeable.
Once string object is created its data or state can't be changed but a new string
object is created.
Class Testimmutablestring{
public static void main(String args[]){
String s="Jon";
s.concat("Snow");//concat() method appends the string at the end
System.out.println(s);//will print Jon because strings are immutable objects
}
}
2.Mutable String
Mutable means you can change the original string. In java we can make mutable
string using
1.StringBuffer class
2.StringBuilder class
Example
1.
class StringBufferExample{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Winter is ");
sb.append("Coming ");//now original string is changed
System.out.println(sb);//prints Winter is coming
}
}
2.
class StringBuilderExample{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("You know");
sb.append("nothing");//now original string is changed
System.out.println(sb);//prints You know nothing
}
}
Difference between Stringbuffer and Stringbuilder class
Java StringBuffer class is thread-safe i.e. multiple threads cannot access it
simultaneously. So it is safe and will result in an order while StringBulider
class is not.
String Functions
Here are some string functions:
public class StringTutorial {
Exception Handling
Exception-Exception is an abnormal condition.
Exception is an event that disrupts the normal flow of the program. It
is an object which is thrown at run time.
A Java exception is an object that describes an exceptional (that is, error)
condition that has occurred in a piece of code. When an exceptional condition
arises, an object representing that exception is created and thrown in the
method that caused the error. That method may choose to handle the exception
itself, or pass it on. Either way, at some point, the exception is caught and
processed. Exceptions can be generated by the Java run-time system, or they can
be manually generated by your code. Exceptions thrown by Java relate to
fundamental errors that violate the rules of the Java language or the constraints
of the Java execution environment. Manually generated exceptions are typically
used to report some error condition to the caller of a method.
Exception Handling
Exception Handling is a mechanism to handle runtime errors such as
ClassNotFound, IO, SQL, Remote etc.
The core advantage of exception handling is to maintain the normal flow of
the application. Exception normally disrupts the normal flow of the application
that is why we use exception handling
Java exception handling is managed via five keywords: try, catch, throw, throws,
and finally
Try block
Program statements that you want to monitor for exceptions are contained
within a try block. If an exception occurs within the try block, it is thrown.
Catch block
Your code can catch this exception (using catch) and handle it in some rational
manner. System-generated exceptions are automatically thrown by the Java run-
time system.
Throw and throws keyword
To manually throw an exception, use the keyword throw. Any exception that is
thrown out of a method must be specified as such by a throws clause.
Finally block
Any code that absolutely must be executed after a try block completes is put in a
finally block. The immediate nature of an exception being thrown means that
execution of the try block code breaks off, regardless of the importance of the
code that follows the point at which the exception was thrown. This introduces
the possibility that the exception leaves things in an unsatisfactory state. You
might have opened a file, for example, and because an exception was thrown, the
code to close the file is not executed.
The finally block provides the means for you to clean up at the end of executing a
try block. You use a finally block when you need to be sure that some particular
code is run before a method returns, no matter what exceptions are thrown
within the associated try block. A finally block is always executed, regardless of
whether or not exceptions are thrown during the execution of the associated try
block. If a file needs to be closed, or a critical resource released, you can
guarantee that it is done if the code to do it is put in a finally block. The finally
block has a very simple structure:
finally { // Clean-up code to be executed last }
Just like a catch block, a finally block is associated with a particular try block,
and it must be located immediately following any catch blocks for the try block.
If there are no catch blocks then you position
the finally block immediately after the try block. If you don't do this, your
program does not compile.
Note
The primary purpose for the try block is to identify code that may result in an
exception being thrown. However, you can use it to contain code that doesn't
throw exceptions for the convenience of using a finally block. This can be useful
when the code in the try block has several possible exit points — break or return
statements, for example — but you always want to have a specific set of
statements executed after the try block has been executed to make sure things
are tidied up, such as closing any open fi les. You can put these in a finally block.
Note that if a value is returned within a finally block, this return overrides any
return statement executed in the try block.
Types of Exceptions
1) Checked Exception
The classes that extend Throwable class except RuntimeException and Error are
known as checked exceptions e.g.IOException, SQLException and Class Not
Found Exception etc. Checked exceptions are checked at compile-time.
2) Unchecked Exception
The classes that extend RuntimeException are known as unchecked exceptions
e.g.ArithmeticException,NullPointerException,ArrayIndexOutOfBoundsException
etc. Unchecked exceptions are not checked at compile-time rather they are
checked at runtime.
Example
1. int a=50/0;//ArithmeticException
2. String s=null;
System.out.println(s.length());//NullPointerException
Example of throw
class ThrowDemo {
public void demoproc()
{
throw new NullPointerException("demo");
}
O/p:
java.lang.NullPointerException: demo
Here, new is used to construct an instance of NullPointerException. Many of
Java’s built in run-time exceptions have at least two constructors: one with no
parameter and one that takes a string parameter. When the second form is used,
the argument specifies a string that describes the exception. This string is
displayed when the object is used as an argument to print( ) or println( ). It can
also be obtained by a call to getMessage( ), which is defined by Throwable.
Example of throws
class ThrowsDemo
{
static void throwOne() throws IllegalAccessException
{
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[])
{
try { throwOne();
}
catch (IllegalAccessException e)
{
System.out.println("Caught " + e);
}}}
O/p:
inside throwOne caught java.lang.IllegalAccessException: demo
Java I/O
Java I/O (Input and Output) is used to process the input and produce the output.
Java uses the concept of stream to make I/O operation fast. The java.io package
contains all the classes required for input and output operations.
Stream
A stream is an abstract representation of an input or output device that is a
source of, or destination for, data.
The stream concept enables you to transfer data to and from diverse physical
devices such as disk fi les, communications links, or just your keyboard, in
essentially the same way.
In general you can write data to a stream or read data from a stream. You can
visualize a stream as a sequence of bytes that flows into or out of your program
Types of Streams
1.Byte or Binary stream
2.Character Stream
The java.io package supports two types of streams — binary streams, which
contain binary data, and character streams, which contain character data.
Binary Stream
When you write data to a binary stream, the data is written to the stream as a
series of bytes, exactly as it appears in memory. No transformation of the data
takes place. Binary numerical values are just written as a series of bytes, 4 bytes
for each value of type int, 8 bytes for each value of type long, 8 bytes for each
value of type double, and so on.
Example
import java.util.Scanner;
Scanner sc = new Scanner(System.in);
String str = null;
do {
str = sc.nextLine();
System.out.println(str);
} while (!str.equals("exit"));
sc.close();
Character Stream
Character streams are used for storing and retrieving text. You may also use
character streams to read text files not written by a Java program.
All binary numeric data has to be converted to a textual representation before
being written to a character stream. This involves generating a character
representation of the original binary data value.
Reading numeric data from a stream that contains text involves much more work
than reading binary data.
When you read a value of type int from a binary stream, you know that it consists
of 4 bytes. When you read an integer from a character stream, you have to
determine how many characters from the stream make up the value. For each
numerical value you read from a character stream, you have to be able to
recognize where the value begins and ends and then convert the token — the
sequence of characters that represents the value — to its binary form.
Example
import java.io.BufferedInputStream;
BufferedInputStream bis = new BufferedInputStream(System.in);
Scanner sc = new Scanner(bis);
String str = null;
do{
str = sc.nextLine();
System.out.println(str);
} while(!str.equals("exit"));
sc.close();
Java Applet
Applet is a special type of program that is embedded in the web page to generate
the dynamic content. It runs inside the browser and works at client side.
Advantage of Applet
There are many advantages of applet. They are as follows:
It works at client side so less response time.
Secured
It can be executed by browsers running under many platforms, including
Linux, Windows, Mac Os etc.
Drawback of Applet
Plugin is required at client browser to execute applet.
Lifecycle of Java Applet
1.Applet is initialized.
2.Applet is started.
3.Applet is painted.
4.Applet is stopped.
5.Applet is destroyed.
Lifecycle methods for Applet:
The java.applet.Applet class provides 4 life cycle methods and
java.awt.Component class provides 1 life cycle
methods for an applet.
java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4
life cycle methods of applet.
1.public void init():is used to initialized the Applet. It is invoked only once.
4.public void destroy():is used to destroy the Applet. It is invoked only once.
java.awt.Component class
The Component class provides 1 life cycle method of applet.
Example
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
public class AppletEx extends Applet
{
public void paint(Graphics g)
{
g.drawOval(10,10,100,100);
g.setColor(Color.BLUE);
g.fillRectangle(120,120,100,100);
setBackground(Color.YELLOW);
}
}
MULTITHREADING:
Java provides built-in support for multithreaded programming. A multithreaded program
contains two or more parts that can run concurrently. Each part of such a program is
called a
thread,and each thread defines a separate path of execution. Thus, multithreading is a
specialized form of multitasking.
There are two distinct types of multitasking: process-based and thread-based.
understand the A process is a program that is executing. Thus,process-based
multitasking is the feature that allows your computer to run two or more programs
concurrently. For example, process-based multitasking enables you to run the Java
compiler at the same time that you are using a text editor.
In process-based multitasking, a program is the smallest unit of code that can be
dispatched by the scheduler.In a thread-based multitasking environment, the thread is
the smallest unit of dispatchable code. This means that a single program can perform
two or more tasks simultaneously. For example, a text editor can format text at the same
time that it is printing, as long as these two actions are being performed by two
separate threads.
• New − A new thread begins its life cycle in the new state. It remains in this state
until the program starts the thread.
Creating Thread:
We can define a class that is to represent a thread in two ways:
1. Defining a subclass of Thread that provides a definition of the run()method that
overrides the
inherited method.
2.Defining class as implementing the Runnable interface, which declares the run()
method,
and then creates a Thread object in your class when you need it.
System.out.println("Main Thread");
}
}
class ThreadEx2 extends Thread {
@Override
public void run() {
Example:
public class ThreadTutorial {
public static void main(String[] args) {
ThreadEx3 thread3 = new ThreadEx3();
thread3.start();
System.out.println("Main Thread");
}
}
class ThreadEx3 extends Thread {
@Override
public void run() {
try {
for (int i = 0; i < 20; i++) {
if(i == 5) {
Thread.sleep(5000);
}
The AWT classes are contained in the java.awt package. It is one of Java’s largest
packages. Fortunately, because it is logically organized in a top-down, hierarchical
fashion, it is easier to understand.
Fig:AWT Hierarchy
Component
At the top of the AWT hierarchy is the Component class. Component is an abstract
class that encapsulates all of the attributes of a visual component. All user interface
elements that are displayed on the screen and that interact with the user are
subclasses of Component.It defines over a hundred public methods that are
responsible for managing events, such as mouse and keyboard input, positioning and
sizing the window, and repainting. A Component object is responsible for
remembering the current foreground and background colors and the currently
selected text font.
Container
The Container class is a subclass of Component.It has additional methods that allow
other Component objects to be nested within it. Other Container objects can be stored
inside of a Container(since they are themselves instances of Component).
Window
The Window class creates a top-level window. A top-level window is not contained within
any other object; it sits directly on the desktop. Generally, we won’t create Window
objects directly. Instead, we will use a subclass of Window called Frame.
Frame
Frame encapsulates what is commonly thought of as a “window.” It is a subclass of
Window and has a title bar, menu bar, borders, and resizing corners.
AWT Controls:
list of commonly used controls while designed GUI using AWT is as follows:
1. TextField
2.Button
3.Label
4.CheckBox
5.List
6.TextArea
7.Dialog
8.Image etc.
To create any of the above control in GUI we need to create object for that class.
Example: Creating Button in AWT.
import java.awt.*;
import java.awt.event.*;
Layout Managers
Layout manager is responsible for positioning the controls within the container.
They eliminate the need of user to place the control on their own. A Layout
manager is an interface that automatically arranges your controls within a window by
using some type of algorithm. This interface has several classes.
1.FlowLayout:
FlowLayout is the default layout manager. FlowLayout implements a simple layout
style, which is similar to how words flow in a text editor. The direction of the layout is
governed by the container ’s component orientation property, which, by default, is left
to right, top to bottom. Therefore, by default, components are laid out line-by-line
beginning at the upper-left corner. In all
cases, when a line is filled, layout advances to the next line. A small space is left
between each component, above and below, as well as left and right. Constructors for
flow layouts are:
FlowLayout( )
FlowLayout(int how)
FlowLayout(int how, int horz, int vert )
The first form creates the default layout, which centers components and leaves five
pixels of space between each component. The second form lets you specify how each
line is aligned. Valid values for how are as follows:
FlowLayout.LEFT
FlowLayout.CENTER
FlowLayout.RIGHT
FlowLayout.LEADING
FlowLayout.TRAILING
These values specify left, center, right, leading edge, and trailing edge alignment,
respectively.
Example:
The first form creates a single-column grid layout. The second form creates a grid
layout with the specified number of rows and columns. Either numRows or
numColumns can be zero.
Example:
Example:
Event Handling:
Event: Any activity that interrupts the current ongoing activity. Event source is
the object that generates the event. The task of handling event is done by event-
listener. When an event occur find an object of appropriate type is created. Then
that object is then passed to a listener. A listener must implement that the
interface that has the method for event handling.