0% found this document useful (0 votes)
5 views163 pages

core java

Java is a programming language developed by Sun Microsystems, initially released in 1995, with its latest version being Java SE 8. It features simplicity, object-oriented design, platform independence, and security, making it suitable for various applications including enterprise and mobile. The Java Virtual Machine (JVM) provides a runtime environment for executing Java bytecode, while Java's data types and control structures facilitate efficient programming.

Uploaded by

pranita.tathe15
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
5 views163 pages

core java

Java is a programming language developed by Sun Microsystems, initially released in 1995, with its latest version being Java SE 8. It features simplicity, object-oriented design, platform independence, and security, making it suitable for various applications including enterprise and mobile. The Java Virtual Machine (JVM) provides a runtime environment for executing Java bytecode, while Java's data types and control structures facilitate efficient programming.

Uploaded by

pranita.tathe15
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 163

Core java

Java programming language was originally developed by Sun Microsystems which was initiated
by James Gosling and released in 1995 as core component of Sun Microsystems' Java platform.
The latest release of the Java Standard Edition is Java SE 8. With the advancement of Java and its
widespread popularity, multiple configurations were built to suit various types of platforms. For
example: J2EE for Enterprise Applications, J2ME for Mobile Applications.
History of Java
James Gosling initiated Java language project in June 1991 for use in one of his many set-top box
projects. The language, initially called ‘Oak’ after an oak tree that stood outside Gosling's office,
also went by the name ‘Green’ and ended up later being renamed as Java, from a list of random
words.
Features of Java
• Simple
• Java is very easy to learn, and its syntax is simple, clean and easy to understand.
According to Sun, Java language is a simple programming language because:
• Java syntax is based on C++ (so easier for programmers to learn it after C++).
• Java has removed many complicated and rarely-used features, for example, explicit
pointers, operator overloading, etc.
• There is no need to remove unreferenced objects because there is an Automatic
Garbage Collection in Java.
• Object-oriented
• Java is an object-oriented programming language. Everything in Java is an object.
Object-oriented means we organize our software as a combination of different types of
objects that incorporates both data and behavior.
• Object-oriented programming (OOPs) is a methodology that simplifies software
Platform Independent
• ava is platform independent because it is different from other languages like C, C++, etc.
which are compiled into platform specific machines while Java is a write once, run
anywhere language. 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 a
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:
• Secured
• Java is best known for its security. With Java, we can develop virus-free systems. Java is
secured because:
• No explicit pointer
Robust

• Robust simply means strong. Java is robust because:


• It uses strong memory management.
• There is a lack of pointers that avoids security problems.
• There is automatic garbage collection in java which runs on the Java Virtual Machine to
get rid of objects which are not being used by a Java application anymore.
• There are exception handling and the type checking mechanism in Java. All these
points make Java robust.
• Architecture-neutral
• ava is architecture neutral because there are no implementation dependent features,
for example, the 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. However, it occupies 4 bytes of memory for
both 32 and 64-bit architectures in Java.
• Portable
• Java is portable because it facilitates you to carry the Java bytecode to any
platform. It doesn't require any implementation.
• High-performance
• Java is faster than other traditional interpreted programming languages because
Java bytecode is "close" to native code. It is still a little bit slower than a compiled
language (e.g., C++). Java is an interpreted language that is why it is slower than
compiled languages, e.g., C, C++, etc.
• Distributed
• Java is distributed because it facilitates users to create distributed applications in
Java. RMI and EJB are used for creating distributed applications. This feature of
Java makes us able to access files by calling the methods from any machine on
the internet
• 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.
• Dynamic
• Java is a dynamic language. It supports dynamic loading of classes. It means
classes are loaded on demand. It also supports functions from its native
languages, i.e., C and C++.
• Java supports dynamic compilation and automatic memory management
(garbage collection).
C++ vs Java
Comparison Index C++ Java
Platform-independent C++ is platform-dependent. Java is platform-independent.
Mainly used for C++ is mainly used for system Java is mainly used for
programming. application programming. It is
widely used in window, web-
based, enterprise and mobile
applications.
Design Goal C++ was designed for Java was designed and created
systems and applications as an interpreter for printing
programming. It was an systems but later extended as
extension of a support network computing.
C programming language. It was designed with a goal of
being easy to use and
accessible to a broader
audience.
Goto C++ supports the goto Java doesn't support the goto
statement. statement.
Multiple inheritance C++ supports multiple Java doesn't support multiple
inheritance. inheritance through class. It
Data type
Data Type Default Value Default size

boolean false 1 bit

char '\u0000' 2 byte

byte 0 1 byte

short 0 2 byte

int 0 4 byte

long 0L 8 byte

float 0.0f 4 byte

double 0.0d 8 byte


JVM (Java Virtual Machine) Architecture

• JVM (Java Virtual Machine) is an abstract machine. It is a specification that


provides runtime environment in which java bytecode can be executed.
• JVMs are available for many hardware and software platforms (i.e. JVM is
platform dependent).
• What is JVM
• It is:
• A specification where working of Java Virtual Machine is specified. But
implementation provider is independent to choose the algorithm. Its
implementation has been provided by Oracle and other companies.
• An implementation Its implementation is known as JRE (Java Runtime
Environment).
• Runtime Instance Whenever you write java command on the command prompt
to run the java class, an instance of JVM is created.
• What it does
• The JVM performs following operation:
• Loads code
• Verifies code
• Executes code
• Provides runtime environment
• JVM provides definitions for the:
• Memory area
• Class file format
• Register set
• Garbage-collected heap
JVM
• 2) Class(Method) Area
• Class(Method) Area stores per-class structures such as the runtime constant pool, field and method data, the
code for methods.
• 3) Heap
• It is the runtime data area in which objects are allocated.
• 4) Stack
• Java Stack stores frames. It holds local variables and partial results, and plays a part in method invocation and
return.
• Each thread has a private JVM stack, created at the same time as thread.
• A new frame is created each time a method is invoked. A frame is destroyed when its method invocation
completes.
• 5) Program Counter Register
• PC (program counter) register contains the address of the Java virtual machine instruction currently being
executed.
• 6) Native Method Stack
• It contains all the native methods used in the application.
Java Variables
• A variable is a container which holds the value while the java program is executed. A variable is assigned
with a datatype.
• Variable is a name of memory location. There are three types of variables in java: local, instance and
static.
• There are two types of data types in java: primitive and non-primitive.
• Types of Variables
• There are three types of variables in java:
• local variable
• instance variable
• static variable
• 1) Local Variable
• A variable declared inside the body of the method is called local variable. You can use this variable only
within that method and the other methods in the class aren't even aware that the variable exists.
• A local variable cannot be defined with "static" keyword.
variable
• 2) Instance Variable
• A variable declared inside the class but outside the body of the method, is called
instance variable. It is not declared as static.
• It is called instance variable because its value is instance specific and is not
shared among instances.
• 3) Static variable
• A variable which is declared as static is called static variable. It cannot be local.
You can create a single copy of static variable and share among all the instances
of the class. Memory allocation for static variable happens only once when the
class is loaded in the memory.
Data Types in Java

• Data types specify the different sizes and values that can be stored in the
variable. There are two types of data types in Java:
• Primitive data types: The primitive data types include boolean, char, byte, short,
int, long, float and double.
• Non-primitive data types: The non-primitive data types include Classes,
Interfaces, and Arrays.
• Java Primitive Data Types
• In Java language, primitive data types are the building blocks of data
manipulation. These are the most basic data types available in Java language.
operators
Operator Type Category Precedence

Unary postfix expr++ expr--


prefix ++expr --expr +expr -expr ~ !

Arithmetic multiplicative */%


additive +-
Shift shift << >> >>>
Relational comparison < > <= >= instanceof

equality == !=
Bitwise bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
Logical logical AND &&
logical OR ||
Ternary ternary ?:
Assignment assignment = += -= *= /= %= &= ^= |= <<= >>=
>>>=
What happen complie time.

Complier
Java code Byte code
How to run program
Code file

classloader

Bytecodeverifier

Interpreter

Runtime

Hardware
Java I/O
• Java I/O (Input and Output) is used to process the input and produce the output.
• Java uses the concept of a 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 a sequence of data. In Java, a stream is composed of bytes. It's called
a stream because it is like a stream of water that continues to flow.
• In Java, 3 streams are created for us automatically. All these streams are attached
with the console.
• 1) System.out: standard output stream
• 2) System.in: standard input stream
• 3) System.err: standard error stream
Java BufferedReader Class
• Java BufferedReader class is used to read the text from a character-based input
stream. It can be used to read data line by line by readLine() method. It makes the
performance fast. It inherits Reader class.

Constructor Description

BufferedReader(Reader rd) It is used to create a buffered character input stream


that uses the default size for an input buffer.

