0% found this document useful (0 votes)
11 views

Unit-Iv Oopc Using Java

Uploaded by

sdaya77777
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Unit-Iv Oopc Using Java

Uploaded by

sdaya77777
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

Packages in Java

 Package in Java is a mechanism to encapsulate a group of classes, sub


packages and interfaces.
 PACKAGE in Java is a collection of classes, sub-packages, and interfaces.
 It helps organize your classes into a folder structure and make it easy to
locate and use them. More importantly, it helps improve code reusability.
 Think of it as a folder in a file directory.
 Packages are used for:
 Preventing naming conflicts. For example there can be two classes with
name Employee in two packages, college.staff.cse.Employee and
college.staff.ee.Employee
 Making searching/locating and usage of classes, interfaces easier
 Providing controlled access: protected and default have package level access
control. A protected member is accessible by classes in the same package
and its subclasses. A default member (without any access specifier) is
accessible by classes in the same package only.
 Packages can be considered as data encapsulation (or data-hiding).
Types of packages in java
 Packages are mainly two types they are.
 1. Built -in Packages.
 2. User defined Packages.
1.Built-in Packages: These are also called as Predefined packages.
 1. Java Lang Package (java.lang.*)
 java.lang package is imported automatically, i.e. we can use the classes
of this package directly in our program. You do not need to import this
package
 This package contains important classes like String, StringBuilder, Math,
Integer, System, etc.
 2. Java Util Package (java.util.*)
 java.util package contains the collections framework,
 This package contains important classes like ArrayList, HashMap,
HashSet, etc.

 3. Java IO Package (java.io.*): java.io package provides serialization, system
input/output through data streams, and the file system.
This package contains important classes like BufferedReader, BufferedWriter, File,
InputStream, OutputStream, etc.
 4. Java Time Package (java.time.*)
java.time package provides the main API for times, dates, instants, and durations.
This package contains important classes like LocalDate, LocalTime,
LocalDateTime, ZonedDateTime, etc.
 5. Java SQL Package (java.sql.*)
java.sql package provides the API for accessing and processing the data stored in
a datasource.
This package contains important interfaces like Connection, PreparedStatement,
ResultSet, and classes like DriverManager, etc.
 6. Java Net Package (java.net.*)
 java.net package provides classes and interfaces for implementing networking
applications.

This package contains important classes like Socket, Proxy, Authenticator, URI,
URL, etc.
7. Javax Swing Package (javax.swing.*):
This package contains important classes like BoxLayout, ImageIcon, JButton, JCheckBox,
JComponent, JFrame, JLabel, JList, JPanel, etc.
 8. java.applet: Contains classes for creating Applets.(AppletViwer)
9. java.awt: Contain classes for implementing the components for graphical user
interfaces (like button , ;menus etc)
 User-defined packages
These are the packages that are defined by the user.
 Creating User defined Package:
 While creating a package, we should choose a name for the package and
include a package statement along with that name at the top of every source
file.
 The package statement should be the first line in the source file.
 Syntax:
 package <package-name>;
 Ex:
 package cse;
 In java, the accessibility of the members of a class or interface depends on its
access specifiers. The following table provides information about the visibility of
both data members and methods.

Compiling and executing the user defined
package java program
How to import Java Package
 To import java package into a class, we need to use
java import keyword which is used to access package and its
classes into the java program.
 Use import to access built-in and user-defined packages into
your java source file so that your class can refer to a class
that is in another package by directly using its name.
 There are 3 different ways to refer to any class that is
present in a different package:
1. without import the package
2. import package with specified class
3. import package with all classes
without import the package(fully specified name)
CommandLineArguments in java
 The command line argument is the argument that passed to a program during
runtime. It is the way to pass argument to the main method in Java.
 These arguments store into the String type args parameter which is main method
parameter.
 Java command-line argument is an argument i.e. passed at the time of running the
Java program.
 In Java, the command line arguments passed from the console can be received in
the Java program and they can be used as input.
 The users can pass the arguments during the execution bypassing the command-line
arguments inside the main() method.
 So, it provides a convenient way to check the behavior of the program for the
different values. You can pass N (1,2,3 and so on) numbers of arguments from the
command prompt.
 We need to pass the arguments as space-separated values. We can pass both strings
and primitive data types(int, double, float, char, etc) as command-line arguments.
These arguments convert into a string array and are provided to the main() function
as a string array argument.
 we were unable to run more than one task in parallel. It was a
