0% found this document useful (0 votes)
15 views29 pages

Unit Iii

Uploaded by

yugabharath852
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)
15 views29 pages

Unit Iii

Uploaded by

yugabharath852
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/ 29

Course Material

Subject: Java Programming Class: II B.Sc CS A

Semester: III

Unit – III

Title Page No.

3.1. Java Array 2


3.2. Java String 6
3.3. Vector in Java 8

3.4. Java Interface 11

3.5. Java Packages 16


3.6. Multithread Programming 21
3.7. Life cycle of thread 22

3.8. Creating Threads 24


3.9. Thread Priority 27

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.

How to declare an array?

• In Java, here is how we can declare an array.


o dataType[] arrayName;
• dataType - it can be primitive data types like int, char, double, byte, etc. or Java objects
o arrayName - it is an identifier

But, how many elements can array this hold?

• 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.

Java Array Index

• 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];

• It stores the value on the basis of the index value.

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

• Single Dimensional Array

• Multidimensional Array

6
3.2. Java String

• Strings represents sequence of char values. An array of characters works same as java
string.

• In Java programming language, strings are treated as objects.


• The java.lang.String class is used to create string object.

How to create String object

• There are two ways to create String object:


o String literal
o New keyword

String literal

• Java String literal is created by using double quotes.

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

• Here is how we can create vectors in Java.

Vector<Type> vector = new Vector<>();

• Here, Type indicates the type of a linked list. For example,

// create Integer type linked list

Vector<Integer> vector= new Vector<>();

// create String type linked list

Vector<String> vector= new 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:

Add Elements to Vector

• add(element) - adds an element to vectors


• add(index, element) - adds an element to the specified position
• addAll(vector) - adds all elements of a vector to another vector

Access Vector Elements

• get(index) - returns an element specified by the index

Remove Vector Elements

• remove(index) - removes an element from specified position


• removeAll() - removes all the elements
• clear() - removes all elements. It is more efficient than removeAll()

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

3.4. Java Interface

• An interface is similar to class. It is a collection of abstract methods (function) and


variables with major differences.
• The difference is that interface define only abstract methods and final fields, This
means that interfaces do not specify any code to implement these methods and data
fiedls contain only constants.
• Therefore, it is the responsibility of the class that implements an interface to define the
code for implementation these methods.
• Java Interface also represents IS-A relationship.
• It is used to achieve abstraction and multiple inheritance in Java.

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.

How interface is different from class?

• An interface can contain any number of methods


• All methods in an interface are abstract (only declaration of method).
• Interface is cannot extended by a class; it is implemented by a class.
• Interface can extend multiple interfaces. It means interface support multiple inheritance

Understanding relationship between Classes and 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:

• The interface keyword is used to declare an 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:

• A class uses the implements keyword to implement an interface. The implements


keyword appears in the class declaration following the extends portion of the
declaration.

14
Rules for implementation interface

• A class can implement more than one interface at a time.


• A class can extend only one class, but implement many interfaces.
• An interface can extend another interface, similarly to the way that a class can extend
another class.

15
16
3.5. Java Packages

• A java package is a group of similar types of classes, interfaces and sub-packages.


• Package in Java is a mechanism to encapsulate a group of classes, sub packages and
interfaces.
• The purpose of package concept is to provide common classes and interfaces for any
program separately. In other words if we want to develop any class or interface which is
common for most of the java programs than such common classes and interfaces must
be place in a package.

Advantage of Java Package

• 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

• These packages consist of a large number of classes which are a part of


Java API.Some of the commonly used built-in packages are:

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

• If any package is design by the user is known as user defined package.


• Any package program can be compile but cannot be execute or run. These program
can be executed through user defined program which are importing package program.

Rules to create user defined package

• Package statement should be the first statement of any package program.


• Choose an appropriate class name or interface name and whose modifier must be
public.
• Any package program can contain only one public class or only one public interface
• Package program should not contain any main class (that means it should not contain
any main())
• Every package program should be save either with public class name or public
Interface name
• Compile package programs - javac -d . a.java
• To Run: java mypack.a

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.

Difference between package keyword and import keyword

• 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

• Package inside the package is called the subpackage. It should be created to


categorize the package further.

3.6. Multithread Programming

• 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.

Advantages of Java Multithreading

• 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.

3.7. Life cycle of thread

• State of a thread are Classified into five types they are


o New State
o Ready State
o Running State
o Waiting State
o Halted or dead State

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

• In java language multithreading can be achieve in two different ways.


o Using Extending Thread class
o Using Runnable interface

Using Extending Thread class

In java language Rules to be followed to creating multithreading program

• 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

Using Runnable interface

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,

Rules to create the thread using Runnable interface

• 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.

3.9. Thread Priority

• 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).

Three types of Thread Priority

public static int MIN_PRIORITY


public static int NORM_PRIORITY
public static int MAX_PRIORITY

The following are the methods of thread class

• getPriority() - This method is used to get the current priority of thread.


• setPriority() - This method is used to set the current priority of thread.
• getName() - This method is used to get the current executing thread name.
• setName() - This method is used to set the user-defined name for the thread.
• run() - Which contains the main business logic that can be executed by multiple
threads simultaneously in every user defined thread class run method should be
overridden.
• start() - Used to convert ready state thread to running state.

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

You might also like