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

BSC MPCS Vth Sem Java Unit 2-signed

The document covers various Java programming concepts including packages, exception handling, multithreading, input/output operations, wrapper classes, and string manipulation. It explains the creation and usage of packages, their advantages, and access protection levels, as well as the importance of wrapper classes for handling primitive data types. Additionally, it details string creation methods and common string methods available in Java.

Uploaded by

MS Reddy
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)
5 views46 pages

BSC MPCS Vth Sem Java Unit 2-signed

The document covers various Java programming concepts including packages, exception handling, multithreading, input/output operations, wrapper classes, and string manipulation. It explains the creation and usage of packages, their advantages, and access protection levels, as well as the importance of wrapper classes for handling primitive data types. Additionally, it details string creation methods and common string methods available in Java.

Uploaded by

MS Reddy
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

Unit – II

01

Packages–Creating and Using Packages, Access Protection, Wrapper Classes, String Class, StringBuffer
Class. Exception: Introduction, Types, Exception Handling Techniques, User-Defined Exception.

Multithreading: Introduction, Main Thread, Creation of New Threads – By Inheriting the Thread Class or
Implementing the Runnable Interface, Thread Lifecycle, Thread Priority, Synchronization.

Input/Output: Introduction, java.io Package, File Class, FileInputStream Class, FileOutputStream Class,
Scanner Class, BufferedInputStream Class, BufferedOutputStream Class, RandomAccessFile Class.

MS bhanu
Packages 02

A package is a container of classes and interfaces. A package represents a directory that contains related
group of classes and interfaces. For example, when we write statement like:
import java.io.*;
Here we are importing classes of java.io package. Here, java is a directory name and io is another sub
directory within it. The “*” represents all the classes and interfaces of that io sub directory. We can create
our own packages called user-defined packages or extend the available packages. User-defined packages can
also be imported into other classes and used exactly in the same way as the Built-in packages. Packages
provide reusability.

Advantages of using a package in Java


These are the reasons why you should use packages in Java:
 Reusability: While developing a project in java, we often feel that there are few things that we are
writing again and again in our code. Using packages, you can create such things in form of classes
inside a package and whenever you need to perform that same task, just import that package and use
the class.
 Better Organization: Again, in large java projects where we have several hundreds of classes, it is
always required to group the similar types of classes in a meaningful package name so that you can
organize your project better and when you need something you can quickly locate it and use it, which
improves the efficiency.
 Name Conflicts: We can define two classes with the same name in different packages so to avoid
name collision, we can use packages

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.

General form for creating a User defined package:


While creating a package, you should choose a name for the package and include a package statement
along with that name at the top of every source file that contains the classes, interfaces, enumerations, and
annotation types that you want to include in the package.
The package statement should be the first line in the source file. There can be only one package statement
in each source file, and it applies to all types in the file.
If a package statement is not used then the class, interfaces, enumerations, and annotation types will be
placed in the current default package.
Syntax:
package packagename;

MS bhanu
Ex: package pack; 03

The first statement in the program must be package statement while creating a package. While
creating a package except instance variables, declare all the members and the class itself as public then only
the public members are available outside the package to other programs.
To compile the Java programs with package statements, you have to use -d option as shown below.

javac -d Destination_folder file_name.java

Then a folder with the given package name is created in the specified destination, and the compiled class
files will be placed in that folder.
Program 1: Write a program to create a package pack with Addition class.
//creating a package
package pack;
public class Addition
{
private double d1,d2;
public Addition(double a,double b)
{
d1 = a;
d2 = b;
}
public void sum()
{
System.out.println ("Sum of two given numbers is : " + (d1+d2) );
}
}
Compiling the above program:
C:\>javac – d . Addition.java
The – d option tells the Java compiler to create a separate directory and place the .class file in that
directory (package). The (.) dot after –d indicates that the package should be created in the current directory.
So, out package pack with Addition class is ready.

The import Keyword


If a class wants to use another class in the same package, the package name need not be used.
Classes in the same package find each other without any special syntax.
Program 2: Write a program to use the Addition class of package pack.
//Using the package pack
import pack.Addition;
class Use

MS bhanu
{
04
public static void main(String args[])
{
Addition ob1 = new Addition(10,20);
ob1.sum();
}
}
Output:
//compiling program
C:\>javac use.java
//Running a program
C:\>java use
Sum of two given numbers: 30.00.

2. Built-in package or Java API Package


Java APl(Application Program Interface) provides a large numbers of classes grouped into different
packages according to functionality. Most of the time we use the packages available with the the Java API.
Following figure shows the system packages that are frequently used in the programs.

Java System Packages and Their Classes

java.lang Language support classes. They include classes for primitive types, string, math
functions, thread and exceptions.

java.util Language utility classes such as vectors, hash tables, random numbers, data, etc.

java.io Input/output support classes. They provide facilities for the input and output of data.

java.applet Classes for creating and implementing applets.

java.net Classes for networking. They include classes for communicating with local computers
as well as with internet servers.

java.awt Set of classes for implementing graphical user interface. They include classes for
windows, buttons, lists, menus and so on.

MS bhanu
05
Access Protection in Packages
Access modifiers define the scope of the class and its members (data and methods). For example, private
members are accessible within the same class members (methods). Java provides many levels of security
that provides the visibility of members (variables and methods) within the classes, subclasses, and
packages.
Packages are meant for encapsulating, it works as containers for classes and other subpackages.
Class acts as containers for data and methods. There are four categories, provided by Java regarding the
visibility of the class members between classes and packages:
1. Subclasses in the same package
2. Non-subclasses in the same package
3. Subclasses in different packages
4. Classes that are neither in the same package nor subclasses

The three main access modifiers private, public and protected provides a range of ways to access required
by these categories.

