UNIT 3 - Contents
• Arrays
• Strings
• Packages
Unit 3 •
•
Creating Packages
Using Packages
• Visibility control
• Exception Handling Techniques
• try-catch
• throw and throws
• finally
• Multithreading
• Creation of Multi-threaded programs
• Thread Class
• Runnable interface
2 September 2021 1 2 September 2021 2
Arrays Arrays
• A group of related data items that share a Initialization of arrays
common name. int number[] ={35,23,67,45,32}
• One dimensional arrays • For initialization of arrays, there is a special value
called null which represents an array with no
Syntax: type arrayname[] = new type[size]; value.
Example: int salary[] = new int[20]; • In Java all arrays store the allocated size in a
variable called length.
Example
int l = a.length, where a is an array.
2 September 2021 3 2 September 2021 4
Arrays String Handling
Two dimensional arrays • String is a sequence of characters.
Syntax • String is the object representation of an
Type arrayname[][]=new type[size][size] unchangeable character array.
Example • StringBuffer is a companion class used to
int m[][] = new int[4][4] create strings that can be manipulated after
they are created.
✓In Java the positions in an array will be
automatically set to 0 if it is not assigned a • Both String and StringBuffer classes are not
value. subclassible.
2 September 2021 5 2 September 2021 6
String Handling - Constructors String Handling - Length
• Empty string creation String s =“abc”;
String s =new String();
• String initialized with characters System.out.println(s.length());
String s =new String(“Java”); System.out.println(“abc”.length());
• Strings can be created by passing an array of characters
to the constructor.
char c[]={‘a’, ’b’, ’c’, ‘d’, ‘e’, ’f’, ‘g’};
String s =new String(c);
System.out.println(s);
String s1=new String(c,2,3);
System.out.println(s1);
2 September 2021 7 2 September 2021 8
String Handling - Concatenation String Handling – Character Extraction
String s =“He is ” + age + “years old”; • To extract single character from a string, we
String s=new StringBuffer(“He is “) can use the charAt() method.
.append(age) • To extract more than one character, we can
.append(“ years old.”) use the getChars() method which allows us to
specify the index of the first and one past the
.toString() last character we want to copy.
String s=“four: “ + 2+ 2 • Example Program
String s=“four:”+ (2+2)
2 September 2021 9 2 September 2021 10
String Handling - Comparison String Handling - Ordering
• To check whether two strings are equal, we • For sorting applications, we need to know
can use the equals() method. Returns true if which string is less than, equal to or greater
two strings are exactly equal. than the next.
• If we want to compare strings irrespective of • For this the method compareTo() is used. If
the case, we can use the equalsIgnoreCase() the ordering is to be done irrespective of the
method. case, the method compareToIgnoreCase() is
• Example Program used.
• Example Program
2 September 2021 11 2 September 2021 12
String Handling – indexOf() and String Handling – indexOf() and
lastIndexOf() lastIndexOf()
• Each of these methods returns the index of the character • int indexOf(int ch, int fromIndex)- Returns the index of the
we are searching for. If the search is unsuccessful, it returns first occurence after fromIndex of the character ch.
-1. • int lastIndexOf(int ch, int fromIndex)- Returns the index of
• int indexOf(int ch)- Returns the index of the first occurence the first occurence before fromIndex of the character ch.
of the character ch. • int indexOf(string str, int fromIndex)- Returns the index of
• int lastIndexOf(int ch)- Returns the index of the last the first character of the first occurence after fromIndex of
occurence of the character ch. the substring str.
• int indexOf(String str)- Returns the index of the first • int lastIndexOf(string str, int fromIndex)- Returns the index
character of the first occurence of the substring str. of the first character of the first occurence before
• int lastIndexOf(String str)- Returns the index of the first fromIndex of the substring str.
character of the last occurence of the substring str.
• Example Program
• Example Program
2 September 2021 13 2 September 2021 14
String Copy Modifications String Copy Modifications
❑ substring() – used to extract a range from a ❑ replace() – takes 2 characters as parameters. All
occurrences of the first are replaced with the second.
String using substring. Example Program
Example Program ❑ toLowerCase() and toUpperCase() – toLowerCase()
converts all the characters in a string to lowercase and
❑ concat() – creates a new object with the toUpperCase() converts all characters to uppercase in
current contents of our string with the new a string.
Example Program
string. ❑ trim() - returns a copy of the string without any
Example Program leading and trailing whitespace.
Example Program
2 September 2021 15 2 September 2021 16
StringBuffer StringBuffer Methods
• String represents fixed length, immutable ❑Constructors – A StringBuffer may be constructed
character sequences. with no parameter which reserves room for 16
chars .
• StringBuffer represents growable and ❑Can also pass an initial string which will set the
writeable character sequences. initial contents and reserve room for 16 more
• StringBuffer can have characters and characters.
substrings inserted in the middle or appended ❑Current length of the StringBuffer can be found
to the end. using length() method and total allocated
capacity using the capacity() method.
❑Example Program
2 September 2021 17 2 September 2021 18
StringBuffer Methods StringBuffer Methods
❑charAt() and setCharAt() – charAt() method ❑append() – used to add substrings to the end
returns the character at a specified position. of the string.
setCharAt() replace a character at a specified ❑Example Program
position. ❑insert() – used to insert substrings in a given
❑Example Program string.
❑Example Program
2 September 2021 19 2 September 2021 20
Packages Java API Packages
• Containers for classes used to keep the class • Provides a large number of classes grouped
name space compartmentalized. into different packages.
• Packages are stored in a hierarchical manner 1. java.lang – include classes for primitive types,
mathematical functions, threads, exceptions
and are explicitly imported into new class
etc.
definitions.
2. java.util – consists of language utility classes
1. Java API packages such as date, time, hashtables etc.
2. User defined packages 3. java.io – provide the facilities for input and
output.
2 September 2021 21 15 July 2020 22
Java API Packages User defined Packages
4. java.net – include classes for communication 1. Declare the package at the beginning of the program
using the form
with local computers as well as with internet package pkg1[.pkg2[.pkg3]]; For example, the package
servers. java.awt.image should be stored in java\awt\image
2. Define the class that is to be put in the package and
5. java.applet – classes for creating and declare it public.
implementing applets. 3. Create a subdirectory under the directory where the
main source files are stored.
6. java.awt – include classes for windows, 4. Store the file as classname.java in the subdirectory
buttons, lists, menus etc. created.
5. Compile the file. This creates the .class file in the
subdirectory.
2 September 2021 23 2 September 2021 24
Packages – import statement Packages – Access Protection
• Java packages can be accessed using the Private No
modifier
Private
protected
Protected Public
import statement. Same Class Yes Yes Yes Yes Yes
Same package No Yes Yes Yes Yes
• Syntax subclass
import package1[.package2][.package3].classname; Same package non- No Yes No Yes Yes
subclass
Import packagename.* Different package No No Yes Yes Yes
subclass
Different package No No No no Yes
non-subclass
2 September 2021 25 2 September 2021 26
Packages – Access Protection Exception Handling
• Anything declared public can be accessed • Exception is an abnormal condition caused by
from anywhere. a runtime error in the program.
• Anything declared private cannot be seen • Example division by zero.
outside a class. • When java interpreter encounters such an
error, it creates an exception object and
• No modifier is the default. throws it. (informs an error has occurred)
• Java’s protected is equivalent to friend in C++. • If exception object is not caught and handled
• If we want to emulate protected in C++, we properly, the interpreter will display an error
must use java’s private protected. message.
2 September 2021 27 2 September 2021 28
Exception Handling Exception Handling - Hierarchy
• If we want the program to continue, then we
should catch the exception object and display
appropriate message for taking corrective
actions.
1. Find the problem (Hit the Exception)
2. Inform that an error has occurred (Throws the
exception)
3. Receive the error information(Catch the
exception)
4. Take corrective actions (Handle the Exception)
2 September 2021 29 2 September 2021 30
Exception Types Exception Types
1. ArithmeticException – caused by 4. FileNotFoundException – caused by an
mathematical errors such as division by zero. attempt to access a non-existent file.
2. ArrayIndexOutOfBoundsException – caused 5. IOException – caused by general I/O failures
by wrong array indices. such as inability to read from a file.
3. ArrayStoreException – caused when a 6. StringIndexOutOfBoundsException – caused
program tries to store the wrong type of data when a program attempts to access a non
in an array. existent character position in a string.
2 September 2021 31 2 September 2021 32
Uncaught Exceptions Uncaught Exceptions
class Exco{ Output
public static void main(String args[]) Java.lang.ArithmeticException:/by zero at
{int d=0; Exco.main (Exco.java:4)
int a = 42/d; • Classname Exco, the method name main, the
}} filename Exco.java and line number 4 are all
included in the stack trace.
• An Exception occurs and in the above
example, we haven’t coded an event handler.
Hence default runtime handler is run.
2 September 2021 33 2 September 2021 34
Exception Handling – try and catch Exception Handling – try and catch
try{ statement; • Catch block catches the exception thrown by
} the try block.
catch(Exception e) • Try block can have one or more statements
{statement; that could generate an exception.
}//processes the exception • If any one statement generates an exception,
the remaining statements are skipped and
• Try is to prepare a block of code that is likely execution jumps to the catch block that is
to cause an error condition and throw an placed next to the try block.
exception.
2 September 2021 35 2 September 2021 36
Exception Handling – multiple catch
Exception Handling – try and catch
clauses
• It is possible to have more than one catch statement in try block.
• Catch block can have one or more statements. try {
• If the catch parameter matches with the type statement}
catch(Exception_type1 e)
of exception object, then the exception is {statement;//processes exception type 1
}
caught and statements in the catch block will catch(Exception_type2 e)
be executed. {statement; //processes exception type 2
}
• Every try statement should be followed by at catch(Exception_type3 e)
{statement; // processes exception type 3
least one catch statement. }
Example program Example program
2 September 2021 37 2 September 2021 38
Exception Handling – Nested try
Exception Handling- finally
statements
• We can wrap a try statement inside another • When exceptions are thrown, the flow of code
try statement. follows a non linear path.
• Each time a try statement is encountered, the • finally block is executed always no matter the
context of that exception is stacked up until all exception is caused or caught.
of the nested try statement completes.
• If a lower level try doesn’t have a match, the • Example Program
stack is unwound and the next try’s match is
checked.
Example program
15 July 2020 39 2 September 2021 40
Exception Handling – throw and Exception Handling – throw and
throws throws
• Throw is used to throw the exception, whereas • If a method is throwing an exception, it
throws is declarative for the method. should either be surrounded by a try catch
• They are not interchangeable. block or the method should have throws
Example program clause in its signature.
public void myMethod(int param) throws
• Throws clause tells the compiler that this
MyException{
particular exception would be handled by the
If (param<10)
calling method.
throw new MyException(“Too Low”)
}
2 September 2021 41 2 September 2021 42
Multithreading Multithreading
• A concept in which the programs are divided • In multitasking, tasks are known as heavy weight
processes.
into two or more processes which can be run
• In multithreading, tasks are known as light weight
in parallel. processes.
• For example, when the program waits for the • Difference is that heavy weight processes are in
input, the CPU sits idle until the I/P is separate address spaces and can be thought of as
different programs running on the same system like
received. word and excel.
• In a multithreaded environment, CPU can • Threads share the same address space.
perform other computational tasks when it • Threads are used in Java enabled Web browsers which
waits for the I/O. can download a file, display a Web page in a window,
print another Web page to a printer and so on.
2 September 2021 43 2 September 2021 44
Life Cycle of a Thread Life Cycle of a Thread
stop() 1. Newborn State
New Born
start()
2. Runnable State
Active
Thread yield() Dead 3. Running State
Running Runnable
stop()
4. Blocked State
Suspend() Resume()
Sleep() Notify() 5. Dead State
Wait()
Blocked
Idle Thread
15 July 2020 45 2 September 2021 46
Life Cycle of a Thread Life Cycle of a Thread
• Newborn State – When we create a thread, it is in • Runnable State – This state means the thread is ready
for execution and is waiting for the availability of the
the new born state. processor.
1. Schedule it for running using start() method. • These threads are executed in a FIFO manner.
2. Kill it using stop() method • If all threads have equal priority, then they are given
time slots for execution.
• This process of assigning time to threads is known as
time slicing.
• We can relinquish the control to another thread of
equal priority by using the yield() method.
2 September 2021 47 2 September 2021 48
Life Cycle of a Thread Life Cycle of a Thread
• Running State – the processor has given its time to the • Blocked State – When a thread is prevented from
thread for execution.
• A running thread may relinquish its control in one of the entering into the runnable state and subsequently
following situations. the running state.
1. Suspend using the suspend() method. A suspended thread
can be revived using the resume() method. • Happens when the thread is suspended, sleep or in
2. Sleep a thread for a specified time period using the method wait state.
sleep(time) where time is in milliseconds. The thread re-
enters the runnable state as soon as the time period is
elapsed.
3. A thread can be put to wait state using wait() method. The
thread can be scheduled to run again using notify() method.
2 September 2021 49 2 September 2021 50
Life Cycle of a Thread Creating Threads
• Dead State – Kill the thread using the stop() • Threads are implemented in the form of
method. objects and contain a method called run().
• The heart of the thread is the run() method.
• Threads can be implemented in 2 ways.
1. By extending the Thread class.
2. By implementing Runnable interface.
2 September 2021 51 2 September 2021 52
Extending the Thread class Implementing the Runnable Interface
1. Declare the class as extending the Thread class. Example Program
2. Implement the run() method that is responsible
for the execution of the thread code.
3. Create a Thread object and call the start()
method.
Example Program
Program to illustrate yield(), sleep() and stop()
methods.
2 September 2021 53 2 September 2021 54
End of Unit 3
2 September 2021 55