Unit Iii
Unit Iii
Semester: III
Unit – III
1
2
3.1. Java Array
• Array is a collection of similar type of data. It is fixed in size means that you can't
increase the size of array at run time
• An array is a collection of similar types of data. It is a container that holds data (values)
of one single type. For example, you can create an array that can hold 100 values of int
type.
• Good question! We have to allocate memory for the array. The memory will define the
number of elements that the array can hold.
o data = new Double[10];
• Here, the size of the array is 10. This means it can hold 10 elements (10 double types
values). The size of an array is also known as the length of an array.
• In Java, each element in an array is associated with a number. The number is known
as an array index. We can access elements of an array by using those indices. For
example,
• int[ ] age = new int[5];
3
How to initialize arrays in Java?
• In Java, we can initialize arrays during declaration or you can initialize later in the
program as per your requirement.
• Initialize an Array During Declaration
• we can easily access and alter elements of an array by using its numeric index
• Here's how you can initialize an array during declaration.
o int[] age = {12, 4, 5, 2, 5};
Advantage of Array
• One variable can store multiple value: The main advantage of the array is we can
represent multiple value under the same name.
• Code Optimization: No, need to declare a lot of variable of same type data, We can
retrieve and sort data easily.
4
• Random access: We can retrieve any data from array with the help of the index value.
Disadvantage of Array
• The main limitation of the array is Size Limit when once we declare array there is no
chance to increase and decrease the size of an array according to our requirement,
Hence memory point of view array concept is not recommended to use.
Array creation
• Every array in a Java is an object, Hence we can create array by using new keyword.
• Note: At the time of array creation we must be specify the size of array otherwise get
an compile time error.
o For Example
o int[] a=new int[]; Invalid (some times).
o int[] a=new int[5]; Valid
• If we specify the array size as negative int value, then we will get run-time error,
• The maximum allowed size of array in Java is 2147483647 (It is the maximum value of
int data type)
5
Difference Between Length and Length() in Java
• length: It is a final variable and only applicable for array. It represent size of array.
• length(): It is the final method applicable only for String objects. It represents the
number of characters present in the String.
Types of Array
• Multidimensional Array
6
3.2. Java String
• Strings represents sequence of char values. An array of characters works same as java
string.
String literal
7
• Each time you create a string literal, the JVM checks the string constant pool first. If the
string already exists in the pool, a reference to the pooled instance is returned. If string
doesn't exist in the pool, a new string instance is created and placed in the pool. For
example:
New keyword
• In such case, JVM will create a new string object in normal(non pool) heap memory and
the literal "Welcome" will be placed in the string constant pool. The variable s will refer
to the object in heap(non pool).
8
3.3. 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.
Creating a Vector
9
Methods of Vector
• The Vector class also provides the resizable-array implementations of the List interface
(similar to the ArrayList class). Some of the Vector methods are:
10
• Vector implements a dynamic array. It is similar to ArrayList
• Vector class object organizes the data in the form of cells
• Vector proves to be very useful if you don't know the size of the array in advance or you
just need one that can change sizes over the lifetime of a program
•
• The default capacity of the Vector v=10 cells
• Vector are Synchronized
• Vector uses Enumeration interface to traverse the elements
• Vector class object organizes the data in the form of cells
11
• The default size of the Vector=0 (size is nothing but number of values available in the
cells)
• In Vector cell values are storing in Heap Memory and cell address
12
• All the methods of an interface are by default public. So, it is not required to use the
keyword public when declaring a method in an interface.
• As shown in the figure given below, a class extends another class, an interface extends
another interface but a class implements an interface.
Creating interface:
13
• In the above syntax Interface is a keyword interface name can be user defined name
the default signature of variable is public static final and for method is public abstract.
Extending interface
• An interface can extend another interface in the same way that a class can extend
another class.
• The extends keyword is used to extend an interface, and the child interface inherits the
methods of the parent interface, this means an interface can be sub-interface from
other interfaces, the new sub-interface will inherit all the members of the super-
interface in the manner similar to subclass
Implementing Interface:
14
Rules for implementation interface
15
16
3.5. Java Packages
• Java package is used to categorize the classes and interfaces so that they can be
easily maintained.
• Java package provides access protection.
• Java package removes naming collision.
• Application development time is less, because reuse the code
• Package in java can be Categorized in two form
o Built-in package
o User-defined package
Built-in package
17
• java.lang: Contains language support classes(e.g classed which defines primitive data
types, math operations). This package is automatically imported.
• java.io: Contains classed for supporting input / output operations.
• java.util: Contains utility classes which implement data structures like Linked List,
Dictionary and support ; for Date / Time operations.
• java.applet: Contains classes for creating Applets.
• java.awt: Contain classes for implementing the components for graphical user
interfaces (like button , ;menus etc).
• java.net: Contain classes for supporting networking operations.
User-defined packages
18
• Import above class in below program using import packageName.className
• Explanations: In above syntax "-d" is a specific tool which is tell to java compiler
create a separate folder for the given package in given path. When we give specific
path then it create a new folder at that location and when we use . (dot) then it crate a
folder at current working directory.
• Explanations: In the above program first we create Package program which is save
with A.java and compiled by "javac -d . A.java". Again we import class "A" in class Hello
using "import mypack.A;" statement.
• Package keyword is always used for creating the undefined package and placing
common classes and interfaces.
• Import Is A Keyword which is used for referring or using the classes and interfaces of
a specific package.
Access Package
• There are Three ways to access the package from outside the package.
o import package.*;
o import package.classname;
o fully qualified name
Using Packagename.*
19
• If you use package.* then all the classes and interfaces of this package will be
accessible but not subpackages (Package inside the package is called the
subpackage).
• The import keyword is used to make the classes and interface of another package
accessible to the current package.
Using packagename.classname
• If you import package.classname then only declared class of this package will be
accessible.
20
Using fully qualified name
• If you use fully qualified name then only declared class of this package will be
accessible. Now there is no need to import. But you need to use fully qualified name
every time when you are accessing the class or interface.
• It is generally used when two packages have same class name e.g. java.util and
java.sql packages contain Date class.
21
Subpackage in java
• A program can be divided into a number of small processes. Each small process can
be addressed as a single thread.
• Multithreaded programs contain two or more threads that can run concurrently and
each thread defines a separate path of execution. This means that a single program
22
can perform two or more tasks simultaneously. For example, one thread is writing
content on a file at the same time another thread is performing spelling check.
• In computer, multitasking is when multiple processes share common processing
resources such as a CPU, hard disk etc... Multi-threading extends the idea of
multitasking into applications where you can subdivide specific operations within a
single application into individual threads.
• Multi-threading enables you to write in a way where multiple activities can proceed
concurrently in the same program.
• A Thread is similar to a program that has a single flow of control, It has a beginning, a
body, and an end, and executes commands sequentially.
• Thread is a lightweight components and it is a flow of control. In other words a flow of
control is known as thread, Threads share the same address space.
• Threads are independent, if there occurs exception in one thread, it doesn't affect other
threads. It shares a common memory area.
• It doesn't block the user because threads are independent and you can perform
multiple operations at same time.
• You can perform many operations together so it saves time.
• Threads are independent so it doesn't affect other threads if exception occur in a single
thread.
23
• 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.
24
3.8. Creating Threads
• Create any user defined class and make that one as a derived class of thread class.
25
• Override run() method of Thread class (It contains the logic of perform any operation)
• Create an object for user-defined thread class and attached that object to predefined
thread class object.
• Object Creation for Thread Class_Name obj=new Class_Name Thread t=new
Thread(obj);
• Call start() method of thread class to execute run() method.
• Save the program with filename.java
26
• The easiest way to create a thread is to create a class that implements the runnable
interface. After implementing runnable interface , the class needs to implement the
run() method,
• Create any user defined class and implements runnable interface within that
• Override run() method within the user defined class.
• all start() method to execute run() method of thread class
Stopping thread
• When ever we want to stop a thread from running further, we may do so by calling its
stop() method, ex. aThread.stop();
• This statement causes the thread to move to the dead state.
• A thread will also move to the dead state automatically when it reaches the end of its
method.
Blocking thread
• A thread can also be temporarily suspended or blocked from entering into the runnable
and subsequently running state by using either following thread methods.
• sleep() - block for a specified time
• suspend() - blocked until further order
• wait() - blocked until certain condition occurs
27
What is the difference between sleep() and suspend()
• Sleep() can be used to convert running state to waiting state and automatically thread
convert from waiting state to running state once the given time period is completed.
• Whereas suspend() can be used to convert running state thread to waiting state but it
will never return back to running state automatically.
• Each thread has a priority. Priorities are represented by a number between 1 and 10.
In most cases, thread scheduler schedules the threads according to their priority
(known as preemptive scheduling).
28
• sleep() - Used to change running state thread to ready state based on time period it is
a static method should be called with class reference.
• suspend() - used to convert running state thread to waiting state, which will never
come back to running state automatically.
• resume() - Used to change the suspended thread state(waiting state) to ready state.
• stop() - This method is used to convert running state thread to dead state.
• getState() - This method is used to get the current state of thread.
29