Private Protected Public No Modifier

Same class Yes Yes Yes Yes

Same package subclass No Yes Yes Yes

Same package non-subclass No Yes Yes Yes

Different package subclass No Yes Yes No

Different package non-subclass No No Yes No

Simply remember, private cannot be seen outside of its class, public can be access from anywhere, and
protected can be accessible in subclass only in the hierarchy.

A class can have only two access modifier, one is default and another is public. If the class has default
access then it can only be accessed within the same package by any other code. But if the class has public
access then it can be access from any where by any other code.

WRAPPER CLESS
A Wrapper class is a class whose object wraps or contains a primitive data types. When we create an object
to a wrapper class, it contains a field and in this field, we can store a primitive data types. In other words, we
can wrap a primitive value into a wrapper class object.
Need of Wrapper Classes
1. They convert primitive data types into objects. Objects are needed if we wish to modify the
arguments passed into a method (because primitive types are passed by value).
2. The classes in java.util package handles only objects and hence wrapper classes help in this case
also.

MS bhanu
3. Data structures in the Collection framework, such as ArrayList and Vector, store only objects
(reference types) and not primitive types. 06
4. An object is needed to support synchronization in multithreading.
The following two statements illustrate the difference between a primitive data type and an object of a
wrapper class:
int x = 25;
Integer y = new Integer(33);
The first statement declares an int variable named x and initializes it with the value 25. The second
statement instantiates an Integer object. The object is initialized with the value 33 and a reference to the
object is assigned to the object variable y. Below table lists wrapper classes in Java API with constructor
details.

Following is the hierarchy of the above classes.

As explain in above table all wrapper classes (except Character) take String as argument constructor. Please
note we might get NumberFormatException if we try to assign invalid argument in constructor. For example
to create Integer object we can have following syntax.
Integer intObj = new Integer (25);
Integer intObj2 = new Integer ("25");
Here in we can provide any number as string argument but not the words etc.
Below statement will throw run time exception (NumberFormatException)

MS bhanu
Integer intObj3 = new Integer ("Two"); 07

The following discussion focuses on the Integer wrapperclass, but applies in a general sense to all eight
wrapper classes.
Autoboxing:
Automatic conversion of primitive types to the object of their corresponding wrapper classes is
known as autoboxing. For example – conversion of int to Integer, long to Long, double to Double etc.
Example:
// Java program to demonstrate Autoboxing
import java.util.ArrayList;
class Autoboxing
{
public static void main(String[] args)
{
char ch = 'a';;
// Autoboxing- primitive to Character object conversion
Character a = ch;
ArrayList<Integer> arrayList = new ArrayList<Integer>();
// Autoboxing because ArrayList stores only objects
arrayList.add(25);
// printing the values from object
System.out.println(arrayList.get(0));
}
}
Output:

25

Unboxing:
It is just the reverse process of autoboxing. Automatically converting an object of a wrapper class to
its corresponding primitive type is known as unboxing. For example – conversion of Integer to int, Long to
long, Double to double etc.
Example:
// Java program to demonstrate Unboxing
import java.util.ArrayList;
class Unboxing
{
public static void main(String[] args)
{
Character ch = 'a';

MS bhanu
// unboxing - Character object to primitive conversion
08
char a = ch;
ArrayList<Integer> arrayList = new ArrayList<Integer>();
arrayList.add(24);
// unboxing because get method returns an Integer object
int num = arrayList.get(0);
// printing the values from primitive data types
System.out.println(num);
}
}
Output:
24

The most common methods of the Integer wrapper class are summarized in below table. Similar methods
for the other wrapper classes are found in the Java API documentation.

MS bhanu
Ex:
Import java.io.*; 09
public class WrappingUnwrapping
{
public static void main(String args[])
{
byte grade = 2;
int marks = 50;
float price = 8.6f;
double rate = 50.5;
Byte g1 = new Byte(grade);
Integer m1 = new Integer(marks);
Float f1 = new Float(price);
Double r1 = new Double(rate);
System.out.println("Values of Wrapper objects (printing as objects)");
System.out.println("Byte object g1: " + g1);
System.out.println("Integer object m1: " + m1);
System.out.println("Float object f1: " + f1);
System.out.println("Double object r1: " + r1);
byte bv = g1.byteValue();
int iv = m1.intValue();
float fv = f1.floatValue();
double dv = r1.doubleValue();
System.out.println("Unwrapped values (printing as data types)");
System.out.println("byte value, bv: " + bv);
System.out.println("int value, iv: " + iv);
System.out.println("float value, fv: " + fv);
System.out.println("double value, dv: " + dv);
}
}

String Class
String is a sequence of characters, for e.g. “Hello” is a string of 5 characters. In java, string is an immutable
object which means it is constant and can cannot be changed once it has been created. In java strings are
class objects and implemented using two classes those are
1) string
2) string buffer
A java is an instantiated object of the string class.

MS bhanu
When java strings compare to “c” strings are more reliable and predictable because in “c” the strings are
terminated by “null values” but where as in java string is not a character array and is not null terminated

Creating a String 10

There are two ways to create a String in Java


1. String literal
2. Using new keyword
String literal
In java, Strings can be created like this: Assigning a String literal to a String instance:
Syntax
In java the declaration of string is as follows.
String string name;
String name = new string (“string”);
String str1 = "Welcome";
String str2 = "Welcome";
Using New Keyword.
Syntax

String string name [];

String name = new string [size];

Ex;

string y[];

Y=new string[3];

String str1 = new String("Welcome");

String str2 = new String("Welcome");

Ex:
String string name =(“GAYATHRI”);

String x= new string (“gayathri”);

A Simple Java String Example