BufferedReader(Reader rd, int size) It is used to create a buffered character input stream
that uses the specified size for an input buffer.
public static void main(String[] args)
• Public
• It is an Access Modifier, which defines who can access this Method. Public means
that this Method will be accessible by any Class(If other Classes can access this
Class.).
• Static
• Static is a keyword which identifies the class related thing. It means the given
Method or variable is not instance related but Class related. It can be accessed
without creating the instance of a Class.
• Void
• Is used to define the Return Type of the Method. It defines what the method can
return. Void means the Method will not return any value.
main
• Main ss the name of the Method. This Method name is searched by JVM as a starting point for an
application with a particular signature only.
• String args[] / String… args
• It is the parameter to the main Method. Argument name could be anything.
Java try-catch
• Java try block
• Java try block is used to enclose the code that might throw an exception. It must be used within
the method.
• Java try block must be followed by either catch or finally block.
• Syntax of Java try-catch
• try{
• //code that may throw exception
• }catch(Exception_class_Name ref){}
Java catch block
• Java catch block is used to handle the Exception. It must be used after the try
block only.
• You can use multiple catch block with a single try.
• The JVM firstly checks whether the exception is handled or not. If exception is
not handled, JVM provides a default exception handler that performs the
following tasks:
• Prints out exception description.
• Prints the stack trace (Hierarchy of methods where the exception occurred).
• Causes the program to terminate.
• But if exception is handled by the application programmer, normal flow of the
application is maintained i.e. rest of the code is executed.
Java Integer parseInt() Method
• The parseInt() method is a method of Integer class under java.lang package. There are three different types of Java
Integer parseInt () methods which can be differentiated depending on its parameter.
• These are:
• Java Integer parseInt (String s) Method
• Java Integer parseInt (String s, int radix) Method
• a Integer parseInt(CharSequence s, int beginText, int endText, int radix)
• 1. Java Integer parseInt (String s) Method
• This method parses the String argument as a signed decimal integer object. The characters in the string must be decimal
digits, except that the first character of the string may be an ASCII minus sign '-' to indicate a negative value or an
ASCII plus '+' sign to indicate a positive value. It returns the integer value which is represented by the argument in a
decimal integer.
• 2. Java Integer parseInt (String s, int radix) Method
• This method parses the String argument as a signed decimal integer object in the specified radix by the second
argument. The characters in the string must be decimal digits of the specified argument except that the first character
may be an ASCII minussign '-' to indicate a negative value or an ASCII plus sign '+' to indicate a positive value. The
resulting integer value is to be returned.
• 3. Java Integer parseInt (CharSequence s, int beginText, int endText, int radix)
• This method parses the CharSequence argument as a signed integer in the specified radix argument, beginning at the
specified beginIndex and extending to endIndex - 1. This method does not take steps to guard against the CharSequence
How to set path
• To set the temporary path of JDK, you need to follow the following steps:
• Open the command prompt
• Copy the path of the JDK/bin directory
• Write in command prompt: set path=copied_path
• Java If-else Statement
• The Java if statement is used to test the condition. It checks boolean con
• dition: true or false. There are various types of if statement in java.
• if(condition){
• //code to be executed
•}
Java Nested if statement

• The nested if statement represents the if block within another if block. Here, the
inner if block condition executes only when outer if block condition is true.
• if(condition)
•{
• //code to be executed
• if(condition)
•{
• //code to be executed
• }
•}
Java Switch Statement
• The Java switch statement executes one statement from multiple conditions. It is like if-else-if ladder
statement. The switch statement works with byte, short, int, long, enum types, String and some
wrapper types like Byte, Short, Int, and Long. Since Java 7, you can use strings in the switch statement.
• switch(expression){
• case value1:
• //code to be executed;
• break; //optional
• case value2:
• //code to be executed;
• break; //optional
• ......

• default:
• code to be executed if all cases are not matched;
• }
Java While Loop

• The Java while loop is used to iterate a part of the program several times. If the
number of iteration is not fixed, it is recommended to use while loop.
• Syntax:
• while(condition){
• //code to be executed
•}
• Java do-while Loop
• The Java do-while loop is used to iterate a part of the program several times. If
the number of iteration is not fixed and you must have to execute the loop at
least once, it is recommended to use do-while loop.
• The Java do-while loop is executed at least once because condition is checked
after loop body.
Syntax
• do{
• //code to be executed
• }while(condition);
• For Loop
• We can have a name of each Java for loop. To do so, we use label before the for
loop. It is useful if we have nested for loop so that we can break/continue specific
for loop.
• for(initialization;condition;incr/decr){
• //code to be executed
•}
What is a class in Java
• 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
• Blocks
• Nested class and interface
• class <class_name>{
• field;
• method;
What is an object

• An entity that has state and behavior is known as an object e.g. chair, bike,
marker, pen, table, car etc. It can be physical or logical (tangible and intangible).
The example of an intangible object is the banking system.
• An object has three characteristics:
• State:represents the data (value) of an object.
• Behavior: represents the behavior (functionality) of an object such as deposit,
withdraw, etc.
• Identity: An object identity is typically implemented via a unique ID. The value of
the ID is not visible to the external user. However, it is used internally by the JVM
to identify each object uniquely.
Access Modifiers in java

• There are two types of modifiers in java: access modifiers and non-access
modifiers.
• The access modifiers in java specifies accessibility (scope) of a data member,
method, constructor or class.
• There are 4 types of java access modifiers:
• private
• default
• protected
• public
Java static keyword
• The static keyword in Java is used for memory management mainly. We can apply java static
keyword with variables, methods, blocks and nested class. The static keyword belongs to the
class than an instance of the class.
• The static can be:
• Variable (also known as a class variable)
• Method (also known as a class method)
• Block
• Nested clas
• 1) Java static variable
• If you declare any variable as static, it is known as a static variable.
• The static variable can be used to refer to the common property of all objects (which is not
unique for each object), for example, the company name of employees, college name of
students, etc.
2) Java static method

• If you apply static keyword with any method, it is known as static method.
• A static method belongs to the class rather than the object of a class.
• A static method can be invoked without the need for creating an instance of a
class.
• A static method can access static data member and can change the value of it.
• 3) Java static block
• Is used to initialize the static data member.
• It is executed before the main method at the time of classloading.
this keyword in java
• There can be a lot of usage of java this keyword. In java, this is a reference
variable that refers to the current object.

this
state
• Here is given the 6 usage of java this keyword.
• this can be used to refer current class instance variable.
• this can be used to invoke current class method (implicitly)
• this() can be used to invoke current class constructor.
• this can be passed as an argument in the method call.
• this can be passed as argument in the constructor call.
• this can be used to return the current class instance from the method.
Constructors in Java

• In Java, a constructor is a block of codes similar to the method. It is called when an


instance of the object is created, and memory is allocated for the object.
• Rules for creating Java constructor
• There are two rules defined for the constructor.
• Constructor name must be the same as its class name
• A Constructor must have no explicit return type
• A Java constructor cannot be abstract, static, final, and synchronized
• Types of Java constructors
• There are two types of constructors in Java:
• Default constructor (no-arg constructor)
• Parameterized constructor
Java Default Constructor
• A constructor is called "Default Constructor" when it doesn't have any parameter.
• <class_name>(){}
• Java Parameterized Constructor
• A constructor which has a specific number of parameters is called a parameterized
constructor.
• Constructor Overloading in Java
• In Java, a constructor is just like a method but without return type. It can also be
overloaded like Java methods.
• Constructor overloading in Java is a technique of having more than one constructor with
different parameter lists. They are arranged in a way that each constructor performs a
different task. They are differentiated by the compiler by the number of parameters in the
list and their types.
Method Overloading in Java
• If a class has multiple methods having same name but different in parameters, it
is known as Method Overloading.
• If we have to perform only one operation, having same name of the methods
increases the readability of the program.
• Advantage of method overloading
• Method overloading increases the readability of the program.
• Different ways to overload the method
• There are two ways to overload the method in java
• By changing number of arguments
• By changing the data type
Method Overriding in Java
• If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in Java.
• In other words, If a subclass provides the specific implementation of the method
that has been declared by one of its parent class, it is known as method overriding.
• Usage of Java Method Overriding
• Method overriding is used to provide the specific implementation of a method
which is already provided by its superclass.
• Method overriding is used for runtime polymorphism
• Rules for Java Method Overriding
• The method must have the same name as in the parent class
• The method must have the same parameter as in the parent class.
• There must be an IS-A relationship (inheritance).
Difference between method overloading and method
overriding in java
No. Method Overloading Method Overriding
1)
Method overloading is used to Method overriding is used to
increase the readability of the provide the specific
program. implementation of the method
that is already provided by its
super class.
2)
Method overloading is Method overriding occurs in
performed within class. two classes that have IS-A
(inheritance) relationship.
3)
In case of method In case of method
overloading, parameter must overriding, parameter must be
be different. same.
4)
Method overloading is the Method overriding is the
example of compile time example of run time
polymorphism. polymorphism.
5)
In java, method overloading Return type must be same or
For Code Reusability.

Inheritance in Java
• Inheritance in Java is a mechanism in which one object acquires all the properties
and behaviors of a parent object. It is an important part of OOPs (Object Oriented
programming system)
• The idea behind inheritance in Java is that you can create new classes that are
built upon existing classes. When you inherit from an existing class, you can reuse
methods and fields of the parent class. Moreover, you can add new methods and
fields in your current class also.
• Inheritance represents the IS-A relationship which is also known as a parent-
child relationship.
• Why use inheritance in java
• For Method Overriding (so runtime polymorphism can be achieved).
• For Code Reusability.
Types of inheritance in java

Class A Class A
Class A

C;ass B
Class B Class c

Class B Class C

Hirechical
inheritance

Single inheritance Multilevel


Super Keyword