drawback, and to remove that drawback, Thread Concept was
introduced.
 A Thread is a very light-weighted process, or we can say the
smallest part of the process that allows a program to operate
more efficiently by running multiple tasks simultaneously.
 The java programming language allows us to create a program
that contains one or more parts that can run simultaneously at
the same time.
 This type of program is known as a multithreading program.
 Each part of this program is called a thread.
 Every thread defines a separate path of execution in java.
 All the tasks are executed without affecting the main
program.
 Another benefit of using thread is that if a thread gets an exception or
an error at the time of its execution, it doesn't affect the execution of
the other threads.
 Multitasking:
 Multitasking is a process of performing multiple tasks simultaneously.
 We can understand it by computer system that perform multiple tasks
like: writing data to a file, playing music, downloading file from remote
server at the same time.
 Multitasking can be achieved either by using multiprocessing or
multithreading. Multitasking by using multiprocessing involves multiple
processes to execute multiple tasks simultaneously whereas
Multithreading involves multiple threads to executes multiple tasks.
 Process is heavy weight, takes more memory and occupy CPU
for longer time that may lead to performance issue.
 To overcome these issue process is broken into small unit of
independent sub-process.
 These sub-process are called threads that can perform
independent task efficiently.
Process-based multitasking Thread-based multitasking
It allows the computer to run two or more It allows the computer to run two or more
programs concurrently threads concurrently

In this process is the smallest unit. In this thread is the smallest unit.

Process is a larger unit. Thread is a part of process.

Process is heavy weight. Thread is light weight.

Process requires seperate address space for Threads share same address space.
each.

Process never gain access over idle time of Thread gain access over idle time of CPU.
CPU.

Inter process communication is expensive. Inter thread communication is not expensive.


Thread Life Cycle
 Like process, thread have its life cycle that includes various phases like: new,
running, terminated etc.
 A thread in Java at any point of time exists in any one of the following states.
 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.
1. New: In this phase, the thread is created using class “Thread class”.It
remains in this state till the program starts the thread. It is also
known as born thread.
2. Runnable: In this page, the instance of the thread is invoked with a
start method. The thread control is given to scheduler to finish the
execution. It depends on the scheduler, whether to run the thread.
3. Running: When the thread starts executing, then the state is
changed to “running” state. The scheduler selects one thread from
the thread pool, and it starts executing in the application.
4. Waiting: This is the state when a thread has to wait. As there
multiple threads are running in the application, there is a need for
synchronization between threads. Hence, one thread has to wait, till
the other thread gets executed. Therefore, this state is referred as
waiting state.
5. Dead: This is the state when the thread is terminated. The thread is
in running state and as soon as it completed processing it is in “dead
state”.
Sr.No. Method & Description

public void start()


1 Starts the thread in a separate path of execution,
then invokes the run() method on this Thread object.

public void run()


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


3 Changes the name of the Thread object. There is also
a getName() method for retrieving the name.

public final void setPriority(int priority)


4 Sets the priority of this Thread object. The possible
values are between 1 and 10.

public final void setDaemon(boolean on)


5 A parameter of true denotes this Thread as a daemon
thread.

public final void join(long millisec)


The current thread invokes this method on a second
6 thread, causing the current thread to block until the
second thread terminates or the specified number of
milliseconds passes.

public void interrupt()


7 Interrupts this thread, causing it to continue
execution if it was blocked for any reason.

public final boolean isAlive()


8 Returns true if the thread is alive, which is any time
after the thread has been started but before it runs
to completion.
Sr.No. Method & Description

public static void yield()


Causes the currently running thread to yield to
1
any other threads of the same priority that are
waiting to be scheduled.

public static void sleep(long millisec)


2 Causes the currently running thread to block for
at least the specified number of milliseconds.

public static boolean holdsLock(Object x)


3 Returns true if the current thread holds the lock
on the given Object.

public static Thread currentThread()


Returns a reference to the currently running
4
thread, which is the thread that invokes this
method.

public static void dumpStack()


Prints the stack trace for the currently running
5
thread, which is useful when debugging a
multithreaded application.
 There are two ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface.
 Thread class:
 Thread class provide constructors and methods to create and
perform operations on a thread. Thread class extends Object
class and implements Runnable interface.
 User defined thread class that extends Thread class and create
an instance of that class. The extending class must override
run() method which is the entry point of new thread.
1. class Multi extends Thread{
2. public void run(){
3. System.out.println("thread is running...");
4. }
5. public static void main(String args[]){
6. Multi t1=new Multi();
7. t1.start();
8. }
9. }
 0/p: thread is running