public class Example
{
public static void main(String args[])
{
//creating a string by java string literal
String str = "Beginnersbook";
char arrch[]={'h','e','l','l','o'};
//converting char array arrch[] to string str2

MS bhanu
String str2 = new String(arrch);
11
//creating another java string str3 by using new keyword
String str3 = new String("Java String Example");
//Displaying all the three strings
System.out.println(str);
System.out.println(str2);
System.out.println(str3);
}
}
Output:
Beginnersbook
hello
Java String Example
String Methods
1. int length(): Returns the number of characters in the String.
Ex: "GeeksforGeeks".length(); // returns 13

2. Char charAt(int i): Returns the character at ith index.


Ex: "GeeksforGeeks".charAt(3); // returns „k‟

3. String substring (int i): Return the substring from the ith index character to end.
Ex: "GeeksforGeeks".substring(3); // returns “ksforGeeks”

4. String substring (int i, int j): Returns the substring from i to j-1 index.
Ex: "GeeksforGeeks".substring(2, 5); // returns “eks”

5. String concat( String str): Concatenates specified string to the end of this string.
Ex: String s1 = ”Geeks”;

String s2 = ”forGeeks”;

String output = s1.concat(s2); // returns “GeeksforGeeks”

6. int indexOf (String s): Returns the index within the string of the first occurrence of the specified
string.
Ex: String s = ”Learn Share Learn”;

int output = s.indexOf(“Share”); // returns 6

7. int indexOf (String s, int i): Returns the index within the string of the first occurrence of the
specified string, starting at the specified index.
Ex: String s = ”Learn Share Learn”;

MS bhanu
int output = s.indexOf(„a‟,3);// returns 8 12

8. Int lastindexOf( int ch): Returns the index within the string of the last occurrence of the specified
string.
Ex: String s = ”Learn Share Learn”;

int output = s.lastindexOf(„a‟); // returns 14

9. boolean equals( Object otherObj): Compares this string to the specified object.
Ex: Boolean out = “Geeks”.equals(“Geeks”); // returns true

Boolean out = “Geeks”.equals(“geeks”); // returns false

10. boolean equalsIgnoreCase (String anotherString): Compares string to another string, ignoring
case considerations.
Ex: Boolean out= “Geeks”.equalsIgnoreCase(“Geeks”); // returns true

Boolean out = “Geeks”.equalsIgnoreCase(“geeks”); // returns true

11. int compareTo( String anotherString): Compares two string lexicographically.


Ex: int out = s1.compareTo(s2); // where s1 ans s2 are

This returns difference s1-s2. If :

out < 0 // s1 comes before s2

out = 0 // s1 and s2 are equal.

out >0 // s1 comes after s2.

12. int compareToIgnoreCase( String anotherString): Compares two string lexicographically,


ignoring case considerations.
Ex: int out = s1.compareToIgnoreCase(s2);

This returns difference s1-s2. If :

out < 0 // s1 comes before s2

out = 0 // s1 and s2 are equal.

out >0 // s1 comes after s2.

Note- In this case, it will not consider case of a letter (it will ignore whether it is uppercase or
lowercase).
13. String toLowerCase(): Converts all the characters in the String to lower case.
Ex: String word1 = “HeLLo”;

MS bhanu
String word3 = word1.toLowerCase(); // returns “hello"
13
14. String toUpperCase(): Converts all the characters in the String to upper case.
Ex: String word1 = “HeLLo”;

String word2 = word1.toUpperCase(); // returns “HELLO”

15. String trim(): Returns the copy of the String, by removing whitespaces at both ends. It does not
affect whitespaces in the middle.
Ex: String word1 = “ Learn Share Learn “;

String word2 = word1.trim(); // returns “Learn Share Learn”

16. String replace (char oldChar, char newChar): Returns new string by replacing all occurrences
of oldChar with newChar.
Ex: String s1 = “feeksforfeeks“;

String s2 = “feeksforfeeks”.replace(„f‟ ,‟g‟); // returns “geeksgorgeeks”

Note:- s1 is still feeksforfeeks and s2 is geeksgorgeeks


Program to illustrate all string methods:

// Java code to illustrate different constructors and methods


// String class.
import java.io.*;
import java.util.*;
class Test
{
public static void main (String[] args)
{
String s= "GeeksforGeeks";
// or String s= new String ("GeeksforGeeks");
// Returns the number of characters in the String.
System.out.println("String length = " + s.length());
// Returns the character at ith index.
System.out.println("Character at 3rd position = " + s.charAt(3));
// Return the substring from the ith index character
// to end of string
System.out.println("Substring " + s.substring(3));
// Returns the substring from i to j-1 index.
System.out.println("Substring = " + s.substring(2,5));
// Concatenates string2 to the end of string1.
MS bhanu
String s1 = "Geeks";
String s2 = "forGeeks"; 14

System.out.println("Concatenated string = " +s1.concat(s2));


// Returns the index within the string
// of the first occurrence of the specified string.
String s4 = "Learn Share Learn";
System.out.println("Index of Share " + s4.indexOf("Share"));
// Returns the index within the string of the
// first occurrence of the specified string,
// starting at the specified index.
System.out.println("Index of a = " + s4.indexOf('a',3));
// Checking equality of Strings
Boolean out = "Geeks".equals("geeks");
System.out.println("Checking Equality " + out);
out = "Geeks".equals("Geeks");
System.out.println("Checking Equality " + out);
out = "Geeks".equalsIgnoreCase("gEeks ");
System.out.println("Checking Equality" + out);
int out1 = s1.compareTo(s2);
System.out.println("If s1 = s2" + out);
// Converting cases
String word1 = "GeeKyMe";
System.out.println("Changing to lower Case " +word1.toLowerCase());
// Converting cases
String word2 = "GeekyME";
System.out.println("Changing to UPPER Case " + word1.toUpperCase());
// Trimming the word
String word4 = " Learn Share Learn ";
System.out.println("Trim the word " + word4.trim());
// Replacing characters
String str1 = "feeksforfeeks";
System.out.println("Original String " + str1);
String str2 = "feeksforfeeks".replace('f' ,'g') ;
System.out.println("Replaced f with g -> " + str2);
}
}