• The super keyword in Java is a reference variable which is used to refer immediate
class object.
• Whenever you create the instance of subclass, an instance of parent class is create
implicitly which is referred by super reference variable.
• Usage of Java super Keyword
• super can be used to refer immediate parent class instance variable.
• super can be used to invoke immediate parent class method.
• super() can be used to invoke immediate parent class constructor.
Final Keyword In Java

• The final keyword in java is used to restrict the user. The java final keyword can
be used in many context. Final can be:
• variable
• method
• class
• The final keyword can be applied with the variables, a final variable that have no
value it is called blank final variable or uninitialized final variable. It can be
initialized in the constructor only. The blank final variable can be static also which
will be initialized in the static block only. We will have detailed learning of these.
Let's first learn the basics of final keyword.
Java Array

• Normally, an array is a collection of similar type of elements that have a


contiguous memory location.
• Java array is an object which contains elements of a similar data type. It is a data
structure where we store similar elements. We can store only a fixed set of
elements in a Java array.
• Array in java is index-based, the first element of the array is stored at the 0 index.
• Advantages
• Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
• Random access: We can get any data located at an index position.
• Disadvantages
• Size Limit: We can store only the fixed size of elements in the array. It doesn't
grow its size at runtime. To solve this problem, collection framework is used in
Java which grows automatically.
• There are two types of array.
• Single Dimensional Array
• Multidimensional Array
Abstract class
• A class which is declared with the abstract keyword is known as an abstract class in
Java. It can have abstract and non-abstract methods (
• method with the body).
• Abstraction is a process of hiding the implementation details and showing only
functionality to the user.
• Another way, it shows only essential things to the user and hides the internal details,
for example, sending SMS where you type the text and send the message. You 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
• There are two ways to achieve abstraction in java
• Abstract class (0 to 100%)
• A class which is declared as abstract is known as an abstract class. It can have
abstract and non-abstract methods. It needs to be extended and its method I
• mplemented. It cannot be instantiated.
• A class which is declared as abstract is known as an abstract class. It can have
abstract and non-abstract methods. It needs to be extended and its method
implemented. It cannot be instantiated.
String
• In Java, string is basically an object that represents sequence of char values. An array of
characters works same as Java string.
• char[] ch={'j','a','v','a','t','p','o','i','n','t'};
• String s=new String(ch)
• String s=“Welcome”
• Generally, String is a sequence of characters. But in Java, string is an object that represents a
sequence of characters. The java.lang.String class is used to create a string object.
• How to create a string object?
• There are two ways to create String object:
• By string literal
• By new keyword
• 1) String Literal
• Java String literal is created by using double quotes. For Example:
• By new keyword
• String s=new String("Welcome");
char charAt(int index) returns char value for the particular index
int length() returns string length
static String format(String format, Object... returns a formatted string.
args)

static String format(Locale l, String format, returns formatted string with given locale.
Object... args)

String substring(int beginIndex) returns substring for given begin index.


String substring(int beginIndex, int endIndex returns substring for given begin index and end index.
)

boolean contains(CharSequence s) returns true or false after matching the sequence of char
value.
static String join(CharSequence delimiter, C returns a joined string.
harSequence... elements)

static String join(CharSequence delimiter, It returns a joined string.


erable<? extends CharSequence> elements
)

0 boolean equals(Object another) checks the equality of string with the given object.

1 boolean isEmpty() checks if string is empty.


2 String concat(String str) concatenates the specified string.
3 String replace(char old, char new) replaces all occurrences of the specified char value.
Java StringBuffer
• Java StringBuffer class is used to create mutable (modifiable) string. The
StringBuffer class in java is same as String class except it is mutable i.e. it can be
changed.
Constructor Description

StringBuffer() creates an empty string buffer with the initial


capacity of 16.

StringBuffer(String str) creates a string buffer with the specified string.

StringBuffer(int capacity) creates an empty string buffer with the specified


capacity as length.
Difference between StringBuffer and StringBuilder

• Java provides three classes to represent a sequence of characters: String,


StringBuffer, and StringBuilder. The String class is an immutable class whereas
StringBuffer and StringBuilder classes are mutable. There are many differences
between StringBuffer and StringBuilder. The StringBuilder class is introduced s
• ince JDK 1.5.
No. StringBuffer StringBuilder

1) StringBuffer is synchronized i.e. StringBuilder is non-


thread safe. It means two synchronized i.e. not thread
threads can't call the methods of safe. It means two threads can
StringBuffer simultaneously. call the methods of StringBuilder
simultaneously.

2) StringBuffer is less efficient than StringBuilder is more


StringBuilder. efficient than StringBuffer.
Wrapper class in Java

• Wrapper class in java provides the mechanism to convert primitive into object
and object into primitive.
• Since J2SE 5.0, autoboxing and unboxing feature converts primitive into object
and object into primitive automatically. The automatic conversion of primitive
into object is known as autoboxing and vice-versa unboxing.
• The eight classes of java.lang package are known as wrapper classes in java
Primitive Type Wrapper class

boolean Boolean

char Character

byte Byte

short Short

int Integer

long Long

float Float

double Double
• Autoboxing in Java is used to convert automatically convert the primitive data
types into corresponding objects.
• Unboxing in Java is reverse of Autoboxing, i.e. it converts wrapper class object
into its corresponding primitive data type.
Java Vector
• Java Vector class comes under the java.util package. The vector class implements
a growable array of objects. Like an array, it contains the component that can be
accessed using an integer index.
• Vector is very useful if we don't know the size of an array in advance or we need
one that can change the size over the lifetime of a program.
• Vector implements a dynamic array that means it can grow or shrink as required.
It is similar to the ArrayList, but with two differences-
• Vector is synchronized.
• The vector contains many legacy methods that are not the part of a collections
framework
• public class Vector<E>
• extends Object<E>
SN Constructor Description

1) vector() It constructs an empty vector with the


default size as 10.

2) vector(int initialCapacity) It constructs an empty vector with the


specified initial capacity and with its
capacity increment equal to zero.

3) vector(int initialCapacity, int It constructs an empty vector with the


capacityIncrement) specified initial capacity and capacity
increment.

4) Vector( Collection<? extends E> c) It constructs a vector that contains the


elements of a collection c.
Interface in Java

• An interface in java is a blueprint of a class. It has static constants and abstract


methods.
• The interface in Java is a mechanism to achieve abstraction. There can be only
abstract methods in the Java interface, not method body. It is used to achieve
abstraction and multiple inheritance in Java.
• In other words, you can say that interfaces can have abstract methods and
variables. It cannot have a method body.
• Java Interface also represents the IS-A relationship.
• It cannot be instantiated just like the abstract class.
• Since Java 8, we can have default and static methods in an interface.
• Since Java 9, we can have private methods in an interface.
Why use Java interface?
• There are mainly three reasons to use interface. They are given below.
• It is used to achieve abstraction.
• By interface, we can support the functionality of multiple inheritance.
• It can be used to achieve loose coupling.
• interface <interface_name>
•{

• // declare constant fields
• // declare methods that abstract
• // by default.
•}
Java Package
• A java package is a group of similar types of classes, interfaces and sub-packages.
• Package in java 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.
• Here, we will have the detailed learning of creating and using user-defined
packages.
• Advantage of Java Package
• 1) Java package is used to categorize the classes and interfaces so that they can
be easily maintained.
• 2) Java package provides access protection.
• 3) Java package removes naming collision.
How to compile it

• If you are not using any IDE, you need to follow the syntax given below:
• javac -d . directory javafilename .
• The -d switch specifies the destination where to put the generated class file. You
can use any directory name like /home (in case of Linux), d:/abc (in case of
windows) etc. If you want to keep the package within the same directory, you can
use . (dot).
• How to access package from another package?
• There are three ways to access the package from outside the package.
• import package.*;
• import package.classname;
• Types of packages in Java
• As mentioned in the beginning of this guide that we have two types of
packages in java.
1) User defined package: The package we create is called user-defined
package.
2) Built-in package: The already defined package like java.io.*,
java.lang.* etc are known as built-in packages.
Exception Handling in Java

• The Exception Handling in Java is one of the powerful mechanism to


handle the runtime errors so that normal flow of the application can
be maintained.
• In this page, we will learn about Java exceptions, its type and the
difference between checked and unchecked exceptions.
• What is Exception in Java
• Dictionary Meaning: Exception is an abnormal condition.
• In Java, an exception is an event that disrupts the normal flow of the
program. It is an object which is thrown at runtime.
Types of Java Exceptions

• There are mainly two types of exceptions: checked and unchecked. Here, an error is considered as the unchecked exception.
According to Oracle, there are three types of exceptions:
• Checked Exception
• Unchecked Exception
• Error
• Difference between Checked and Unchecked Exceptions
• 1) Checked Exception
• The classes which directly inherit Throwable class except RuntimeException and Error are known as checked exceptions e.g.
IOException, SQLException etc. Checked exceptions are checked at compile-time.
• 2) Unchecked Exception
• The classes which inherit RuntimeException are known as unchecked exceptions e.g. ArithmeticException,
NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-time, but they
are checked at runtime.
• 3) Error
• Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
Java Exception Keywords
Keyword Description
try The "try" keyword is used to specify a block
where we should place exception code. The try
block must be followed by either catch or
finally. It means, we can't use try block alone.
catch The "catch" block is used to handle the
exception. It must be preceded by try block
which means we can't use catch block alone.
It can be followed by finally block later.
Finally The "finally" block is used to execute the
important code of the program. It is executed
whether an exception is handled or not.
throw The "throw" keyword is used to throw an
exception.
throws The "throws" keyword is used to declare
exceptions. It doesn't throw an exception. It
specifies that there may occur an exception in
Java try-catch block
• Java try block
• Java try block is used to enclose the code that might throw an exception. It must
be used within the method.
• If an exception occurs at the particular statement of try block, the rest of the
block code will not execute. So, it is recommended not to keeping the code in try
block that will not throw an exception.
• Java try block must be followed by either catch or finally block.
• try{
• //code that may throw an exception
• }catch(Exception_class_Name ref){}
Java catch block