Implementing Runnable interface
 The java contains a built-in interface Runnable inside the java.lang package.
 The Runnable interface implemented by the Thread class that contains all
the methods that are related to the threads.
 To create a thread using Runnable interface, follow the step given
below.
• Step-1: Create a class that implements Runnable interface.
• Step-2: Override the run( ) method with the code that is to be executed by
the thread. The run( ) method must be public while overriding.
• Step-3: Create the object of the newly created class in the main( ) method.
• Step-4: Create the Thread class object by passing above created object as
parameter to the Thread class constructor.
• Step-5: Call the start( ) method on the Thread class object created in the
above step.
 Priority of a thread describes how early it gets execution and
selected by the thread scheduler.
 In Java, when we create a thread, always a priority is assigned to it.
 The priority is given by the JVM or by the programmer itself
explicitly.
 Each thread has a priority. Priorities are represented by a number
between 1 and 10. In most cases, the thread scheduler schedules the
threads according to their priority
 Priority 1 is considered as the lowest priority, and priority 10 is
considered as the highest priority.
 The thread with more priority allocates the processor first.
• The default priority is set to 5 as excepted.
• Minimum priority is set to 1.
• Maximum priority is set to 10.
 Here 3 constants are defined in it namely as follows:
1. public static int NORM_PRIORITY // 5
2. public static int MIN_PRIORITY // 1
3. public static int MAX_PRIORITY // 10
We will use currentThread() method to get the name of the
current thread.
1. User can also use setName() method if he/she wants to make
names of thread as per choice for understanding purposes.

2. getName() method will be used to get the name of the thread.

3. The accepted value of priority for a thread is in the range of 1 to


10.
Thread Synchronization
 Synchronization is a process of handling resource accessibility by multiple
thread requests.
 The main purpose of synchronization is to avoid thread interference.
 Java Synchronization is better option where we want to allow only one
thread to access the shared resource.
 The problem of shared resources occurs when two or more threads get
execute at the same time. In such a situation, we need some way to
ensure that the shared resource will be accessed by only one thread at a
time, and this is performed by using the concept called synchronization.
 The synchronization is the process of allowing only one thread to access a
shared resource at a time.
 There are two types of thread synchronization mutual exclusive and inter-
thread communication.
1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. Static synchronization.
2. Cooperation (Inter-thread communication in java)
 it will keep the threads from interfering with each other while sharing any
resources.
 It is used for preventing threads from interfering with each other and to
keep distance between the threads. Mutual exclusive is achieved using
the following:
1. Synchronized Block
2. Synchronized Method
3. Static Synchronization
1. Synchronized block If a block is declared as synchronized then the code which
is written inside a method is only executed instead of the whole code. It is used when
sequential access to code is required.
Syntax:
synchronized (object reference)
{

}
Exapmle on synchronized block
 Java Synchronized Method
 If you declare any method as synchronized, it is known as synchronized
method.
 Synchronized method is used to lock an object for any shared resource.
 When a thread invokes a synchronized method, it automatically acquires
the lock for that object and releases it when the thread completes its task.
 Synchronized method It is a method that can be declared synchronized
using the keyword “synchronized” before the method name.
 By writing this, it will make the code in a method thread-safe so that no
resources are shared when the method is executed.
 Syntax:

 synchronized public void methodName()


 {

 }
 If you make any static method as synchronized, the lock will be on the class
not on object.
 we are using synchronized keyword on the static method to perform static
synchronization.
 In case of synchronized method and synchronized block there cannot be
interference between t1 and t2 or t3 and t4 because t1 and t2 both refers to a
common object that have a single lock.
 But there can be interference between t1 and t3 or t2 and t4 because t1
acquires another lock and t3 acquires another lock. So we need static
synchronization
Inter Thread Communication in java
 Interthread communication is important when you develop an
application where two or more threads exchange some information.
 There are three simple methods and a little trick which makes thread
communication possible. All the three methods are listed below −
 These methods have been implemented as final methods in Object, so
they are available in all the classes. All three methods can be called
only from within a synchronized context.
Sr.No. Method & Description
public void wait()
Causes the current thread to wait
1
until another thread invokes the
notify().
public void notify()
2 Wakes up a single thread that is
waiting on this object's monitor.
public void notifyAll()
Wakes up all the threads that
3
called wait( ) on the same object.
 Inter-thread communication is a process in which a thread is paused