Output :

MS bhanu
String length = 13
15
Character at 3rd position = k
Substring ksforGeeks
Substring = eks
Concatenated string = GeeksforGeeks
Index of Share 6
Index of a = 8
Checking Equality false
Checking Equality true
Checking Equalityfalse
If s1 = s2false
Changing to lower Case geekyme
Changing to UPPER Case GEEKYME
Trim the word Learn Share Learn
Original String feeksforfeeks
Replaced f with g -> geeksgorgeeks

String buffer class


string buffer is a peer class of string. While string creates fixed
Length, string buffer creates of flexible length that can be modified in terms of both length & content. We
can insert characters and sub string in the middle of the string (or) appended another string to the end.
There are some commonly used string buffers methods are

StringBuffer Methods
Here is the list of important methods supported by StringBuffer class −

Sr.No. Methods & Description

1 public StringBuffer append(String s)


Updates the value of the object that invoked the method. The method takes boolean, char, int,
long, Strings, etc.

2 public StringBuffer reverse()


The method reverses the value of the StringBuffer object that invoked the method.

3 public delete(int start, int end)


Deletes the string starting from the start index until the end index.

4 public insert(int offset, int i)


This method inserts a string s at the position mentioned by the offset.

5 replace(int start, int end, String str) This method replaces the characters in a substring of this
StringBuffer with characters in the specified String.

Here is the list of other methods (except set methods) which are very similar to String class −
MS bhanu
Sr.No. Method & Description

1 int capacity() 16
Returns the current capacity of the String buffer.

2 char charAt(int index)


The specified character of the sequence currently represented by the string buffer, as indicated by
the index argument, is returned.

3 void ensureCapacity(int minimumCapacity)


Ensures that the capacity of the buffer is at least equal to the specified minimum.

4 void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)


Characters are copied from this string buffer into the destination character array dst.

5 int indexOf(String str)


Returns the index within this string of the first occurrence of the specified substring.

6 int indexOf(String str, int fromIndex)


Returns the index within this string of the first occurrence of the specified substring, starting at
the specified index.

7 int lastIndexOf(String str)


Returns the index within this string of the rightmost occurrence of the specified substring.

8 int lastIndexOf(String str, int fromIndex)


Returns the index within this string of the last occurrence of the specified substring.

9 int length()
Returns the length (character count) of this string buffer.

10 void setCharAt(int index, char ch)


The character at the specified index of this string buffer is set to ch.

11 void setLength(int newLength)


Sets the length of this String buffer.

12 CharSequence subSequence(int start, int end)


Returns a new character sequence that is a subsequence of this sequence.

13 String substring(int start)


Returns a new String that contains a subsequence of characters currently contained in this
StringBuffer. The substring begins at the specified index and extends to the end of the
StringBuffer.

14 String substring(int start, int end)


Returns a new String that contains a subsequence of characters currently contained in this

MS bhanu
StringBuffer.

15 String toString() 17
Converts to a string representing the data in this string buffer.
Ex:

public class StringBufferMain


{
public static void main(String[] args)
{
StringBuffer buffer = new StringBuffer();
buffer.append("Hello World!");
System.out.println(buffer.toString());
buffer.delete(5, 11);
System.out.println(buffer.toString());
buffer.deleteCharAt(5);
System.out.println(buffer.toString());
buffer.insert(0, "World ");
System.out.println(buffer.toString());
System.out.println("Index of Hello: " + buffer.indexOf("Hello"));
System.out.println();
StringBuffer newBuffer = new StringBuffer("This is a Hello World string. Hello!");
System.out.println("Index of Hello: " + newBuffer.indexOf("Hello"));
System.out.println("Last index of Hello: " + newBuffer.lastIndexOf("Hello"));
newBuffer.replace(0, 4, "That here");
System.out.println(newBuffer.toString());
newBuffer.setCharAt(newBuffer.length() - 1, '?');
System.out.println(newBuffer.toString());
newBuffer.reverse();
System.out.println(newBuffer.toString());
compareTime();
}
private static void compareTime()
{
long startTime;
String str = "";
StringBuffer buffer = new StringBuffer();
startTime = System.currentTimeMillis();
for (int i = 0; i < 10000; i++)
MS bhanu
{
18
str += "extra";
}
System.out.println("Time using String: "+ (System.currentTimeMillis() - startTime) + " ms.");
startTime = System.currentTimeMillis();
for (int i = 0; i < 10000; i++)
{
buffer.append("extra");
}
System.out.println("Time using StringBuffer: "+ (System.currentTimeMillis() - startTime) + " ms.");
}
}
OUTPUT:
Hello World!

Hello!

Hello

World Hello

Index of Hello: 6

Index of Hello: 10

Last index of Hello: 30

That here is a Hello World string. Hello!

That here is a Hello World string. Hello?

?olleH .gnirts dlroW olleH a si ereh tahT

Time using String: 488 ms.

Time using StringBuffer: 2 ms.

Difference Between String and StringBuffer Class in Java

BASIS FOR
STRING STRINGBUFFER
COMPARISON

MS bhanu
Basic The length of the String object is The length of the StringBuffer can be
19
fixed. increased.

Modification String object is immutable. StringBuffer object is mutable.

Performance It is slower during concatenation. It is faster during concatenation.

Memory Consumes more memory. Consumes less memory.

Storage String constant pool. Heap Memory.