• Java catch block is used to handle the Exception by declaring the type of exception within
the parameter. The declared exception must be the parent class exception ( i.e.,
Exception) or the generated exception type. However, the good approach is to declare the
generated type of exception.
• The catch block must be used after the try block only. You can use multiple catch block
with a single try block.
• Java catch multiple exceptions
• A try block can be followed by one or more catch blocks. Each catch block must contain a
different exception handler. So, if you have to perform different tasks at theAt a time only
one exception occurs and at a time only one catch block is executed.
• All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.
Java Nested try block

• The try block within a try block is known as nested try block in java. Why use
nested try block
• Sometimes a situation may arise where a part of a block may cause one error and
the entire block itself may cause another error. In such cases, exception handlers
have to be nested.
• Java finally block
• Java finally block is a block that is used to execute important code such as closing
connection, stream etc.
• Java finally block is always executed whether exception is handled or not.
• Java finally block follows try or catch block.
Java throw keyword

• The Java throw keyword is used to explicitly throw an exception.


• We can throw either checked or uncheked exception in java by throw
keyword. The throw keyword is mainly used to throw custom exception. We
will see custom exceptions later.
• The syntax of java throw keyword is given below.
• Java Exception propagation
• An exception is first thrown from the top of the stack and if it is not caught,
it drops down the call stack to the previous method,If not caught there, the
exception again drops down to the previous method, and so on until they
are caught or until they reach the very bottom of the call stack.This is called
exception propagation.
Java throws keyword

• The Java throws keyword is used to declare an exception. It gives an information


to the programmer that there may occur an exception so it is better for the
programmer to provide the exception handling code so that normal flow can be
maintained.
• Exception Handling is mainly used to handle the checked exceptions. If there
occurs any unchecked exception such as NullPointerException, it is programmers
fault that he is not performing check up before the code being used.
No. throw throws

1) Java throw keyword is used to explicitly throw Java throws keyword is used to declare an
an exception. exception.

2) Checked exception cannot be propagated Checked exception can be propagated with


using throw only. throws.

3) Throw is followed by an instance. Throws is followed by class.

4) Throw is used within the method. Throws is used with the method signature.

5) You cannot throw multiple exceptions. You can declare multiple exceptions e.g.
public void method()throws
IOException,SQLException.
Collections in Java

• The Collection in Java is a framework that provides an architecture to store


and manipulate the group of objects.
• Java Collections can achieve all the operations that you perform on a data
such as searching, sorting, insertion, manipulation, and deletion.
• Java Collection means a single unit of objects. Java Collection framework
provides many interfaces (Set, List, Queue, Deque) and classes (ArrayList,
Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).
• What is Collection in Java
• A Collection represents a single unit of objects, i.e., a group.
What is a framework in Java
• It provides readymade architecture.
• It represents a set of classes and interfaces.
• It is optional.
• What is Collection framework
• The Collection framework represents a unified architecture for storing and
manipulating a group of objects. It has:
• Interfaces and its implementations, i.e., classes
• Algorithm
Iterator interface

• Iterator interface provides the facility of iterating the elements in a


forward direction only.
No. Method Description

1 public boolean hasNext() It returns true if the iterator has


more elements otherwise it
returns false.

2 public Object next() It returns the element and moves


the cursor pointer to the next
element.

3 public void remove() It removes the last elements


returned by the iterator. It is less
used.
Collection Interface
• The Collection interface is the interface which is implemented by all the classes in
the collection framework. It declares the methods that every collection will have.
In other words, we can say that the Collection interface builds the foundation on
which the collection framework depends.
• Some of the methods of Collection interface are Boolean add ( Object obj),
Boolean addAll ( Collection c), void clear(), etc. which are implemented by all the
subclasses of Collection interface.
• List Interface
• List interface is the child interface of Collection interface. It inhibits a list type data
structure in which we can store the ordered collection of objects. It can have
duplicate values.
• List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.
• To instantiate the List interface, we must use :
ArrayList
• The ArrayList class implements the List interface. It uses a dynamic array to store the
duplicate element of different data types. The ArrayList class maintains the insertion
order and is non-synchronized. The elements stored in the ArrayList class can be
randomly accessed. Consider the following example.
• void add(int index, Object element)
• Inserts the specified element at the specified position index in this list. Throws
IndexOutOfBoundsException if the specified index is out of range (index < 0 || index
> size()).
• boolean add(Object o)
• Appends the specified element to the end of this list.
• boolean addAll(Collection c)
• Appends all of the elements in the specified collection to the end of this list, in the
order that they are returned by the specified collection's iterator. Throws
• boolean addAll(int index, Collection c)
• Inserts all of the elements in the specified collection into this list, starting at the
specified position. Throws NullPointerException if the specified collection is null.
• void clear()
• Removes all of the elements from this list.
• Object clone()
• Returns a shallow copy of this ArrayList.
• LinkedList Class
• The LinkedList class extends AbstractSequentialList and implements the List
interface. It provides a linked-list data structure.
• LinkedList( )
• This constructor builds an empty linked list.
• LinkedList(Collection c)
• This constructor builds a linked list that is initialized with the elements of the collection c.
• void add(int index, Object element)
• Inserts the specified element at the specified position index in this list. Throws
IndexOutOfBoundsException if the specified index is out of range (index < 0 || index > size()).
• boolean add(Object o)
• Appends the specified element to the end of this list.
• boolean addAll(Collection c)
• Appends all of the elements in the specified collection to the end of this list, in the order that they
are returned by the specified collection's iterator. Throws NullPointerException if the specified
HashSet
• HashSet extends AbstractSet and implements the Set interface. It creates a
collection that uses a hash table for storage.
• A hash table stores information by using a mechanism called hashing. In hashing,
the informational content of a key is used to determine a unique value, called its
hash code.
• The hash code is then used as the index at which the data associated with the key
is stored. The transformation of the key into its hash code is performed
automatically.
• boolean add(Object o)
• Adds the specified element to this set if it is not already present.
• void clear()
• Removes all of the elements from this set.
TreeSet
• TreeSet provides an implementation of the Set interface that uses a tree for storage.
Objects are stored in a sorted and ascending order.
• Access and retrieval times are quite fast, which makes TreeSet an excellent choice when
storing large amounts of sorted information that must be found quickly.
• TreeSet( )
• This constructor constructs an empty tree set that will be sorted in an ascending order
according to the natural order of its elements.
• TreeSet(Collection c)
• This constructor builds a tree set that contains the elements of the collection c.
• TreeSet(Comparator comp)
• This constructor constructs an empty tree set that will be sorted according to the given
comparator.
• TreeSet(SortedSet ss)
• void add(Object o)
• Adds the specified element to this set if it is not already present.
• boolean addAll(Collection c)
• Adds all of the elements in the specified collection to this set.
• void clear()
• Removes all of the elements from this set.
• Object clone()
• Returns a shallow copy of this TreeSet instance.
• LinkedHashSet
• This class extends HashSet, but adds no members of its own.
• LinkedHashSet maintains a linked list of the entries in the set, in the order in which they were inserted.
This allows insertion-order iteration over the set.
• That is, when cycling through a LinkedHashSet using an iterator, the elements will be returned in the
order in which they were inserted.
• The hash code is then used as the index at which the data associated with the key is stored. The
• HashSet( )
• This constructor constructs a default HashSet.
• HashSet(Collection c)
• This constructor initializes the hash set by using the elements of the collection c.
• LinkedHashSet(int capacity)
• This constructor initializes the capacity of the linkedhashset to the given integer
value capacity. The capacity grows automatically as elements are added to the
HashSet.
• LinkedHashSet(int capacity, float fillRatio)
• This constructor initializes both the capacity and the fill ratio (also called load
capacity) of the hash set from its arguments.
Vector
• Vector implements a dynamic array. It is similar to ArrayList, but with two differences −
• Vector is synchronized.
• Vector contains many legacy methods that are not part of the collections framework.
• Vector proves to be very useful if you don't know the size of the array in advance or you just need one that
can change sizes over the lifetime of a program.
• Vector( )
• This constructor creates a default vector, which has an initial size of 10.
• Vector(int size)
• This constructor accepts an argument that equals to the required size, and creates a vector whose initial
capacity is specified by size.
• Vector(int size, int incr)
• This constructor creates a vector whose initial capacity is specified by size and whose increment is
specified by incr. The increment specifies the number of elements to allocate each time that a vector is
resized upward
• . Vector(Collection c)
Files and I/O

• The java.io package contains nearly every class you might ever need to perform
input and output (I/O) in Java. All these streams represent an input source and an
output destination. The stream in the java.io package supports many data such as
primitives, object, localized characters, etc.
• Stream
• A stream can be defined as a sequence of data. There are two kinds of Streams −
• InPutStream − The InputStream is used to read data from a source.
• OutPutStream − The OutputStream is used for writing data to a destination.

