Vxl Java Ppt2
Vxl Java Ppt2
Syntax:-
package nameOfPackage;
Step 7)for suppose we want to create a sub package p2 within our existing java package p1. Then we will
modify our code as
package p1.p2
class c1
{
public void m1()
{
System.out.println("m1 of c1");
}}
Step 8) Compile the file
Step 9) To execute the above code use the fully qualified name of the class i.e. the package name
followed by the sub-package name followed by the class name : ouput
Output :
How to access package from another package? Example of package that import the packagename.*
There are 2 ways to access the package from outside the package. //save by A.java
import package.*; package pack;
import package.classname; public class A{
1) Using packagename.* public void msg(){System.out.println("Hello");}
If you use package.* then all the classes and interfaces of this }
package will be accessible but not subpackages. //save by B.java
The import keyword is used to make the classes and interface package mypack;
of another package accessible to the current package. import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
} }
Output: Hello
Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;
class B{
public static void main(String args[]) {
A obj = new A();
obj.msg();
Output: Hello
} }
final, finally and finalize:
Throw :
Java throw keyword is used throw an exception explicitly in the code, inside the function or the block
of code.
Using throw keyword, we can only propagate unchecked exception
The throw keyword is followed by an instance of Exception
throw is used within the method body.
We are allowed to throw only one exception at a time i.e. we cannot throw multiple exceptions.
It is mainly used to throw a custom exception
Syntax : throw new ArithmeticException("Person is not eligible to vote");
Throws keyword:
Java throws keyword is used in the method signature to declare an exception which might be thrown
by the function while the execution of the code.
Using throws keyword, we can declare both checked and unchecked exceptions. However, the throws
keyword can be used to propagate checked exceptions only.
The throws keyword is followed by class names of Exceptions to be thrown.
throws is used with the method signature.
We can declare multiple exceptions using throws keyword that can be thrown by the method. For
example, main() throws IOException, SQLException.
Syntax: return_type method_name() throws exception_class_name
{
//method code
}
Throws keyword:
Java throws keyword is used in the method signature to declare an exception which might be thrown
by the function while the execution of the code.
Using throws keyword, we can declare both checked and unchecked exceptions. However, the throws
keyword can be used to propagate checked exceptions only.
The throws keyword is followed by class names of Exceptions to be thrown.
throws is used with the method signature.
We can declare multiple exceptions using throws keyword that can be thrown by the method. For
example, main() throws IOException, SQLException.
Syntax: return_type method_name() throws exception_class_name
{
//method code
}
Java Exceptions:
An exception is an unexpected event that occurs during program execution. It affects the flow of
the program instructions which can cause the program to terminate abnormally.
An exception can occur for many reasons. Some of them are:
Invalid user input
Device failure
Loss of network connection
Physical limitations (out of disk memory)
Code errors
Opening an unavailable file
Errors represent not-recoverable conditions such as Java virtual machine (JVM) running out of
memory, memory leaks, stack overflow errors, library incompatibility, infinite recursion, etc.
Errors are usually beyond the control of the programmer and we should not try to handle errors.
There are two types of errors:
1. Compile time errors
2. Runtime errors
Compile time errors can be again classified again into two types:
1. Syntax Errors
2. Semantic Errors
Syntax Errors Example:
for example Instead of declaring int a; you mistakenly declared it as in a; for which compiler will
throw an error.
Example: You have declared a variable int a; and after some lines of code you again declare an
integer as int a;. All these errors are highlighted when you compile the code.
Runtime Errors Example:
A Runtime error is called an Exceptions error. It is any event that interrupts the normal flow of
program execution.
Example for exceptions are, arithmetic exception, Nullpointer exception, Divide by zero
exception, etc.
Exceptions can be caught and handled by the program.
When an exception occurs within a method, it creates an object. This object is called the
exception object.
It contains information about the exception such as the name and description of the exception
and state of the program when the exception occurred.
Java Exception hierarchy
In the above image - the Throwable class is the root class in the hierarchy.
Note :An exception that occurs during the execution of a program is called an unchecked or a runtime exception. The
main cause of unchecked exceptions is mostly due to programming errors like attempting to access an element with an
invalid index, calling the method with illegal arguments, etc.
1. RuntimeException
A runtime exception happens due to a programming error. They are also known as unchecked
exceptions.
These exceptions are not checked at compile-time but run-time. Some of the common runtime
exceptions are:
Improper use of an API - IllegalArgumentException
Null pointer access (missing the initialization of a variable) - NullPointerException
Out-of-bounds array access - ArrayIndexOutOfBoundsException
Dividing a number by 0 - ArithmeticException
IOException
An IOException is also known as a checked exception. They are checked by the
compiler at the compile-time and the programmer is prompted to handle these exceptions.
Some of the examples of checked exceptions are:
Trying to open a file that doesn’t exist results in FileNotFoundException
Trying to read past the end of a file
Try Catch Block
Java provides an inbuilt exceptional handling.
The normal code goes into a TRY block.
The exception handling code goes into the CATCH block
In our example, TRY block will contain the code to connect to the server. CATCH block will contain the
code to connect to the backup server.
In case the server is up, the code in the CATCH block will be ignored. In case the server is down, an
exception is raised, and the code in catch block will be executed.
class connect{
if(Server Up){
// code to connect to server
}
else{
// code to connect to BACKUP server
}
}
Step 1: Save the file & compile the code. Run the program using command, java JavaException
Step 2) An Arithmetic Exception – divide by zero is shown as below for line # 5 and line # 6 is never
executed
class JavaException {
public static void main(String args[]) {
int d = 0;
int n = 20;
try {
int fraction = n / d;
System.out.println("This line will not be Executed");
} catch (ArithmeticException e) {
System.out.println("In the catch Block due to Exception = " + e);
}
System.out.println("End Of Main");
}
}
Note: The AritmeticException Object “e” carries information about the exception that has
occurred which can be useful in taking recovery actions.
Java finally block
In Java, the finally block is always executed no matter whether there is an exception or not.
The finally block is optional. And, for each try block, there can be only one finally block.
The basic syntax of finally block is: example :
class Main {
try {
public static void main(String[] args) {
//code try {
// code that generates exception
}
int divideByZero = 5 / 0;
catch (ExceptionType1 e1) { }
catch (ArithmeticException e) {
// catch block
System.out.println("ArithmeticException => " +
} e.getMessage());
}
finally {
finally {
// finally block always executes System.out.println("This is the finally block");
} } } Output
}
ArithmeticException => / by zero
This is the finally block
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the
CPU.
Multitasking can be achieved in two ways:
Process-based Multitasking (Multiprocessing)
Thread-based Multitasking (Multithreading)
Process-based Multitasking (Multiprocessing)
Each process has an address in memory. In other words, each process allocates a separate
memory area. And A process is heavyweight. And the Cost of communication between the process is
high.
Switching from one process to another requires some time for saving and loading registers
, memory maps, updating lists, etc.
Multithreading in Java
Multithreading in Java is a process of executing multiple threads simultaneously.
A thread is a lightweight sub-process, the smallest unit of processing.
Multiprocessing and multithreading, both are used to achieve multitasking.
However, we use multithreading than multiprocessing because threads use a shared memory area. They
don't allocate separate memory area so saves memory, and context-switching between the threads takes
less time than process.
Java Multithreading is mostly used in games, animation, etc.
Advantages of Java Multithreading
1) It doesn't block the user because threads are independent and you can perform multiple operations at
the same time.
2) You can perform many operations together, so it saves time.
3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single thread.
Thread-based Multitasking (Multithreading)
Threads share the same address space.
A thread is lightweight.
Cost of communication between the thread is low.
Thread in java
A thread is a lightweight sub process, the smallest unit of processing. It is a separate path of execution.
Threads are independent. If there occurs exception in one thread, it doesn't affect other threads. It uses a
shared memory area.
In the above figure, a thread is executed inside the
process. There is context-switching between the threads.
There can be multiple processes inside the OS
, and one process can have multiple threads.
Note:A thread in Java is the direction or path that is taken while a program is being
executed. Generally, all the programs have at least one thread, known as the main thread, that is
provided by the JVM or Java Virtual Machine at the starting of the program’s execution. Ie when the
main thread is provided, the main() method is invoked by the main thread.
How to create a thread in Java:
There are two ways to create a thread:
By extending Thread class
By implementing Runnable interface.
Thread class:
Thread class provide constructors and methods to create and perform operations on a thread.
Thread class extends Object class and implements Runnable interface.
Commonly used Constructors of Thread class:
• Thread()
• Thread(String name)
• Thread(Runnable r)
• Thread(Runnable r,String name)
Commonly used methods of Thread class:
public void run(): is used to perform action for a thread.
public void start(): starts the execution of the thread.JVM calls the run() method on the thread.
public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily
cease execution) for the specified number of milliseconds.
Creating a thread by Extending java.lang.Thread class
In this case, a thread is created by a new class that extends the Thread class, creating an
instance of that class. The run() method includes the functionality that is supposed to be
implemented by the Thread.
Examples to create a thread by extending java.lang.Thread class.
Filename: Multi.java
class Multi extends Thread
{
public void run(){
for( int i=0;i<10;i++) {
System.out.println("thread is running...");
} }
Class Threaddemo {
public static void main(String args[]) {
Multi t1=new Multi();
t1.start();
for( int i=0;i<10;i++)
{ s.o.pn(“ main thread running…”); }
} Note :Here, start() is used to create a new thread and to make
} it runnable. The new thread begins inside the void run()
Output: method.
thread is running...
Implementing Runnable interface
This is the easy method to create a thread among the two. In this case, a class is created
to implement the runnable interface and then the run() method.
The code for executing the Thread should always be written inside the run() method.
FileName: Multi3.java
class Multi3 implements Runnable{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
t1.start();
} }
If you are not extending the Thread class, your class object
would not be treated as a thread object. So you need to
explicitly create the Thread class object. We are passing the
Can we start a thread twice:
No. After starting a thread, it can never be started again. If you does so, an
IllegalThreadStateException is thrown. In such case, thread will run once but for second time, it will
throw exception.
public class TestThreadTwice1 extends Thread{
public void run(){
System.out.println("running...");
}
public static void main(String args[]){
TestThreadTwice1 t1=new TestThreadTwice1();
t1.start();
t1.start();
} }
Java Thread stop() method
The stop() method of thread class terminates the thread execution. Once a thread is stopped, it
cannot be restarted by start() method.
Syntax
public final void stop()
public final void stop(Throwable obj)
Life Cycle of a Thread
A thread goes through various stages in its life cycle. For example, a thread is born, started, runs,
and then dies.
The following diagram shows the complete life cycle of a thread:
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 − A thread transitions/moves 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.
Thread Priorities
Every Java thread has a priority that helps the operating system determine the order in
which threads are scheduled.
Java thread 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.
Thread Scheduler in Java
A component of Java that decides which thread to run or execute and which thread to wait
is called a thread scheduler in Java.
In Java, a thread is only chosen by a thread scheduler if it is in the runnable state. However, if there is
more than one thread in the runnable state, it is up to the thread scheduler to pick one of the threads
and ignore the other ones. There are some criteria that decide which thread will execute first. There
are two factors for scheduling a thread i.e. Priority and Time of arrival.
Time of Arrival: Suppose two threads of the same priority enter the runnable state, then priority
cannot be the factor to pick a thread from these two threads. In such a case, arrival time of thread is
considered by the thread scheduler. A thread that arrived first gets the preference over the other
threads.
Daemon Thread in Java
Daemon thread in Java is a service provider thread that provides services to the user thread. Its
life depend on the mercy of user threads i.e. when all the user threads dies, JVM terminates this
thread automatically.
There are many java daemon threads running automatically e.g. gc, finalizer etc.
It provides services to user threads for background supporting tasks. It has no role in life than to
serve user threads.
Its life depends on user threads.
It is a low priority thread.
The sole purpose of the daemon thread is that it provides services to user thread for background
supporting task. If there is no user thread, why should JVM keep running this thread. That is why
JVM terminates the daemon thread if there is no user thread.
Methods for Java Daemon thread by Thread class
The java.lang.Thread class provides two methods for java daemon thread.
JDBC has four major components that are used for the
interaction with the database.
JDBC API
JDBC Test Suite
JDBC Driver Manger
JDBC ODBC Bridge Driver
JDBC API: JDBC API provides various interfaces and methods to establish easy connection with different
databases.
java.sql.*;
JDBC Test suite: JDBC Test suite facilitates the programmer to test the various operations such as
deletion, updation, insertion that are being executed by the JDBC Drivers.
JDBC Driver manager: JDBC Driver manager loads the database-specific driver into an application in
order to establish the connection with the database. The JDBC Driver manager is also used to make the
database-specific call to the database in order to do the processing of a user request.
JDBC-ODBC Bridge Drivers: JDBC-ODBC Bridge Drivers are used to connect the database drivers to
the database. The bridge does the translation of the JDBC method calls into the ODBC method call. It
makes the usage of the sun.jdbc.odbc package that encompasses the native library in order to access the
ODBC (Open Database Connectivity) characteristics.
Architecture of JDBC
1) Application: It is the Java servlet or an applet that communicates with the data source.
2) The JDBC API: It allows the Java programs to perform the execution of the SQL statements and
then get the results.
A few of the crucial interfaces and classes defined in the JDBC API are the following:
Drivers DriverManager Statement
Connection ResultSet SQL data
DriverManager: DriverManager plays a crucial role in the architecture of JDBC.
It uses database-specific drivers to connect the enterprise applications to various databases.
4) JDBC drivers: To interact with a data source with the help of the JDBC, one needs a JDBC
driver which conveniently interacts with the respective data source.
Different Types of Architecture of JDBC
The architecture of the JDBC consists of two and three tiers model in order to access the given
database.
Two-tier model: In this model, the application interacts directly with the source of data. The JDBC
driver establishes the interaction between the data source and the application. When a query is sent
by the user to the data source, the reply of those sent queries is sent directly to the user.
Three-tier model: In this model, the queries of the user are being sent to the middle-tier services,
from where the commands are sent again to the source of data. The answers to those queries are
reverted to the middle tier, and from there, it is again sent to the user.
Java Database Connectivity :
There are 5 steps to connect any java application with the database using JDBC. These steps
are as follows:
Register the driver class
Create the connection object
Create the Statement object
Execute the query
Close the connection object
Register the driver class
The forName() method of Class class is used to register the driver class. This method is used to
dynamically load the driver class.
Example to register the OracleDriver class
Here, Java program is loading oracle driver to esteblish database connection.
Class.forName("oracle.jdbc.driver.OracleDriver");
Create the connection object
The getConnection() method of DriverManager class is used to establish connection
with the database.
Example to establish connection with the Oracle database
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","password");
Create the Statement object
The createStatement() method of Connection interface is used to create statement. The
object of statement is responsible to execute queries with the database.
Syntax of createStatement() method
public Statement createStatement()throws SQLException
Example to create the statement object
Statement stmt=con.createStatement();
Execute the query
The executeQuery() method of Statement interface is used to execute queries to the
database. This method returns the object of ResultSet that can be used to get all the records of a
table.
Example to execute query:
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
Close the connection object
By closing connection object statement and ResultSet will be closed automatically.
The close() method of Connection interface is used to close the connection.
con.close();
import java.sql.*;
class OracleCon {
public static void main(String args[]) {
try{
//step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");
//step2 create the connection object
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
//step3 create the statement object
Statement stmt=con.createStatement();
//step4 execute query
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
//step5 close the connection object
con.close();
} catch(Exception e) { System.out.println(e); }
} }
Streams in java
Java provides I/O Streams to read and write data where, a Stream represents an input source or an
output destination which could be a file, i/o devise, other program etc.
Streams of 2 types :
InputStream − This is used to read data from a source.
OutputStream − This is used to write data to a destination.
Based on the data they handle there are two types of streams −
Byte Streams − These handle data in bytes (8 bits) i.e., the byte stream classes read/write data of 8
bits. Using these you can store characters, videos, audios, images etc.
Character Streams − These handle data in 16 bit Unicode. Using these you can read and write text
data only.
Standard Streams
Java provides 3 standard streams representing the input and, output devices:
Standard Input − This is used to read data from user through input devices. keyboard is used as
standard input stream and represented as System.in.
Standard Output − This is used to project data (results) to the user through output devices. A
computer screen is used for standard output stream and represented as System.out.
Standard Error − This is used to output the error data produced by the user's program and usually a
computer screen is used for standard error stream and represented as System.err.
FileOutputStream Class:
We can write byte-oriented as well as character-oriented data through FileOutputStream
class.
Java FileOutputStream Class:
Java FileOutputStream is an output stream used for writing data to a file.
FileOutputStream class declaration: Output :Success...
The content of a text file testout.txt is set with
public class FileOutputStream extends OutputStream
the data A.
FileOutputStream Example 1: write byte testout.txt
import java.io.FileOutputStream; A
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
fout.write(65);
fout.close();
System.out.println("success...");
} catch(Exception e){System.out.println(e);}
}
}
Eexample 2: write string
import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
String s="Welcome to nalandacollege”;
byte b[]=s.getBytes();//converting string into byte array
fout.write(b);
fout.close(); Output:
System.out.println("success..."); Success...
} The content of a text file testout.txt is set with the data
catch(Exception e) { System.out.println(e); } Welcome to nalanda college
} testout.txt
} Welcome to javaTpoint.
FileInputStream Class
FileInputStream class obtains input bytes from a file.
It is used for reading byte-oriented data (streams of raw bytes) and also used to read
character-stream data.
Java FileInputStream class declaration
public class FileInputStream extends InputStream
FileInputStream class methods:
int read() - It is used to read the byte of data from the input stream.
void close()- It is used to closes the stream.
Example :To read single character from a file : To read String from a file :
import java.io.FileInputStream; int i=0;
while((i=fin.read())!=-1){
public class DataStreamExample { System.out.print((char)i);
public static void main(String args[]) { }
try{
FileInputStream fin=new FileInputStream("D:\\simha.txt");
int i=fin.read(); Note: Before running the code, a text file named as
“simha.txt" is required to be created.
System.out.print((char)i); In this file, we are having following content:
fin.close(); Welcome to javatpoint.
After executing the above program, we will get a
} catch(Exception e) {System.out.println(e);} single character from the file which is 87 (in byte
} } form). To see the text, you need to convert it into
character.
Output : W
FileWriter Class
Java FileWriter class is used to write character-oriented data to a file
It is character-oriented class which is used for file handling in java
Unlike FileOutputStream class, we don't need to convert string into byte array because it provides
method to write string directly.
Output:
Example :
Success...
import java.io.FileWriter;
simha.txt:
public class FileWriterExample {
Welcome to nalanda degree
public static void main(String args[]) {
college.
try{
FileWriter fw=new FileWriter("D:\\simha.txt");
fw.write("Welcome to nalanda degree college.");
fw.close();
} catch(Exception e) { System.out.println(e); }
System.out.println("Success...");
}
}
FileReader Class
Java FileReader class is used to read data from the file. It returns data in byte format like
FileInputStream class.
FileReader class declaration
public class FileReader extends InputStreamReader