Exceptional Handling
An exception is a problem that arises during the execution of a program. An exception can occur for many
different reasons, including the following: A user has entered invalid data. A file that needs to be opened
cannot be found. A network connection has been lost in the middle of communications, or the JVM has run
out of memory
Types of Exceptions
1. Checked Exception: A checked exception is an exception that is typically a user error or a problem that
cannot be foreseen by the programmer. Checked exception can also be defined as “The classes that extend
the Throwable class except RuntimeException and Error are known as Checked Exceptions”. For example,
if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions are checked at
compile-time and cannot simply be ignored at the time of compilation. Example of Checked Exception are
IOException, SQLException etc.
2. Unchecked Exception: Also known as Runtime Exceptions and they are ignored at the time of
compilation but checked during execution of the program. Unchecked Exceptions can also be defined as
“The Classes that extend the RuntimeException class are known as Unchecked Exceptions”. Examples are
ArithmeticException, NullPointerException etc.
3. Error: These are not exceptions at all, but problems that arise beyond the control of the user or the
programmer. Errors are typically ignored in your code because you can rarely do anything about an error.
For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.

Hierarchy of Exception
All exception classes are subtypes of the java.lang.Exception class. The exception class is a subclass of the
Throwable class. Other than the exception class there is another subclass called Error which is derived from
the Throwable class.

MS bhanu
20

Table of JAVA – Built in Exceptions


Following is the list of Java Unchecked RuntimeException

Handling Exceptions in Java


Following five keywords are used to handle an exception in Java:
1. try

MS bhanu
2. catch
3. finally
21
4. throw
5. throws

TRY –CATCH BLOCK


A method catches an exception using a combination of the try and catch keywords. A try/catch block is
placed around the code that might generate an exception. Code within a try/catch block is referred to as
protected code, and the syntax for using try/catch looks like the following:

A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in
protected code, the catch block (or blocks) that follows the try is checked. If the type of exception that
occurred is listed in a catch block, the exception is passed to the catch block much as an argument is passed
into a method parameter.
Example of Program without Exceptional Handling

MS bhanu
22

Multiple Catch Blocks:


A try block can be followed by multiple catch blocks, but when we use multiple catch statements it is
important that exception subclasses must come before any of their superclasses. The reason is “a catch
statement with superclass will catch exceptions of that type plus any of its subclass, thus causing a catch
statement with subclass exception a nonreachable code which is error in JAVA”.
Example:

MS bhanu
23

Finally Block
The finally keyword is used to create a block of code that follows a try block. A finally block of code always
executes, whether or not an exception has occurred. Using a finally block allows you to run any cleanup-
type statements that you want to execute, no matter what happens in the protected code.

MS bhanu
Throw Keyword
The throw keyword is used to explicitly throw an exception. We can throw either checked or unchecked
exception. The throw keyword is normally used to throw custom exception. 24
Throws Keyword
The throws keyword is used to declare the exception, it provide information to the programmer that there
may occur an exception so during call of that method, and programmer must use exceptional handling
mechanism. Throws keyword is also used to propagate checked exception.
Example
In this example, exception is created by extending Exception class and the custom exception is declared in
the method validate (int i)

Important Points in Exceptional Handling


 A catch clause cannot exist without a try statement.
 It is not compulsory to have finally clauses whenever a try/catch block is present.
 The try block cannot be present without either catch clause or finally clause.
 Any code cannot be present in between the try, catch, finally blocks.
Declaring your Own Exceptions
You can create your own exceptions in Java. Keep the following points in mind when writing your own
exception classes:
 All exceptions must be a child of Throwable.

MS bhanu
 If you want to write a checked exception that is automatically enforced by the Handle or Declare
Rule, you need to extend the Exception class.
25
 If you want to write a runtime exception, you need to extend the RuntimeException class.
Example to create custom exception is shown in the section above.

Multithreading
Multithreading is a conceptual programming concept where a program (process) is divided into two or more
subprograms (process), which can be implemented at the same time in parallel. A multithreaded program
contains two or more parts that can run concurrently. Each part of such a program is called a thread, and
each thread defines a separate path of execution. A process consists of the memory space allocated by the
operating system that can contain one or more threads. A thread cannot exist on its own; it must be a part of
a process.
There are two distinct types of Multitasking i.e. Processor-Based and Thread-Based multitasking.
Q: What is the difference between thread-based and process-based multitasking?
Ans: As both are types of multitasking there is very basic difference between the two. Process-Based
multitasking is a feature that allows your computer to run two or more programs concurrently. For example
you can listen to music and at the same time chat with your friends on Facebook using browser. In Thread-
based multitasking, thread is the smallest unit of code, which means a single program can perform two or
more tasks simultaneously. For example a text editor can print and at the same time you can edit text
provided that those two tasks are perform by separate threads.
Benefits of Multithreading
1. Enables programmers to do multiple things at one time
2. Programmers can divide a long program into threads and execute them in parallel which eventually
increases the speed of the program execution
3. Improved performance and concurrency
4. Simultaneous access to multiple applications
Life Cycle of Thread
A thread can be in any of the five following states
1. Newborn State: When a thread object is created a new thread is born and said to be in Newborn state.
2. Runnable State: If a thread is in this state it means that the thread is ready for execution and waiting for
the availability of the processor. If all threads in queue are of same priority then they are given time slots for
execution in round robin fashion
3. Running State: It means that the processor has given its time to the thread for execution. A thread keeps
running until the following conditions occurs
a. Thread give up its control on its own and it can happen in the following situations
i. A thread gets suspended using suspend() method which can only be revived with resume()
method