source program Destinatio


n
Byte Streams

• Java byte streams are used to perform input and output of 8-bit bytes. Though
there are many classes related to byte streams but the most frequently used
classes are, FileInputStream and FileOutputStream. Following is an example
which makes use of these two classes to copy an input file into an output file −
• Character Streams
• Java Byte streams are used to perform input and output of 8-bit bytes, whereas
Java Character streams are used to perform input and output for 16-bit unicode.
Though there are many classes related to character streams but the most
frequently used classes are, FileReader and FileWriter. Though internally
FileReader uses FileInputStream and FileWriter uses FileOutputStream but here
the major difference is that FileReader reads two bytes at a time and FileWriter
writes two bytes at a time.
Standard Streams
• All the programming languages provide support for standard I/O where the user's
program can take input from a keyboard and then produce an output on the
computer screen. If you are aware of C or C++ programming languages, then you
must be aware of three standard devices STDIN, STDOUT and STDERR. Similarly,
Java provides the following three standard streams −
• Standard Input − This is used to feed the data to user's program and usually a
keyboard is used as standard input stream and represented as System.in.
• Standard Output − This is used to output the data produced by the user's
program and usually a computer screen is used for standard output stream and
represented as System.out.
• Standard Error − This is used to output the error data produced by the user's
program and usually a computer screen is used for standard error stream and
FileInputStream

• This stream is used for reading data from the files. Objects can be created
using the keyword new and there are several types of constructors
available.
• Following constructor takes a file name as a string to create an input stream
object to read the file −
• File f = new File("C:/java/hello");
• InputStream f = new FileInputStream(f);
• Once you have InputStream object in hand, then there is a list of helper
methods which can be used to read to stream or to do other operations on
the stream.
• This method closes the file output stream. Releases any system resources associated with the file.
Throws an IOException.
• protected void finalize()throws IOException {}
• This method cleans up the connection to the file. Ensures that the close method of this file output
stream is called when there are no more references to this stream. Throws an IOException.
• public int read(int r)throws IOException{}
• This method reads the specified byte of data from the InputStream. Returns an int. Returns the
next byte of data and -1 will be returned if it's the end of the file.
• public int read(byte[] r) throws IOException{}
• This method reads r.length bytes from the input stream into an array. Returns the total number of
bytes read. If it is the end of the file, -1 will be returned.
• public int available() throws IOException{}
• Gives the number of bytes that can be read from this file input stream. Returns an int.
FileOutputStream

• FileOutputStream is used to create a file and write data into it. The stream would
create a file, if it doesn't already exist, before opening it for output.
• Here are two constructors which can be used to create a FileOutputStream
object.
• Following constructor takes a file name as a string to create an input stream
object to write the file −
• OutputStream f = new FileOutputStream("C:/java/hello")
• File f = new File("C:/java/hello");
• OutputStream f = new FileOutputStream(f);
• public void close() throws IOException{}
• This method closes the file output stream. Releases any system resources
associated with the file. Throws an IOException.
• protected void finalize()throws IOException {
• This method cleans up the connection to the file. Ensures that the close method
of this file output stream is called when there are no more references to this
stream. Throws an IOException.
• public void write(int w)throws IOException{}
• This methods writes the specified byte to the output stream.
• public void write(byte[] w)
FileReader Class

• FileReader(File file)
• This constructor creates a new FileReader, given the File to read from.
• FileReader(FileDescriptor fd)
• This constructor creates a new FileReader, given the FileDescriptor to read from.

• FileReader(String filename)
• This constructor creates a new FileReader, given the name of the file to read
from.
• This class inherits from the OutputStreamWriter class. The class is used for
writing streams of characters.
Multithreading

• Java is a multi-threaded programming language which means we can develop


multi-threaded program using Java. A multi-threaded program contains two or
more parts that can run concurrently and each part can handle a different task at
the same time making optimal use of the available resources specially when your
computer has multiple CPUs.
• By definition, multitasking is when multiple processes share common processing
resources such as a CPU. Multi-threading extends the idea of multitasking into
applications where you can subdivide specific operations within a single
application into individual threads. Each of the threads can run in parallel. The OS
divides processing time not only among different applications, but also among
each thread within an application.
• Multi-threading enables you to write in a way where multiple activities can
FileWriter
• FileWriter(File file)
• This constructor creates a FileWriter object given a File object.
• FileWriter(File file, boolean append)
• This constructor creates a FileWriter object given a File object with a boolean indicating
whether or not to append the data written.
• FileWriter(FileDescriptor fd)
• This constructor creates a FileWriter object associated with the given file descripto
• FileWriter(String fileName)
• This constructor creates a FileWriter object, given a file name
• FileWriter(String fileName, boolean append)
• This constructor creates a FileWriter object given a file name with a boolean indicating
whether or not to append the data written.
Life Cycle of a Thread

• A thread goes through various stages in its life cycle. For example, a thread is
born, started, runs, and then dies. The following diagram shows the complete life
cycle of a thread.
Runnable

New Running

Dead Waiting
• New − A new thread begins its life cycle in the new state. It remains in this state until
the program starts the thread. It is also referred to as a born thread.
• Runnable − After a newly born thread is started, the thread becomes runnable. A
thread in this state is considered to be executing its task.
• Waiting − Sometimes, a thread transitions to the waiting state while the thread
waits for another thread to perform a task. A thread transitions back to the runnable
state only when another thread signals the waiting thread to continue executing.
• Timed Waiting − A runnable thread can enter the timed waiting state for a specified
interval of time. A thread in this state transitions back to the runnable state when
that time interval expires or when the event it is waiting for occurs.
• Terminated (Dead) − A runnable thread enters the terminated state when it
completes its task or otherwise terminates.
Thread Priorities

• Every Java thread has a priority that helps the operating system determine the
order in which threads are scheduled.
• Java thread priorities are in the range between MIN_PRIORITY (a constant of 1)
and MAX_PRIORITY (a constant of 10). By default, every thread is given priority
NORM_PRIORITY (a constant of 5).
• Threads with higher priority are more important to a program and should be
allocated processor time before lower-priority threads. However, thread priorities
cannot guarantee the order in which threads execute and are very much platform
dependent.
Create a Thread by Implementing a Runnable
Interface

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

• The sleep() method of Thread class is used to sleep a thread for the
specified amount of time.
• Syntax of sleep() method in java
• The Thread class provides two methods for sleeping a thread:
• public static void sleep(long miliseconds)throws InterruptedException
• public static void sleep(long miliseconds, int nanos)throws
InterruptedException
• Thread(Runnable threadObj, String threadName);
• Where, threadObj is an instance of a class that implements
the Runnableinterface and threadName is the name given to the new
thread.
• Step 3
• Once a Thread object is created, you can start it by
calling start() method, which executes a call to run( ) method.
Following is a simple syntax of start() method −
• void start();
Create a Thread by Extending a
Thread Class
• The second way to create a thread is to create a new class that
extends Thread class using the following two simple steps. This approach
provides more flexibility in handling multiple threads created using available
methods in Thread class.
• Step 1
• You will need to override run( ) method available in Thread class. This method
provides an entry point for the thread and you will put your complete business
logic inside this method. Following is a simple syntax of run() method
• Step 2
• Once Thread object is created, you can start it by calling start() method, which
executes a call to run( ) method. Following is a simple syntax of start() method −
Thread Methods

• public void start()


• Starts the thread in a separate path of execution, then invokes the run() method on this Thread
object.
• public void run()
• If this Thread object was instantiated using a separate Runnable target, the run() method is invoked
on that Runnable object.
• public final void setName(String name)
• Changes the name of the Thread object. There is also a getName() method for retrieving the name.
• public final void setPriority(int priority)
• Sets the priority of this Thread object. The possible values are between 1 and 10.
• public final void join(long millisec)
• The current thread invokes this method on a second thread, causing the current thread to block until
the second thread terminates or the specified number of milliseconds passes.
• public final boolean isAlive()
• Returns true if the thread is alive, which is any time after the thread has been started
but before it runs to completion.
• public static void yield()
• Causes the currently running thread to yield to any other threads of the same priority
that are waiting to be scheduled.
• public static void sleep(long millisec)
• Causes the currently running thread to block for at least the specified number of
milliseconds.
• public static Thread currentThread()
• Returns a reference to the currently running thread, which is the thread that invokes
this method.
Thread Scheduler in Java

• Thread scheduler in java is the part of the JVM that decides which thread should run.
• There is no guarantee that which runnable thread will be chosen to run by the thread
scheduler.
• Only one thread at a time can run in a single process.
• The thread scheduler mainly uses preemptive or time slicing scheduling to schedule the
threads.
• Sleep method in java
• The sleep() method of Thread class is used to sleep a thread for the specified amount of time.
• Syntax of sleep() method in java
• The Thread class provides two methods for sleeping a thread:
• public static void sleep(long miliseconds)throws InterruptedException
• public static void sleep(long miliseconds, int nanos)throws InterruptedException
ThreadGroup in Java

• Java provides a convenient way to group multiple threads in a single


object. In such way, we can suspend, resume or interrupt group of
threads by a single method call.
• A ThreadGroup represents a set of threads. A thread group can also
include the other thread group. The thread group creates a tree in
which every thread group except the initial thread group has a parent.
• A thread is allowed to access information about its own thread group,
but it cannot access the information about its thread group's parent
thread group or any other thread groups.
Daemon Thread in Java

• Daemon thread in java is a service provider thread that provides services to the user
thread. Its life depend on the mercy of user threads i.e. when all the user threads
dies, JVM terminates this thread automatically.
• There are many java daemon threads running automatically e.g. gc, finalizer etc.
• You can see all the detail by typing the jconsole in the command prompt. The
jconsole tool provides information about the loaded classes, memory usage, running
threads etc.
• Points to remember for Daemon Thread in Java
• It provides services to user threads for background supporting tasks. It has no role in
life than to serve user threads.
• Its life depends on user threads.
Java Thread Pool

• Java Thread pool represents a group of worker threads that are waiting for the job and reuse many times.
• In case of thread pool, a group of fixed size threads are created. A thread from the thread pool is pulled out and
assigned a job by the service provider. After completion of the job, thread is contained in the thread pool again.
• Thread Synchronization
• When we start two or more threads within a program, there may be a situation when multiple threads try to
access the same resource and finally they can produce unforeseen result due to concurrency issues. For
example, if multiple threads try to write within a same file then they may corrupt the data because one of the
threads can override data or while one thread is opening the same file at the same time another thread might
be closing the same file.
• So there is a need to synchronize the action of multiple threads and make sure that only one thread can access
the resource at a given point in time. This is implemented using a concept called monitors. Each object in Java is
associated with a monitor, which a thread can lock or unlock. Only one thread at a time may hold a lock on a
monitor.
• Java programming language provides a very handy way of creating threads and synchronizing their task by
using synchronized blocks. You keep shared resources within this block. Following is the general form of the
synchronized statement −
Java Applet

• Applet is a special type of program that is embedded in the webpage 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 plateforms, including Linux, Windows, Mac Os etc.
• Lifecycle methods for Applet:
• For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle methods of applet.
• public void init(): is used to initialized the Applet. It is invoked only once.
• public void start(): is invoked after the init() method or browser is maximized. It is used to start the Applet.
• public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is minimized.
• public void destroy(): is used to destroy the Applet. It is invoked only once.
•.
start

init destory

stop
java.awt.Component class

• The Component class provides 1 life cycle method of applet.


• public void paint(Graphics g): is used to paint the Applet. It provides Graphics
class object that can be used for drawing oval, rectangle, arc etc.
• How to run an Applet?
• There are two ways to run an applet
• By html file.
• By appletViewer tool (for testing purpose).
• To execute the applet by appletviewer tool, write in command prompt:
• c:\>javac First.java
• c:\>appletviewer myapplet.html
Displaying Graphics in Applet
• public abstract void drawString(String str, int x, int y): is used to draw the specified string.
• public void drawRect(int x, int y, int width, int height): draws a rectangle with the specified width and height.
• public abstract void fillRect(int x, int y, int width, int height): is used to fill rectangle with the default color and
specified width and height.
• public abstract void drawOval(int x, int y, int width, int height): is used to draw oval with the specified width and
height.
• public abstract void fillOval(int x, int y, int width, int height): is used to fill oval with the default color and specified
width and height.
• public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line between the points(x1, y1) and (x2, y2).
• public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer): is used draw the specified
image.
• public abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle): is used draw a circular or
elliptical arc.
• public abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle): is used to fill a circular or
elliptical arc.
• public abstract void setColor(Color c): is used to set the graphics current color to the specified color.
Displaying Image in Applet