running in its critical region and another thread is allowed to enter (or
lock) in the same critical region to be executed. i.e. synchronized threads
communicate with each other.
 What is the difference between notify() and notifyAll()?
 notify() wakes up only one thread and it follows thread priority.
notifyAll() wakes up multiple threads and it does not follow thread
priority.
 Explain the reason why wait(), notify() and notifyAll() belong to the
object class instead of the thread class?
 According to the Inter-thread communication rule, the owner must be
common to the multiple threads.
 In Java, the owner can be any Java class object. To make these methods
available in any type of owner, Java defines those methods in object
class because it is a supreme class for all owners.
Vector in java
 Vector is like the dynamic array which can grow or shrink its size.
 Unlike array, we can store n-number of elements in it as there is no size limit.
 It is found in the java.util package and implements the List interface, so we can use all the methods of List
interface here.
 It is recommended to use the Vector class in the thread-safe implementation only.
 It is similar to the ArrayList, but with two differences.
• Vector is synchronized.
• Java Vector contains many legacy methods that are not the part of a collections framework.
 Java Vector Constructors
 Vector class supports four types of constructors. These are given below:
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, It constructs an empty


int capacityIncrement) vector with the specified
initial capacity and
capacity increment.
 1.void add(int index, Object element)
 Inserts the specified element at the specified position in this Vector.
 2.boolean add(Object o)
 Appends the specified element to the end of this Vector.
 3.boolean addAll(Collection c)
 Appends all of the elements in the specified Collection to the end of this Vector, in
the order that they are returned by the specified Collection's Iterator.
 4.boolean addAll(int index, Collection c)
 Inserts all of the elements in in the specified Collection into this Vector at the
specified position.
 5.void clear()
 Removes all of the elements from this vector.
 6.Object elementAt(int index)
 Returns the component at the specified index.
 7.boolean equals(Object o)
 Compares the specified Object with this vector for equality.
 8.Object firstElement()
 Returns the first component (the item at index 0) of this vector.
 9.Object get(int index)
 Returns the element at the specified position in this vector.
 10.boolean isEmpty()
 Tests if this vector has no components.
 11.Object remove(int index)
 Removes the element at the specified position in this vector.
 12.int size()
Java ArrayList Class
 The ArrayList class is a part of java collection framework. It is available inside
the java.util package.
 The ArrayList class extends AbstractList class and implements List interface.
 Java ArrayList class uses a dynamic array for storing the elements. It is like an
array, but there is no size limit.
 We can add or remove elements anytime. So, it is much more flexible than the
traditional array.
 The ArrayList in Java can have the duplicate elements also. It implements the
List interface so we can use all the methods of the List interface here.
1. ArrayList supports dynamic array that can grow as needed.
2. It can contain Duplicate elements and it also maintains the insertion order.
3. Manipulation is slow because a lot of shifting needs to be occurred if any
element is removed from the array list.
4. ArrayLists are not synchronized.
5. ArrayList allows random access because it works on the index basis.
 ArrayList class constructors:
 The ArrayList class has the following constructors.
• ArrayList( ) - Creates an empty ArrayList.
• ArrayList(Collection c) - Creates an ArrayList with given collection of elements.
• ArrayList(int size) - Creates an empty ArrayList with given size (capacity).

• Methods in ArrayList:
• boolean add(E element) - Appends given element to the ArrayList.
• boolean addAll(Collection c) - Appends given collection of elements to the
ArrayList.
• void add(int index, E element) - Inserts the given element at specified index.
• E get(int index) - Returns element at specified index from the ArrayList.
• int indexOf(E element) - Returns the index value of given element first occurence
in the ArrayList.
• int lastIndexOf(E element) - Returns the index value of given element last
occurence in the ArrayList.
 E set(int index, E newElement) - Replace the element at specified index
with newElement in the invoking ArrayList.
• E remove(int index) - Removes the element at specified index in the
invoking ArrayList.
• boolean remove(Object element) - Removes the first occurence of the
given element from the invoking ArrayList.
 void clear( ) - Removes all the elements from the ArrayList.
• int size( ) - Returns the total number of elements in the invoking
ArrayList.
• boolean isEmpty( ) - Returns true if the list is empty otherwise returns
false.
• void sort(Comparator c) - Sorts all the elements of invoking list based on
the given comparator.
• List[ ] subList(int startIndex, int endIndex) - Returns list of elements
starting from startIndex to endIndex-1.
 void trimToSize( ) - Used to trim a ArrayList instance to the number of
elements it contains.

You might also like