Java Unit 4 Complete
Java Unit 4 Complete
com 1
www.Jntufastupdates.com 2
www.Jntufastupdates.com 3
www.Jntufastupdates.com 4
www.Jntufastupdates.com 5
www.Jntufastupdates.com 6
www.Jntufastupdates.com 7
www.Jntufastupdates.com 8
www.Jntufastupdates.com 9
www.Jntufastupdates.com 10
www.Jntufastupdates.com 11
www.Jntufastupdates.com 12
www.Jntufastupdates.com 13
www.Jntufastupdates.com 14
www.Jntufastupdates.com 15
www.Jntufastupdates.com 16
www.Jntufastupdates.com 17
www.Jntufastupdates.com 18
www.Jntufastupdates.com 19
www.Jntufastupdates.com 20
www.Jntufastupdates.com 21
www.Jntufastupdates.com 22
www.Jntufastupdates.com 23
www.Jntufastupdates.com 24
www.Jntufastupdates.com 25
Exception Handling
The exception handling in java is one of the powerful mechanism to handle the runtime
errors so that normal flow of the application can be maintained.
What is exception
In java, exception is an event that disrupts the normal flow of the program. It is an object which is
thrown at runtime.
The core advantage of exception handling is to maintain the normal flow of the application.
Exception normally disrupts the normal flow of the application that is why we use exception
handling.
Types of Exception
There are mainly two types of exceptions: checked and unchecked where error is considered as
unchecked exception. The sun microsystem says there are three types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error
1) Checked Exception: The classes that extend Throwable class except RuntimeException and Error
are known as checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked
at compile-time.
2) Unchecked Exception: The classes that extend RuntimeException are known as unchecked
exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptionsarenotchecked at compile-timeratherthey arechecked at runtime.
Java try block is used to enclose the code that might throw an exception. It must be used within
the method.
1. try{
2. //code that may throw exception
3. }catch(Exception_class_Name ref){}
1. try{
2. //code that may throw exception
3. }finally{}
Java catch block is used to handle the Exception. It must be used after the try block only.
As displayed in the above example, rest of the code is not executed (in such case, rest of the
code... statement is not printed).
There can be 100 lines of code after exception. So all the code after exception will not be
executed.
Now, as displayed in the above example, rest of the code is executed i.e. rest of the code...
statement is printed.
If you have to perform different tasks at the occurrence of different Exceptions, use java multi
catch block.
Output:task1 completed
rest of the code...
class Excep6{
public static void main(String args[]){
try{
try{
System.out.println("going to divide");
int b =39/0;
}catch(ArithmeticException e){System.out.println(e);}
Java finally block is a block that is used to execute important code such as closing connection,
stream etc.
Case 1
Let's see the java finally example where exception doesn't occur.
class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Output:5
finally block is always executed
rest of the code...
We can throw either checked or uncheked exception in java by throw keyword. The throw
keyword is mainly used to throw custom exception. We will see custom exceptions later.
1. throw exception;
In this example, we have created the validate method that takes integer value as a parameter. If
the age is less than 18, we are throwing the ArithmeticException otherwise print a message
welcome to vote.
Output:
The Java throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception so it is better for the programmer to provide the
exception handling code so that normal flow can be maintained.
Exception Handling is mainly used to handle the checked exceptions. If there occurs any
unchecked exception such as NullPointerException, it is programmers fault that he is not
performing check up before the code being used.
Let's see the example of java throws clause which describes that checked exceptions can be
propagated by throws keyword.
import java.io.IOException;
class Testthrows1{
void m()throws IOException{
throw new IOException("device error");//checked exception
If you are creating your own Exception that is known as custom exception or user-defined
exception. Java custom exceptions are used to customize the exception according to user need.
By the help of custom exception, you can have your own exception and message.
These streams can be different in how they are handling data and the type of data they are handling.
1. Character Streams:
Character streams are designed to address character based records, which includes textual records
inclusive of letters, digits, symbols, and other characters. These streams are represented by way of
training that quit with the phrase "Reader" or "Writer" of their names, inclusive of FileReader,
BufferedReader, FileWriter, and BufferedWriter.
Character streams offer a convenient manner to read and write textual content-primarily based
information due to the fact they mechanically manage character encoding and decoding. They
convert the individual statistics to and from the underlying byte circulation the usage of a particular
individual encoding, such as UTF-eight or ASCII.It makes person streams suitable for operating with
textual content files, analyzing and writing strings, and processing human-readable statistics.
2. Byte Streams:
Byte streams are designed to deal with raw binary data, which includes all kinds of data,
including characters, pictues, audio, and video. These streams are represented through
cclasses that cease with the word "InputStream" or "OutputStream" of their names,along
with FileInputStream,BufferedInputStream, FileOutputStream and BufferedOutputStream.
Byte streams offer a low-stage interface for studying and writing character bytes or blocks of
bytes. They are normally used for coping with non-textual statistics, studying and writing
files of their binary form, and running with network sockets. Byte streams don't perform any
individual encoding or deciphering. They treat the data as a sequence of bytes and don't
interpret it as characters.
Here are the some of the differences listed:
1. import java.io.CharArrayReader;
2. import java.io.IOException;
3.
4. public class CharacterStreamExample
5. {
6. public static void main(String[] args) {
7. // Creates an array of characters
8. char[] array = {'H','e','l','l','o'};
9. try {
10. CharArrayReader reader=new CharArrayReader(array);
11. System.out.print("The characters read from the reader:");
12. int charRead;
13. while ((charRead=reader.read())!=-1) {
14. System.out.print((char)charRead+",");
15. }
16. reader.close();
17. } catch (IOException ex)
18. {
19. ex.printStackTrace();
20. }
21. }
22. }
23. Output: The characters read from the reader:H,e,l,l,o,
1. import java.io.ByteArrayInputStream;
2.
3. public class ByteStreamExample
4. {
5. public static void main(String[] args)
6. {
7. // Creates the array of bytes
8. byte[] array = {10,20,30,40};
9. try {
10. ByteArrayInputStream input=new ByteArrayInputStream(array);
11. System.out.println("The bytes read from the input stream:");
12. for (int i=0;i<array.length;i++)
13. {
14. // Reads the bytes
15. int data=input.read();
16. System.out.print(data+",");
17. }
18. input.close();
19. } catch (Exception ex)
20. {
21. ex.getStackTrace();
22. }
23. }
24. }
The File class have several methods for working with directories and files such as creating
new directories or files, deleting and renaming directories or files, listing the contents of a
directory etc.
Fields
Constructors
Java File Example 1
1. import java.io.*;
2. public class FileDemo {
3. public static void main(String[] args) {
4.
5. try {
6. File file = new File("javaFile123.txt");
7. if (file.createNewFile()) {
8. System.out.println("New File is created!");
9. } else {
10. System.out.println("File already exists.");
11. }
12. } catch (IOException e) {
13. e.printStackTrace();
14. }
15.
16. }
17. }
Output: New File is created!
Java File Example 2
1. import java.io.*;
2. public class FileDemo2 {
3. public static void main(String[] args) {
4.
5. String path = "";
6. boolean bool = false;
7. try {
8. // createing new files
9. File file = new File("testFile1.txt");
10. file.createNewFile();
11. System.out.println(file);
12. // createing new canonical from file object
13. File file2 = file.getCanonicalFile();
14. // returns true if the file exists
15. System.out.println(file2);
16. bool = file2.exists();
17. // returns absolute pathname
18. path = file2.getAbsolutePath();
19. System.out.println(bool);
20. // if file exists
21. if (bool) {
22. // prints
23. System.out.print(path + " Exists? " + bool);
24. }
25. } catch (Exception e) {
26. // if any error occurs
27. e.printStackTrace();
28. }
29. }
30. }
31. Output:
32. testFile1.txt
33. /home/Work/Project/File/testFile1.txt
34. true
35. /home/Work/Project/File/testFile1.txt Exists? true
Java Scanner
Scanner class in Java is found in the java.util package. Java provides various ways to read
input from the keyboard, the java.util.Scanner class is one of them.
The Java Scanner class breaks the input into tokens using a delimiter which is whitespace
by default. It provides many methods to read and parse various primitive values.
The Java Scanner class is widely used to parse text for strings and primitive types using a
regular expression. It is the simplest way to get input in Java. By the help of Scanner in
Java, we can get input from the user in primitive types such as int, long, double, byte,
float, short, etc.
The Java Scanner class provides nextXXX() methods to return the type of value such as
nextInt(), nextByte(), nextShort(), next(), nextLine(), nextDouble(), nextFloat(),
nextBoolean(), etc. To get a single character from the scanner, you can call next().charAt(0)
method which returns a single character.
Example 1 : Java Scanner where we are getting a single input from the user. Here, we
are asking for a string through in.nextLine() method.
1. import java.util.*;
2. public class ScannerExample {
3. public static void main(String args[]){
4. Scanner in = new Scanner(System.in);
5. System.out.print("Enter your name: ");
6. String name = in.nextLine();
7. System.out.println("Name is: " + name);
8. in.close();
9. }
10. }