• Applet is mostly used in games and animation. For this purpose image is
required to be displayed. The java.awt.Graphics class provide a method
drawImage() to display the image.
• Syntax of drawImage() method:
• public abstract boolean drawImage(Image img, int x, int y,
ImageObserver observer): is used draw the specified image.
• Other required methods of Applet class to display image:
• public URL getDocumentBase(): is used to return the URL of the
document in which applet is embedded.
• public URL getCodeBase(): is used to return the base URL.
Animation in Applet

• Applet is mostly used in games and animation. For this purpose image
is required to be moved.
• EventHandling in Applet
• As we perform event handling in AWT or Swing, we can perform it in
applet also. Let's see the simple example of event handling in applet
that prints a message by click on the button.
Event Classes Description Listener Interface
ActionEvent generated when button is pressed, ActionListener
menu-item is selected, list-item is
double clicked
MouseEvent generated when mouse is dragged, MouseListener
moved,clicked,pressed or released
and also when it enters or exit a
component
KeyEvent generated when input is received KeyListener
from keyboard
ItemEvent generated when check-box or list item ItemListener
is clicked
TextEvent generated when value of textarea or TextListener
textfield is changed
MouseWheelEvent generated when mouse wheel is MouseWheelListener
moved
WindowEvent generated when window is activated, WindowListener
deactivated, deiconified, iconified,
ComponentEvent generated when component is hidden, ComponentEventListener
moved, resized or set visible

ContainerEvent generated when component is added or ContainerListener


removed from container

AdjustmentEvent generated when scroll bar is manipulated AdjustmentListener

FocusEvent generated when component gains or FocusListener


loses keyboard focus
Parameter in Applet

• We can get any information from the HTML file as a parameter. For
this purpose, Applet class provides a method named getParameter().
Syntax:
• public String getParameter(String parameterName)
Java AWT Tutorial

• Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based


applications in java.
• Java AWT components are platform-dependent i.e. components are displayed
according to the view of operating system. AWT is heavyweight i.e. its
components are using the resources of OS.
• The java.awt package provides classes for AWT api such as TextField, Label,
TextArea, RadioButton, CheckBox, Choice, List etc.
• Container
• The Container is a component in AWT that can contain another components like
buttons, textfields, labels etc. The classes that extends Container class are known
as container such as Frame, Dialog and Panel.
• Window
• The window is the container that have no borders and menu bars. You must
use frame, dialog or another window for creating a window.
• Panel
• The Panel is the container that doesn't contain title bar and menu bars. It can
have other components like button, textfield etc.
• Frame
• The Frame is the container that contain title bar and can have menu bars. It
can have other components like button, textfield etc.
Useful Methods of Component class
public void add(Component c) inserts a component on this component.

public void setSize(int width,int height) sets the size (width and height) of the component.

public void setLayout(LayoutManager m) defines the layout manager for the component.

public void setVisible(boolean status) changes the visibility of the component, by default
false.
• To create simple awt example, you need a frame. There are two ways to create a
frame in AWT.
• By extending Frame class (inheritance)
• By creating the object of Frame class (association)
• Java AWT Label
• The object of Label class is a component for placing text in a container. It is used
to display a single line of read only text. The text can be changed by an
application but a user cannot edit it directly.
• Java AWT TextField
• The object of a TextField class is a text component that allows the editing of a
single line text. It inherits TextComponent class.
TextArea

• The TextArea control in AWT provide us multiline editor area. The user can type here
as much as he wants. When the text in the text area become larger than the viewable
area the scroll bar is automatically appears which help us to scroll the text up & down
and right & left.
• TextArea()
• Constructs a new text area with the empty string as text.
• TextArea(int rows, int columns)
• Constructs a new text area with the specified number of rows and columns and the
empty string as text.
• Choice
• Choice control is used to show pop up menu of choices. Selected choice is shown on
the top of the menu.
• void add(String item)
• Adds an item to this Choice menu.
• void addItem(String item)
• Obsolete as of Java 2 platform v1.1.
• Canvas
• Canvas control represents a rectangular area where application can draw
something or can receive inputs created by user.
• CheckBox Class
• Checkbox control is used to turn an option on(true) or off(false). There is label for
each checkbox representing what the checkbox does.The state of a checkbox can
be changed by clicking on it.
CheckBoxGroup Class

• The CheckboxGroup class is used to group the set of checkbox.


• List
• The List represents a list of text items. The list can be configured that
user can choose either one item or multiple items.
• Scrollbar Class
Canvas Class

• Introduction
• Canvas control represents a rectangular area where application can draw
something or can receive inputs created by user.
• Image Class
• Image control is superclass for all image classes representing graphical images.
• Scrollbar
• Scrollbar control represents a scroll bar component in order to enable user to
select from range of values.
• Dialog
• Dialog control represents a top-level window with a title and a border used to
take some form of input from the user.
Java LayoutManagers

• BorderLayout (LayoutManagers)
• The BorderLayout is used to arrange the components in five regions: north,
south, east, west and center. Each region (area) may contain one component
only. It is the default layout of frame or window. The BorderLayout provides
five constants for each region
• Java FlowLayout
• The FlowLayout is used to arrange the components in a line, one after
another (in a flow). It is the default layout of applet or panel
• Java GridLayout
• The GridLayout is used to arrange the components in rectangular grid. One
component is displayed in each rectangle.
Java CardLayout