MS bhanu
ii. A thread is made to sleep for a specified period of time using sleep(time) method, where
time in milliseconds
iii. A thread is made to wait for some event to occur using wait () method. In this case a
thread can be scheduled to run again using notify () method. 26
b. A thread is pre-empted by a higher priority thread
4. Blocked State: If a thread is prevented from entering into runnable state and subsequently running state,
then a thread is said to be in Blocked state.
5. Dead State: A runnable thread enters the Dead or terminated state when it completes its task or otherwise
terminates.

Main Thread
Every time a Java program starts up, one thread begins running which is called as the main thread of the
program because it is the one that is executed when your program begins.
 Child threads are produced from main thread
 Often it is the last thread to finish execution as it performs various shut down operations
Creating a Thread
Java defines two ways in which this can be accomplished:
1. You can implement the Runnable interface. You can extend the Thread class, itself.
2. Create Thread by Implementing Runnable
MS bhanu
The easiest way to create a thread is to create a class that implements the Runnable interface. To implement
Runnable, a class need only implement a single method called run( ), which is declared like this:
27
public void run( )
You will define the code that constitutes the new thread inside run( ) method. It is important to
understand that run( ) can call other methods, use other classes, and declare variables, just like the main
thread can.
After you create a class that implements Runnable, you will instantiate an object of type Thread from within
that class. Thread defines several constructors. The one that we will use is shown here:
Thread(Runnable threadOb, String threadName);
Here threadOb is an instance of a class that implements the Runnable interface and the name of the new
thread is specified by threadName. After the new thread is created, it will not start running until you call its
start( ) method, which is declared within Thread. The start( ) method is shown here:
void start( );
Example to Create a Thread using Runnable Interface

Create Thread by Extending Thread


The second way to create a thread is to create a new class that extends Thread, and then to create an instance
of that class. The extending class must override the run( ) method,
Which is the entry point for the new thread. It must also call start( ) to begin execution of the new thread.

MS bhanu
Example to Create a Thread by Extending Thread Class
28

Thread Methods

MS bhanu
29

Example

MS bhanu
30

Use of Yield() Method


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

MS bhanu
As you can see in the output below, thread A gets started and when condition if(i==2) gets satisfied yield()
method gets evoked and the control is relinquished from thread A to thread B which run to its completion
and only after that thread a regain the control back.
31
Output

Output

MS bhanu
Use of sleep() Method
Causes the currently running thread to block for at least the specified number of milliseconds. You need to
handle exception while using sleep() method.
32

Use of suspend() and resume() method


A suspended thread can be revived by using the resume() method. This approach is useful when we want to
suspend a thread for some time due to certain reason but do not want to kill it.
Following is the example in which two threads C and A are created. Thread C is started ahead of
Thread A, but C is suspended using suspend() method causing Thread A to get hold of the processor
allowing it to run and when Thread C is resumed using resume() method it runs to its completion.
MS bhanu
33

MS bhanu
Thread Priority 34

Every Java thread has a priority that helps the operating system determine the order in which threads
are scheduled.
Java 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 very much platform dependent

In the above code, you can see Priorities of Thread is set to maximum for Thread A which lets it to run to
completion ahead of C which is set to minimum priority.
Output:

MS bhanu
Synchronization 35

When two or more threads need access to a shared resource, they need some way to ensure that the
resource will be used by only one thread at a time. The process by which this synchronization is achieved is
called thread synchronization. The synchronized keyword in Java creates a block of code referred to as a
critical section. Every Java object with a critical section of code gets a lock associated with the object. To
enter a critical section, a thread needs to obtain the corresponding object's lock.
synchronized(object)
{
// statements to be synchronized
}
Problem without using Synchronization
In the following example method updatesum() is not synchronized and access by both the threads
simultaneously which results in inconsistent output. Making a method synchronized, Java creates a
“monitor” and hands it over to the thread that calls the method first time. As long as the thread holds the
monitor, no other thread can enter the synchronized section of the code. Writing the method as
synchronized will make one thread enter the method and till execution is not complete no other thread can
get access to the method.

Example

MS bhanu
36

MS bhanu
JAVA INPUT /OUTPUT 37

Java I/O (Input and Output) is used to process the input and produce the output.
Java uses the concept of stream to make I/O operation fast. The java.io package contains all the classes
required for input and output operations.
We can perform file handling in java by Java I/O API.

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 console.
1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream
Let's see the code to print output and error message to the console.
1. System.out.println("simple message");
2. System.err.println("error message");
Let's see the code to get input from console.
1. int i=System.in.read();//returns ASCII code of 1st character
2. System.out.println((char)i);//will print the character

Java.io package
This package provides for system input and output through data streams, serialization and the file system.
Unless otherwise noted, passing a null argument to a constructor or method in any class or interface in this
package will cause a NullPointerException to be thrown.
The classes in the package are primarily abstract classes and stream-oriented that define methods and
subclasses which allow bytes to be read from and written to files or other input and output sources.
For reading the stream:
Open the stream
Read information
Close the stream
For writing in stream:
Open the stream
Write information
Close the stream

MS bhanu
Java.io.FileInputStream Class in Java 38

FileInputStream is useful to read data from a file in the form of sequence of bytes. FileInputStream is meant
for reading streams of raw bytes such as image data. For reading streams of characters, consider using
FileReader.
Constructor and Description
 FileInputStream(File file) :Creates an input file stream to read from the specified File object.
 FileInputStream(FileDescriptor fdobj) :Creates an input file stream to read from the specified file
descriptor.
 FileInputStream(String name) :Creates an input file stream to read from a file with the specified
name.
Important Methods:
1. int read() : Reads a byte of data from this input stream.
Syntax: public int read( ) throws IOException

2. int read(byte[] b) :Reads up to b.length bytes of data from this input stream into an array of bytes.

Syntax:public int read(byte[] b) throws IOException

3. int read(byte[] b, int off, int len) : Reads up to len bytes of data from this input stream into an array
of bytes.