• The CardLayout class manages the components in such a manner that only one
component is visible at a time. It treats each component as a card that is why it is
known as CardLayout.
• Java GridBagLayout
• The Java GridBagLayout class is used to align components vertically, horizontally
or along their baseline.
• The components may not be of same size. Each GridBagLayout object maintains a
dynamic, rectangular grid of cells. Each component occupies one or more cells
known as its display area. Each component associates an instance of
GridBagConstraints. With the help of constraints object we arrange component's
display area on the grid. The GridBagLayout manages each component's minimum
and preferred sizes in order to determine component's size.
SWing
• Java Swing tutorial is a part of Java Foundation Classes (JFC) that
is used to create window-based applications. It is built on the top of
AWT (Abstract Windowing Toolkit) API and entirely written in java.
• Unlike AWT, Java Swing provides platform-independent and
lightweight components.
• The javax.swing package provides classes for java swing API such as
JButton, JTextField, JTextArea, JRadioButton, JCheckbox, JMenu,
JColorChooser etc.
Difference between AWT and Swing
No. Java AWT Java Swing
1) AWT components are platform- Java swing components are platform-
dependent. independent.

2) AWT components are heavyweight. Swing components are lightweight.

3) AWT doesn't support pluggable Swing supports pluggable look and


look and feel. feel.
4) AWT provides less components than Swing provides more powerful
Swing. componentssuch as tables, lists,
scrollpanes, colorchooser, tabbedpane
etc.

5) AWT doesn't follows MVC(Model Swing follows MVC.


View Controller) where model
represents data, view represents
presentation and controller acts as an
interface between model and view.
What is JFC

• The Java Foundation Classes (JFC) are a set of GUI components which
simplify the development of desktop applications.
• Java JButton
• The JButton class is used to create a labeled button that has platform
independent implementation. The application result in some action
when the button is pushed. It inherits AbstractButton class.
• There are two types of the applet -
• Applets based on the AWT(Abstract Window Toolkit) package by
extending its Applet class.
• Applets based on the Swing package by extending its JApplet class.
• Exceptions are events that occur during the execution of programs
that disrupt the normal flow of instructions (e.g. divide by zero, array
access out of bound, etc.). In Java, an exception is an object that
wraps an error event that occurred within a method and contains:
Information about the error including its type.
• A Collection is a group of individual objects represented as a single
unit. Java provides Collection Framework which defines several
classes and interfaces to ... represent a group of objects as a single
unit.
HashMap Hashtable

1) HashMap is non synchronized. It is not-thread safe and can't be shared between many Hashtable is synchronized. It is thread-safe and can be shared with many threads.
threads without proper synchronization code.

2) HashMap allows one null key and multiple null values. Hashtable doesn't allow any null key or value.

3) HashMap is a new class introduced in JDK 1.2. Hashtable is a legacy class.

4) HashMap is fast. Hashtable is slow.

5) We can make the HashMap as synchronized by calling this code Hashtable is internally synchronized and can't be unsynchronized.
Map m = Collections.synchronizedMap(hashMap);

6) HashMap is traversed by Iterator. Hashtable is traversed by Enumerator and Iterator.

7) Iterator in HashMap is fail-fast. Enumerator in Hashtable is not fail-fast.

8) HashMap inherits AbstractMap class. Hashtable inherits Dictionary class.


• Wrapper classes are used to convert any data type into an object. The primitive data types are not objects;
they do not belong to any class; they are defined in the language itself. Sometimes, it is required to convert
data types into objects in Java language
• JVM (Java Virtual Machine) Architecture
• Java Virtual Machine
• Internal Architecture of JVM
• JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in
which java bytecode can be executed.
• JVMs are available for many hardware and software platforms (i.e. JVM is platform dependent).
• What is JVM
• It is:
• A specification where working of Java Virtual Machine is specified. But implementation provider is
independent to choose the algorithm. Its implementation has been provided by Oracle and other companies.
• An implementation Its implementation is known as JRE (Java Runtime Environment).
• Runtime Instance Whenever you write java command on the command prompt to run the java class, an
• What it does
• The JVM performs following operation:
• Loads code
• Verifies code
• Executes code
• Provides runtime environment
• Instance variable in Java is used by Objects to store their
states. Variables which are defined without the STATIC keyword and are
Outside any method declaration are Object-specific and are known as instance
variables. They are called so because their values are instance specific and are
not shared among instances
static The member belongs to the class, not to objects of that class.

final Variable values can't be changed once assigned, methods can't be


overriden, classes can't be inherited.

abstract If applied to a method - has to be implemented in a subclass, if applied


to a class - contains abstract methods

synchronized Controls thread access to a block/method.

volatile The variable value is always read from the main memory, not from a
specific thread's memory.

transient The member is skipped when serializing an object.


• Ex1.java
• A java package is a group of similar types of classes, interfaces and sub-packages.
• Package in java can be categorized in two form, built-in package and user-defined package

• //save as Simple.java
• package mypack;
• public class Simple{
• public static void main(String args[]){
• System.out.println("Welcome to package");
• }
• }
• How to compile java package
• If you are not using any IDE, you need to follow the syntax given below:
• java mypack.Simple]
• The super keyword in java is a reference variable that is used to refer
parent class objects. The keyword “super” came into the picture with
the concept of Inheritance. It is majorly used in the following
contexts:
• 2. Use of super with methods: This is used when we want to call
parent class method. So whenever a parent and child class have same
named methods then to resolve ambiguity we use super keyword.
This code snippet helps to understand the said usage of super
keyword.
• class Person
• {
• void message()
• {
• System.out.println("This is person class");
• }
• }

• /* Subclass Student */
• class Student extends Person
• {
• void message()
• {
• System.out.println("This is student class");
• void display()
• // will invoke or call current class message() method
• message();

• // will invoke or call parent class message() method
• super.message();
• }
• }
• /* Driver program to test */
• class Test
• {
• public static void main(String args[])
• {
• Student s = new Student();

• // calling display() of Student
• s.display();
• Exception handling is one of the most important feature of java
programming that allows us to handle the runtime errors caused by
exceptions. In this guide, we will learn what is an exception, types of
it, exception classes and how to handle exceptions in java with
examples.
• Exception Handling
• If an exception occurs, which has not been handled by programmer
then program execution gets terminated and a system generated
error message is shown to the user. For example look at the system
generated exception below:
• public class JavaExceptionExample{
• public static void main(String args[]){
• try{
• //code that may raise exception
• int data=100/0;
• }catch(ArithmeticException e){System.out.println(e);}
• //rest code of the program
• System.out.println("rest of the code...");
• }
• }
• public class FileCopyExample {

• public static void main(String[] args) {

• try {
• FileReader fr = new FileReader("input.txt");
• BufferedReader br = new BufferedReader(fr);
• FileWriter fw = new FileWriter("output.txt", true);
• String s;

• while ((s = br.readLine()) != null) { // read a line


• fw.write(s); // write to output file
• fw.flush();
• }
• br.close();
• fw.close();
• System.out.println("file copied");
• } catch (IOException e) {
• // TODO Auto-generated catch block
• e.printStackTrace();
• }
• }
• Slip15.java
• The Adapter classes are an abstract class for receiving various events and the methods in these classes are
empty.
• These classes exist as a convenience for creating the listener objects.
• The Java provides a special feature called as an adapter class that can simplify the creation of the event
handlers in certain situations.
• An adapter class provides empty implementation of all the methods in an event listener interface that is this
class itself write the definition for methods which are already present in a particular event listener interface and
However these definitions does not affect the program flow or meaning at all.
• The Adapter classes are very useful when we have to receive and process only some of the events that are
already handled by a particular event listener interface.
• We can define a new class which can act as an event listener by extending one of the adapter classes &
implementing only those events in which we are interested.
• Example- Suppose that we want to use the MouseClicked event or method from MouseListener and if we do
not use adapter class then unnecessarily we have to define all the other methods from MouseListener as
MouseReleased, MousePressed etc.
• Garbage Collector is a program that manages memory automatically
wherein de-allocation of objects is handled by Java rather than the
programmer. In the Java programming language, dynamic allocation
of objects is achieved using the new operator. An object once created
uses some memory and the memory remains allocated till there are
references for the use of the object.
• When there are no references to an object, it is assumed to be no
longer needed, and the memory, occupied by the object can be
reclaimed. There is no explicit need to destroy an object as Java
handles the de-allocation automatically.
• Inner class in java
• Inner class means one class which is a member of another class. There
are basically four types of inner classes in java.
• 1) Nested Inner class
2) Method Local inner classes
3) Anonymous inner classes
4) Static nested classes
• Nested Inner class can access any private instance variable of outer
class. Like any other instance variable, we can have access modifier
private, protected, public and default modifier.
Like class, interface can also be nested and can have access specifiers.
• class Outer {
• // Simple nested inner class
• class Inner {
• public void show() {
• System.out.println("In a nested class method");
• }
• }
• }
• class Main {
• public static void main(String[] args) {
• Outer.Inner in = new Outer().new Inner();
• in.show();
• }
• }
• When a variable is declared with final keyword, its value can’t be modified, essentially, a
constant. This also means that you must initialize a final variable. If the final variable is a
reference, this means that the variable cannot be re-bound to reference another object,
but internal state of the object pointed by that reference variable
• // a final variable
• final int THRESHOLD = 5;
• // a blank final variable
• final int THRESHOLD;
• // a final static variable PI
• static final double PI = 3.141592653589793;
• // a blank final static variable
• static final double PI;
• An array is a group of like-typed variables that are referred to by a common name.Arrays in
Java work differently than they do in C/C++. Following are some important point about
Java arrays.
• In Java all arrays are dynamically allocated.(discussed below)
• Since arrays are objects in Java, we can find their length using member length. This is
different from C/C++ where we find length using sizeof.
• A Java array variable can also be declared like other variables with [] after the data type.
• The variables in the array are ordered and each have an index beginning from 0.
• Java array can be also be used as a static field, a local variable or a method parameter.
• The size of an array must be specified by an int value and not long or short.
• The direct superclass of an array type is Object.
• Every array type implements the interfaces Cloneable and java.io.Serializable.
• 1) StringBuffer is present in Java and StringBuilder was added in Java 5.

2) Both StringBuffer and StringBuilder represents mutable String which means you can add/remove
characters, substring without creating new objects.

3) You can convert a StringBuffer into String by calling toString() method.

4) Both StringBuilder and StringBuffer doesn't override equals() and hashCode() method because
they are mutable and not intended to be used as a key in hash-based collection classes e.g.
HashMap, Hashtable, and HashSet.

5) StringBuffer is synchronized which means all method which modifies the internal data of
StringBuffer is synchronized e.g. append(), insert() and delete(). On contrary, StringBuilder is not
synchronized.

6) Because of synchronization StringBuffer is considered thread safe e.g. multiple threads can call
its method without compromising internal data structure but StringBuilder is not synchronized
hence not thread safe

Read more:
https://javarevisited.blogspot.com/2017/08/10-differences-between-stringbuffer-and-StringBuilde
r-in-java.html#ixzz64UWwkn23
• Ex2
An applet is a Java program that runs in a Web browser. An applet can be a fully functional Java application because
has the entire Java API at its disposal.
There are some important differences between an applet and a standalone Java application, including the following −
•An applet is a Java class that extends the java.applet.Applet class.
•A main() method is not invoked on an applet, and an applet class will not define main().
•Applets are designed to be embedded within an HTML page.
•When a user views an HTML page that contains an applet, the code for the applet is downloaded to the user's machine.
•A JVM is required to view an applet. The JVM can be either a plug-in of the Web browser or a separate runtime
environment.
• Life Cycle of an Applet
• Four methods in the Applet class gives you the framework on which you build any serious applet −
• init − This method is intended for whatever initialization is needed for your applet. It is called after
the param tags inside the applet tag have been processed.
• start − This method is automatically called after the browser calls the init method. It is also called
whenever the user returns to the page containing the applet after having gone off to other pages.
• stop − This method is automatically called when the user moves off the page on which the applet
sits. It can, therefore, be called repeatedly in the same applet.
• destroy − This method is only called when the browser shuts down normally. Because applets are
meant to live on an HTML page, you should not normally leave resources behind after a user
leaves the page that contains the applet.
• paint − Invoked immediately after the start() method, and also any time the applet needs to
repaint itself in the browser. The paint() method is actually inherited from the java.awt.
• Abstract class in Java
• A class which is declared with the abstract keyword is known as an abstract class in Java. It can have
abstract and non-abstract methods (method with the body).
• Before learning the Java abstract class, let's understand the abstraction in Java first.
• Abstraction is a process of hiding the implementation details and showing only functionality to the
user.
• Another way, it shows only essential things to the user and hides the internal details, for example,
sending SMS where you type the text and send the message. You 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.
• Abstract class in Java
• A class which is declared as abstract is known as an abstract class. It can have abstract and non-
abstract methods. It needs to be extended and its method implemented. It cannot be instantiated.
• Points to Remember
• An abstract class must be declared with an abstract keyword.
• It can have abstract and non-abstract methods.
• It cannot be instantiated.
• It can have constructors and static methods also.
• Abstract Method in Java
• A method which is declared as abstract and does not have implementation is known as an abstract
method.
• abstract class Bike{
• abstract void run();
• }
• class Honda4 extends Bike{
• void run(){System.out.println("running safely");}
• public static void main(String args[]){
• Bike obj = new Honda4();
• obj.run();
• }
• }
• An event in Java is an object that is created when something changes within a graphical user
interface. If a user clicks on a button, clicks on a combo box, or types characters into a text
field, etc., then an event triggers, creating the relevant event object. This behavior is part of
Java's Event Handling mechanism and is included in the Swing GUI library.
• How Events Work
• Event handling in Java is comprised of two key elements:
• The event source, which is an object that is created when an event occurs. Java provides
several types of these event sources, discussed in the section Types of Events below.
• The event listener, the object that "listens" for events and processes them when they occur.
• public void actionPerformed(ActionEvent e){
• tf.setText("Welcome");
• }
• ArrayList class extends AbstractList class and implements the List interface.
• ArrayList supports dynamic array that can grow as needed. ArrayList has three
constructors.
• ArrayList() //It creates an empty ArrayList
• ArrayList( Collection C ) //It creates an ArrayList that is initialized with elements of
the Collection C
• ArrayList( int capacity ) //It creates an ArrayList that has the specified initial capacity
• LinkedList class
• LinkedList class extends AbstractSequentialList and
implements List,Deque and Queue inteface.
• LinkedList has two constructors.
• LinkedList() //It creates an empty LinkedList
• LinkedList( Collection C ) //It creates a Lin
• final(lowercase) is a reserved keyword in java. We can’t use it as an identifier
as it is reserved. We can use this keyword with variables, methods and also
with classes. The final keyword in java has different meaning depending upon
it is applied to variable, class or method.
• final int b = 6;
• finally is also a reserved keyword in java i.e, we can’t use it as an identifier.
The finally keyword is used in association with a try/catch block and
guarantees that a section of code will be executed, even if an exception is
thrown. The finally block will be executed after the try and catch blocks, but
before control transfers back to its origin.
• final int b = 6;
• try {
• System.out.println("inside B");
• return;
• }
• finally
• {
• System.out.println("B's finally");
• }
• }
• finalize() method is a protected and non-static method of java.lang.Object
class. This method will be available in all objects you create in java. This
method is used to perform some final operations or clean up operations on
an object before it is removed from the memory.
4 method of file class
• boolean canExecute() : Tests whether the application can execute the file denoted by this
abstract pathname.
• boolean canRead() : Tests whether the application can read the file denoted by this abstract
pathname.
• boolean canWrite() : Tests whether the application can modify the file denoted by this abstract
pathname.
• int compareTo(File pathname) : Compares two abstract pathnames lexicographically.
• boolean createNewFile() : Atomically creates a new, empty file named by this abstract
pathname .
• static File createTempFile(String prefix, String suffix) : Creates an empty file in the default
temporary-file directory.
• boolean delete() : Deletes the file or directory denoted by this abstract pathname.
• boolean equals(Object obj) : Tests this abstract pathname for equality with the given object.
• There are two basic types of dialogs: modal and modeless. Modal dialogs block
input to other top-level windows. Modeless dialogs allow input to other windows.
An open file dialog is a good example of a modal dialog....
Message dialogs
• ERROR_MESSAGE.
• WARNING_MESSAGE.
• QUESTION_MESSAGE.
• INFORMATION_MESSAGE.
• option dialog
• The input dialog has an additional component for user input. This can be a text field
into which the user can type an arbitrary string, or a combo box from which the user
can select one item.
• he PLAIN_MESSAGE type has no icon. Each dialog type also has a method that lets
you supply your own icon instead. For each dialog type, you can specify a message.
This message can be a string, an icon, a user interface component, or any other
object. Here is how the message object is displayed:
• The showConfirmDialog and showOptionDialog return integers to indicate which button the user
chose. For the option dialog, this is simply the index of the chosen option or the value
CLOSED_OPTION if the user closed the dialog instead of choosing an option. For the confirmation
dialog, the return value can be one of the following:
• Difference Between Interface and Abstract Class
• Main difference is methods of a Java interface are implicitly abstract and cannot have
implementations. A Java abstract class can have instance methods that implements a default
behavior.
• Variables declared in a Java interface is by default final. An abstract class may contain non-
final variables.
• Members of a Java interface are public by default. A Java abstract class can have the usual flavors of
class members like private, protected, etc..
• Java interface should be implemented using keyword “implements”; A Java abstract class should be
extended using keyword “extends”.
• An interface can extend another Java interface only, an abstract class can extend another Java class
and implement multiple Java interfaces.
• A Java class can implement multiple interfaces but it can extend only one abstract class.
• Interface is absolutely abstract and cannot be instantiated; A Java abstract class also cannot be
instantiated, but can be invoked if a main() exists.
• Explain Java’s delegation event model
• The event model is based on the Event Source and Event Listeners. Event Listener
is an object that receives the messages / events. The Event Source is any object
which creates the message / event. The Event Delegation model is based on –
The Event Classes, The Event Listeners, Event Objects.

There are three participants in event delegation model in Java;

- Event Source – the class which broadcasts the events


- Event Listeners – the classes which receive notifications of events
- Event Object – the class object which describes the event.

An event occurs (like mouse click, key press, etc) which is followed by the event is
broadcasted by the event source by invoking an agreed method on all event
listeners. The event object is passed as argument to the agreed-upon method.
Later the event listeners respond as they fit, like submit a form, displaying a
message / alert etc.
• throw throws
• 1) Java throw keyword is used to explicitly throw an exception.
• Java throws keyword is used to declare an exception.
• 2) Checked exception cannot be propagated using throw only.
• Checked exception can be propagated with throws.
• 3) Throw is followed by an instance.
• Throws is followed by class.
• 4) Throw is used within the method.
• Throws is used with the method signature.
• 5) You cannot throw multiple exceptions.
• You can declare multiple exceptions e.g.
• public void method()throws IOException,SQLException

You might also like