Syntax:public int read(byte[] b, int off,int len) throws IOException

4. long skip(long n) : Skips over and discards n bytes of data from the input stream.

Syntax:public long skip(long n) throws IOException

5. int available() : Returns an estimate of the number of remaining bytes that can be read (or skipped
over) from this input stream .

Syntax:public int available() throws IOException

6. void close() : Closes this file input stream and releases any system resources associated with the
stream.

Syntax:public void close() throws IOException

7. FileDescriptor getFD() :Returns the FileDescriptor object that represents the connection to the actual
file in the file system being used by this FileInputStream.

Syntax :public final FileDescriptor getFD() throws IOException

8. FileChannel getChannel() :Returns the unique FileChannel object associated with this file input
stream.
MS bhanu
Syntax :public FileChannel getChannel() 39

9. void finalize() :Ensures that the close method of this file input stream is called when there are no
more references to it.

Syntax :protected void finalize() throws IOException

Creating a file using FileOutputStream


FileOutputStream class belongs to byte stream and stores the data in the form of individual bytes. It can be
used to create text files. A file represents storage of data on a second storage media like a hard disk or CD.
Whether or not a file is available or may be created depends upon the underlying platform. Some platforms,
in particular, allow a file to be opened for writing by only one FileOutputStream (or other file-writing
objects) at a time. In such situations, the constructors in this class will fail if the file involved is already
open.
FileOutputStream is meant for writing streams of raw bytes such as image data. For writing streams of
characters, consider using FileWriter.
Important methods:
 void close() : Closes this file output stream and releases any system resources associated with this
stream.
 protected void finalize() : Cleans up the connection to the file, and ensures that the close method of
this file output stream is called when there are no more references to this stream.
 void write(byte[] b) : Writes b.length bytes from the specified byte array to this file output stream.
 void write(byte[] b, int off, int len) : Writes len bytes from the specified byte array starting at offset
off to this file output stream.
 void write(int b) : Writes the specified byte to this file output stream.
Following steps are to be followed to create a text file that stores some characters (or text):
1. Reading data: First of all, data should be read from the keyboard. For this purpose, associate the
keyboard to some input stream class. The code for using DataInputSream class for reading data from
the keyboard is as:

DataInputStream dis =new DataInputStream(System.in);

Here System.in represent the keyboard which is linked with DataInputStream object
2. Send data to OutputStream: Now , associate a file where the data is to be stored to some output
stream. For this , take the help of FileOutputStream which can send data to the file. Attaching the
file.txt to FileOutputStream can be done as:

FileOutputStream fout=new FileOutputStream(“file.txt”);

MS bhanu
3. Reading data from DataInputStream: The next step is to read data from DataInputStream and
write it into FileOutputStream . It means read data from dis object and write it into fout object, as
shown here:
40

ch=(char)dis.read();
fout.write(ch);
4. Close the file: Finally, any file should be closed after performing input or output operations on it,
else the data of the may be corrupted. Closing the file is done by closing the associated streams. For
example, fout.close(): will close the FileOutputStream ,hence there is no way to write data into the file.
Implementation:
//Java program to demonstrate creating a text file using FileOutputStream
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
class Create_File
{
public static void main(String[] args) throws IOException
{
DataInputStream dis=new DataInputStream(System.in);
FileOutputStream fout=new FileOutputStream("file.txt");
BufferedOutputStream bout=new BufferedOutputStream(fout,1024);
System.out.println("Enter text (@ at the end):");
char ch;
while((ch=(char)dis.read())!='@')
{
bout.write(ch);
}
bout.close();
}
}

Java.io.BufferedInputStream class in Java


A BufferedInputStream adds functionality to another input stream-namely, the ability to buffer the input and
to support the mark and reset methods. When the BufferedInputStream is created, an internal buffer array is
created. As bytes from the stream are read or skipped, the internal buffer is refilled as necessary from the
contained input stream, many bytes at a time.
Constructor and Description
MS bhanu
 BufferedInputStream(InputStream in) : Creates a BufferedInputStream and saves its argument,
the input stream in, for later use. 41

 BufferedInputStream(InputStream in, int size) : Creates a BufferedInputStream with the


specified buffer size, and saves its argument, the input stream in, for later use.
Methods:
1. int available() : Returns an estimate of the number of bytes that
can be read (or skipped over) from this input stream without
blocking by the next invocation of a method for this input stream.

Syntax:public int available() throws IOException

2. void close() : Closes this input stream and releases any system resources associated with the stream.

Syntax:public void close() throws IOException

3. void mark(int readlimit) : Marks the current position in this input stream.

Syntax:public void mark(int readlimit)

4. boolean markSupported() : Tests if this input stream supports the mark and reset methods.

Syntax:public boolean markSupported()

5. int read() : Reads the next byte of data from the input stream.

Syntax:public int read() throws IOException

6. int read(byte[] b, int off, int len) : Reads bytes from this byte-input stream into the specified byte
array, starting at the given offset.

Syntax:public int read(byte[] b, int off, int len) throws IOException

7. void reset() : Repositions this stream to the position at the time the mark method was last called on
this input stream.

Syntax:public void reset() throws IOException

8. long skip(long n) :Skips over and discards n bytes of data from this input stream

Syntax:public long skip(long n) throws IOException

Program:
// Java program to demonstrate working of BufferedInputStream
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
// Java program to demonstrate BufferedInputStream methods MS bhanu
class BufferedInputStreamDemo
42
{
public static void main(String args[]) throws IOException
{
FileInputStream fin = new FileInputStream("file1.txt");
BufferedInputStream bin = new BufferedInputStream(fin);
System.out.println("Number of remaining bytes:" +bin.available());
boolean b=bin.markSupported();
if (b)
bin.mark(bin.available());
bin.skip(4);
System.out.println("FileContents :");
int ch;
while ((ch=bin.read()) != -1)
System.out.print((char)ch);
bin.reset();
while ((ch=bin.read()) != -1)
System.out.print((char)ch);
fin.close();
}
}
Output:

Number of remaining bytes:47


FileContents :
is my first line
This is my second line
This is my first line
This is my second lin

Java.io.BufferedOutputStream class in Java


Java.io.BufferedOutputStream class implements a buffered output stream. By setting up such an output
stream, an application can write bytes to the underlying output stream without necessarily causing a call to
the underlying system for each byte written.
Fields
 protected byte[] buf: The internal buffer where data is stored.
 protected int count: The number of valid bytes in the buffer.
Constructor and Description MS bhanu
 BufferedOutputStream(OutputStream out) : Creates a new buffered output stream to write data to
the specified underlying output stream. 43

 BufferedOutputStream(OutputStream out, int size) : Creates a new buffered output stream to


write data to the specified underlying output stream with the specified buffer size.
Methods:
 void flush() : Flushes this buffered output stream.

Syntax :public void flush() throws IOException

 void write(byte[] b, int off, int len) : Writes len bytes from the specified byte array starting at offset
off to this buffered output stream.

Syntax : void write(byte[] b, int off, int len)

Program:
//Java program demonstrating BufferedOutputStream
import java.io.*;
class BufferedOutputStreamDemo
{
public static void main(String args[])throws Exception
{
FileOutputStream fout = new FileOutputStream("f1.txt");
BufferedOutputStream bout = new BufferedOutputStream(fout);
for(int i = 65; i < 75; i++)
{
bout.write(i);
}
byte b[] = { 75, 76, 77, 78, 79, 80 };
bout.write(b);
bout.flush();
bout.close();
fout.close();
}
}
Output :
ABCDEFGHIJKLMNOP

Java.io.RandomAccessFile Class
The Java.io.RandomAccessFile class file behaves like a large array of bytes stored in the file
system.Instances of this class support both reading and writing to a random access file.
MS bhanu
Class declaration
44
Following is the declaration for Java.io.RandomAccessFile class −

public class RandomAccessFile


extends Object
implements DataOutput, DataInput, Closeable

Methods of RandomAccessFile Class :


1. read() : java.io.RandomAccessFile.read() reads byte of data from file. The byte is returned as an
integer in the range 0-255

Syntax :public int read()

2. read(byte[] b) java.io.RandomAccessFile.read(byte[] b) reads bytes upto b.length fron the buffer.

Syntax :public int read(byte[] b)

3. read((byte[] b, int offset, int len) : java.io.RandomAccessFile.read((byte[] b, int offset, int


len) reads bytes initialising from offset positon upto b.length fron the buffer.

Syntax :public int read(byte[] b, int offset, int len)

4. readBoolean() : java.io.RandomAccessFile.readBoolean() reads a boolean from the file.

Syntax :public final boolean readBoolean()

5. readByte() : java.io.RandomAccessFile.readByte() reads a signed eight-bit value from file, start


reading from the File Pointer.

Syntax :public final byte readByte()

6. readChar() : java.io.RandomAccessFile.readChar() reads a character from the file, start reading


from the File Pointer.

Syntax :public final char readChar()

7. readDouble() : java.io.RandomAccessFile.readDouble() reads a double value from the file, start


reading from the File Pointer.

Syntax :public final double readDouble()

8. readFloat() : java.io.RandomAccessFile.readFloat() reads a float value from the file, start reading
from the File Pointer.

Syntax :public final double readFloat()

9. readFully(byte[] b) : java.io.RandomAccessFile.readFully(byte[] b) reads bytes upto b.length


from the buffer, start reading from the File Pointer.

MS bhanu
Syntax :public final void readFully(byte[] b) 45

10. readInt() : java.io.RandomAccessFile.readInt() reads a signed 4 bytes integer from the file, start
reading from the File Pointer.
11. readFully(byte[] b, int offset, int len) : java.io.RandomAccessFile.readFully(byte[] b, int offset,
int len) reads bytes initialising from offset positon upto b.length from the buffer, start reading from the
File Pointer.
12. readLong() : java.io.RandomAccessFile.readLong() reads a signed 64 bit integer from the file,
start reading from the File Pointer.

Java.util.Scanner Class
The java.util.Scanner class is a simple text scanner which can parse primitive types and strings using
regular expressions.Following are the important points about Scanner −
 A Scanner breaks its input into tokens using a delimiter pattern, which by default matches
whitespace.
 A scanning operation may block waiting for input.
 A Scanner is not safe for multithreaded use without external synchronization.

Class declaration
Following is the declaration for java.util.Scanner class −

public final class Scanner


extends Object
implements Iterator<String>

Commonly used methods of Scanner class


There is a list of commonly used Scanner class methods:

Method Description

public String next() it returns the next token from the scanner.

public String nextLine() it moves the scanner position to the next line and returns the value as a
string.

public byte nextByte() it scans the next token as a byte.

public short nextShort() it scans the next token as a short value.

public int nextInt() it scans the next token as an int value.

public long nextLong() it scans the next token as a long value.

public float nextFloat() it scans the next token as a float value.

MS bhanu
public double it scans the next token as a double value. 46
nextDouble()
Example
import java.util.Scanner;
class ScannerTest
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter your rollno");
int rollno=sc.nextInt();
System.out.println("Enter your name");
String name=sc.next();
System.out.println("Enter your fee");
double fee=sc.nextDouble();
System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee);
sc.close();
}
}

Output:

Enter your rollno


111
Enter your name
Ratan
Enter
450000
Rollno:111 name:Ratan fee:450000

MS bhanu

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy