Download as pdf or txt
Download as pdf or txt
You are on page 1of 60

Stream classes in Java

 Java performs I/O through Streams.


 A Stream is linked to a physical layer by java I/O system to make input
and output operation in java.
 A stream can be defined as a sequence of data.
 The InputStream is used to read data from a source and the
OutputStream is used for writing data to a destination.
 InputStream and OutputStream are the basic stream classes in Java.
 Why we need Stream classes?
 To perform read and write operations on binary files we need a
mechanism to read that binary data on file/to write binary data (i.e. in
the form of byte). These classes are capable to read and write one
byte on binary files.
 The IO operations are performed using the concept of streams.
 Generally, a stream means a continuous flow of data.
 In java, a stream is a logical container of data that allows us to read from and write to it.
 The Stream is defined in the java.io package.
 Java provides two types of streams, and they are as follows.
• Byte Stream
• Character Stream
Byte Stream in java
 In java, the byte stream is an 8 bits carrier.
 In Java 1.0 version all IO operations were byte oriented, there was no other stream
(character stream).
 The java byte stream is defined by two abstract
classes, InputStream and OutputStream
 The InputStream class used for byte stream based input operations, and the
OutputStream class used for byte stream based output operations.
 InputStream class
 The InputStream class has defined as an abstract class, and it has the following methods
which have implemented by its concrete classes.

S.No. Method with Description


1 int available()It returns the number of
bytes that can be read from the input
stream.

2 int read()It reads the next byte from the


input stream.
3 int read(byte[] b)It reads a chunk of bytes
from the input stream and store them in
its byte array, b.

4 void close()It closes the input stream and


also frees any resources connected with
this input stream.
 OutputStream class
 The OutputStream class has defined as an abstract class, and it has the following
methods which have implemented by its concrete classes.

S.No. Method with Description


1 void write(int n)It writes
byte(contained in an int) to the output
stream.

2 void write(byte[] b)It writes a whole


byte array(b) to the output stream.

3 void flush()It flushes the output steam


by forcing out buffered bytes to be
written out.

4 void close()It closes the output stream


and also frees any resources connected
with this output stream.
 import java.io.*;
public class ReadingDemo {
public static void main(String[] args) throws IOException {

 BufferedInputStream read = new BufferedInputStream(System.in);


 try {
 System.out.print("Enter any character: ");
 char c = (char)read.read();
 System.out.println("You have entered '" + c + "'");
 }
 catch(Exception e) {
 System.out.println(e);
 }
 finally {
 read.close();
 }}

 File Handling using Byte Stream
 In java, we can use a byte stream to handle files.
 The byte stream has the following built-in classes to perform various
operations on a file.
• FileInputStream - It is a built-in class in java that allows reading data
from a file. This class has implemented based on the byte stream.
The FileInputStream class provides a method read() to read data
from a file byte by byte.
It is used for reading byte-oriented data (streams of raw bytes) such as
image data, audio, video etc.
You can also read character-stream data. But, for reading streams of
characters, it is recommended to use FileReader class.
public class FileInputStream extends InputStream
Method Description
int available() It is used to return the estimated
number of bytes that can be read from
the input stream.
int read() It is used to read the byte of data from
the input stream.
int read(byte[] b) It is used to read up to b.length bytes
of data from the input stream.
int read(byte[] b, int off, int len) It is used to read up to len bytes of
data from the input stream.
long skip(long x) It is used to skip over and discards x
bytes of data from the input stream.
FileChannel getChannel() It is used to return the unique
FileChannel object associated with the
file input stream.
FileDescriptor getFD() It is used to return
the FileDescriptor object.
protected void finalize() It is used to ensure that the close
method is call when there is no more
reference to the file input stream.
void close() It is used to closes the stream.
 Java FileOutputStream Class
 Java FileOutputStream is an output stream used for writing data to a file.
 If you have to write primitive values into a file, use FileOutputStream class.
 You can write byte-oriented as well as character-oriented data through FileOutputStream
class. But, for character-oriented data, it is preferred to use FileWriter than
FileOutputStream.
Method Description

protected void finalize() It is used to clean up the connection with the file output stream.

void write(byte[] ary) It is used to write ary.length bytes from the byte array to the file
output stream.

void write(byte[] ary, int off, int len) It is used to write len bytes from the byte array starting at
offset off to the file output stream.

void write(int b) It is used to write the specified byte to the file output stream.

FileChannel getChannel() It is used to return the file channel object associated with the file
output stream.

FileDescriptor getFD() It is used to return the file descriptor associated with the stream.

void close() It is used to closes the file output stream


Character Stream in java
 The java.io package provides CharacterStream classes to
overcome the limitations of ByteStream classes, which can only
handle the 8-bit bytes and is not compatible to work directly
with the Unicode characters.
 CharacterStream classes are used to work with 16-bit Unicode
characters.
 CharacterStream classes are mainly used to read characters from
the source and write them to the destination.
 For this purpose, the CharacterStream classes are divided into
two types of classes, I.e., Reader class and Writer class.
 The Reader class used for character stream based input
operations, and the Writer class used for charater stream based
output operations.
Java BufferedReader Class
 Java BufferedReader class is used to read the text from a
character-based input stream. It can be used to read data line by
line by readLine() method.
 import java.io.*;
 public class BufferedReaderExample{
 public static void main(String args[])throws Exception{
 InputStreamReader r=new InputStreamReader(System.in);
 BufferedReader br=new BufferedReader(r);
 System.out.println("Enter your name");
 String name=br.readLine();
 System.out.println("Welcome to:"+name);
 }
 }
Java BufferedWriter Class
 Java BufferedWriter class is used to provide buffering for Writer instances. It
makes the performance fast. It inherits Writer class.
 import java.io.*;
 public class BufferedWriterExample {
 public static void main(String[] args) throws Exception {
 FileWriter writer = new FileWriter("E:\\BufferWriter.txt");
 BufferedWriter buffer = new BufferedWriter(writer);
 buffer.write("Welcome to javaTpoint.");
 buffer.close();
 System.out.println("Success");
 }
 }
Java AWT
 Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface (GUI) or
windows-based applications in Java.
 Java AWT components are platform-dependent i.e. components are displayed according to the
view of operating system.
 The java.awt package provides classes for AWT API such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.
 AWT is the foundation upon which Swing is made i.e Swing is a improved GUI API that extends
the AWT.
 most GUI Java programs are implemented using Swing because of its rich implementation of
GUI controls and light-weighted nature.
 Java AWT Hierarchy
 Components
 All the elements like the button, text fields, scroll bars, etc. are called components. In Java AWT,
there are classes for each component
 In order to place every component in a particular position on a screen, we need to add them to
a container.
Container
 The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extends Container class are known as container such as
Frame, Dialog and Panel.
 Panel class is a concrete subclass of Container. Panel does not contain title bar,
menu bar or border. It is container that is used for holding components.
 Frame is a subclass of Window and have resizing canvas. It is a container that
contain several different components like button, title bar, textfield, label etc. In
Java, most of the AWT applications are created using Frame window.
Java Swing classes
 Java Swing is a GUI Framework that contains a set of classes to provide
more powerful and flexible GUI components than AWT.
 Swing provides the look and feel of modern Java GUI. Swing library is an
official Java GUI tool kit released by Sun Microsystems. It is used to create
graphical user interface with Java.
 Swing provides a rich set of widgets and packages to make sophisticated
GUI components for Java applications.
 Swing is a part of Java Foundation Classes(JFC), which is an API for Java
GUI programing that provide GUI.
 Swing classes are defined in javax.swing package and its sub-packages.
 The javax.swing package provides classes for java swing API such as
JButton, JTextField, JTextArea, JRadioButton, JCheckbox, JMenu,
JColorChooser etc.
 Unlike AWT, Java Swing provides platform-independent and lightweight
components.
Difference Between AWT and Swing

No. Java AWT Java Swing

1) AWT components are platform- Java swing components


dependent. are platform-independent.

2) AWT components Swing components


are heavyweight. are lightweight.

3) AWT doesn't support pluggable Swing supports pluggable look


look and feel. and feel.

4) AWT provides less Swing provides more powerful


components than Swing. components such as tables,
lists, scrollpanes, colorchooser,
tabbedpane etc.

5) AWT doesn't follows MVC(Model Swing follows MVC.


View Controller) where model
represents data, view
represents presentation and
controller acts as an interface
between model and view.
What is a Container Class?
 Container classes are classes that can have other components on
it. So for creating a Java Swing GUI, we need at least one container
object.
 There are 3 types of Java Swing containers.
1. Panel: It is a pure container and is not a window in itself. The sole
purpose of a Panel is to organize the components on to a window.
2. Frame: It is a fully functioning window with its title and icons.
3. Dialog: It can be thought of like a pop-up window that pops out
when a message has to be displayed. It is not a fully functioning
window like the Frame.
 What is JFC
 The Java Foundation Classes (JFC) are a set of GUI components
which simplify the development of desktop applications.
 Java JFrame
 The javax.swing.JFrame class is a type of container which inherits the
java.awt.Frame class. JFrame works like the main window where
components like labels, buttons, textfields are added to create a GUI.
 Unlike Frame, JFrame has the option to hide or close the window with the
help of setDefaultCloseOperation(int) method.
 Creating a JFrame
 There are two ways to create a JFrame Window.
1. By instantiating JFrame class.
2. By extending JFrame class.

1.Java JButton:
JButton class is used to create a labeled button that has platform
independent implementation. The application result in some action when the
button is pushed. It inherits AbstractButton class.
 Commonly used Constructors:
 JButton(): It creates a button with no text and icon.
 JButton(String s): It creates a button with the specified text.
 Methods of AbstractButton class:
 void setText(String s): It is used to set specified text on button
 String getText(): It is used to return the text of the button.
 void setEnabled(boolean b): It is used to enable or disable the button.
 setBounds(int x-coordinate, int y-coordinate, int width, int height):
2. JLabel
 The object of JLabel class is a component for placing text in a container. It is used to
display a single line of read only text.
 It is under package javax.swing.JLabel class. It is used for placing text in a box. Only
Single line text is allowed and the text can not be changed directly.
 The class JLabel can display either text, an image, or both.

 Declaration
 public class JLabel extends JComponent implements SwingConstants, Accessible

 Commonly used Constructors:


 JLabel(): Creates a JLabel instance with no image and with an empty string for the
title.
 JLabel(String s): Creates a JLabel instance with the specified text.
 JLabel(Icon i): Creates a JLabel instance with the specified image.
 JLabel(String s, Icon i, int horizontalAlignment): Creates a JLabel instance with the
specified text, image, and horizontal alignment.
Commonly used Methods:

Methods Description
String getText() t returns the text string that a label
displays.
void setText(String text) It defines the single line of text this
component will display.
void setHorizontalAlignment(int alignment) It sets the alignment of the label's
contents along the X axis.
Icon getIcon() It returns the graphic image that the label
displays.
int getHorizontalAlignment() It returns the alignment of the label's
contents along the X axis.
3.Java JTextField
 The object of a JTextField class is a text component that allows the editing of a
single line text. It inherits JTextComponent class.
 JTextField is used for taking input of single line of text. It is most widely used text
component.
 Constructors:
 JTextField(int cols):
 JTextField(String str, int cols):
 JTextField(String str):
 JTextField():
 Methods:
 void addActionListener(ActionListener l): It is used to add the specified action
listener to receive action events from this textfield.
 Action getAction(): It returns the currently set Action for this ActionEvent
source, or null if no Action is set.
 void setFont(Font f): It is used to set the current font.
 void removeActionListener(ActionListener l): It is used to remove the
specified action listener so that it no longer receives action events from this
textfield.
4.JCheckBox
 The JcheckBox class is used to create chekbox in swing framework.
 The JCheckBox class is used to create a checkbox. It is used to turn an
option on (true) or off (false).
 Constructors:
 JCheckBox(): Creates an initially unselected check box button with
no text, no icon.
 JChechBox(String s): Creates an initially unselected check box with
text.
 JCheckBox(String text, boolean selected): Creates a check box with
text and specifies whether or not it is initially selected.
 JCheckBox(Action a): Creates a check box where properties are
taken from the Action supplied.
5.Java JComboBox
 JComboBox is a part of Java Swing package. JComboBox inherits
JComponent class .
 JComboBox shows a popup menu that shows a list and the user can
select a option from that specified list .
 Combo box is a combination of text fields and drop-down list.
 Constructor of the JComboBox:
1. JComboBox() : creates a new empty JComboBox .
2. JComboBox(ComboBoxModel M) : creates a new JComboBox with
items from specified ComboBoxModel
3. JComboBox(E [ ] i) : creates a new JComboBox with items from
specified array.
4. JComboBox(Vector items) : creates a new JComboBox with items
from the specified vector.
 Methods of JComboBox:
1. addItem(E item) : adds the item to the JComboBox
2. void removeItem(Object anObject): It is used to delete an item to
the item list.
3. void removeAllItems(): It is used to remove all the items from the
list.
4. void addActionListener(ActionListener a): It is used to add the
ActionListener.
5. addItemListener( ItemListener l) : adds a ItemListener to JComboBox
6. getItemAt(int i) : returns the item at index i
7. getItemCount(): returns the number of items from the list
8. getSelectedItem() : returns the item which is selected.
9. removeItemAt(int i) : removes the element at index i
10. removeActionListener(ActionListener l): removes an ActionListener.
6.JRadioButton
 Radio button is a group of related button in which only one can be selected. JRadioButton class is
used to create a radio button in Frames.
 The JRadioButton class is used to create a radio button. It is used to choose one option from
multiple options. It is widely used in exam systems or quiz.
 It should be added in ButtonGroup to select one radio button only.

 Constructors:
1. JRadioButton(): Creates an unselected radio button with no text.
2. JRadioButton(String s): Creates an unselected radio button with specified text.
3. JRadioButton(String s, boolean selected): Creates a radio button with the specified text and
selected status.
Methods:
1. void setText(String s): It is used to set specified text on button.
2. String getText(): It is used to return the text of the button.
3. void setEnabled(boolean b): It is used to enable or disable the button.
4. void setIcon(Icon b): It is used to set the specified Icon on the button.
5. void addActionListener(ActionListener a): It is used to add the action listener to this object.
7. JList
 The object of JList class represents a list of text items. The list of text
items can be set up so that the user can choose either one item or
multiple items.
 JList is part of Java Swing package . JList is a component that displays
a set of Objects and allows the user to select one or more items .
 JList inherits JComponent class.
 Constructor for JList are :

1. JList(): creates an empty blank list


2. JList(E [ ] l) : creates an new list with the elements of the array.
3. JList(ListModel d): creates a new list with the specified List Model
4. JList(Vector l) : creates a new list with the elements of the vector
Java JOptionPane
 The JOptionPane class is used to provide standard dialog boxes such as
message dialog box, confirm dialog box and input dialog box.
 These dialog boxes are used to display information or get input from
the user.
 The JOptionPane class inherits JComponent class.

public class JOptionPane extends JComponent implements Accessible
 Constructors:
 JOptionPane(): It is used to create a JOptionPane with a test message.
 JOptionPane(Object message): It is used to create an instance of
JOptionPane to display a message.
 JOptionPane(Object message, int messageType): It is used to create an
instance of JOptionPane to display a message with specified message
type and default options.
 Methods:
 JDialog createDialog(String title): It is used to create and return a new
parentless JDialog with the specified title.
 static void showMessageDialog(Component parentComponent, Object
message): It is used to create an information-message dialog titled
"Message".
 static void showMessageDialog(Component parentComponent, Object
message, String title, int messageType): It is used to create a message
dialog with given title and messageType.
 static int showConfirmDialog(Component parentComponent, Object
message): It is used to create a dialog with the options Yes, No and
Cancel; with the title, Select an Option.
 static String showInputDialog(Component parentComponent, Object
message): It is used to show a question-message dialog requesting input
from the user parented to parentComponent.
 void setInputValue(Object newValue): It is used to set the input value
that was selected or input by the user.
JMenuBar, JMenu and JMenuItem
 The JMenuBar class is used for displaying menubar on the frame. The JMenu
Object is used for pulling down the components of the menu bar.
 The JMenuItem Object is used for adding the labelled menu item.
 The JMenuBar class is used to display menubar on the window or frame. It may
have several menus.
 The object of JMenu class is a pull down menu component which is displayed
from the menu bar. It inherits the JMenuItem class.
 The items used in a menu must belong to the JMenuItem or any of its subclass.
 public class JMenuBar extends JComponent implements MenuElement,
Accessible
 public class JMenu extends JMenuItem implements MenuElement, Accessible
 public class JMenuItem extends AbstractButton implements Accessible,
MenuElement
Java JTabbedPane
 The JTabbedPane class is used to switch between a group of
components by clicking on a tab with a given title or icon. It inherits
JComponent class.
 JTabbedPane is one of the classes provided by the swing package in
java.
 It is very useful, as it provides the flexibility to the user to switch
between different groups of components he desires to see, by simply
clicking on one of the tabs.
 Constructors:
 JTabbedPane(): Creates an empty TabbedPane with a default tab
placement of JTabbedPane.Top.
 JTabbedPane(int tabPlacement): Creates an empty TabbedPane with a
specified tab placement.
 JTabbedPane(int tabPlacement, int tabLayoutPolicy): Creates an empty
TabbedPane with a specified tab placement and tab layout policy.
Java JScrollPane
 A JscrollPane is used to make scrollable view of a
component.
 When screen size is limited, we use a scroll pane to
display a large component or a component whose size
can change dynamically.
 Constructors
 JScrollPane(): It creates a scroll pane.
 JScrollPane(Component): The Component parameter,
when present, sets the scroll pane's client.
 JScrollPane(int, int): The two int parameters, when
present, set the vertical and horizontal scroll bar
policies (respectively).
 Java ActionListener Interface
 The Java ActionListener is notified whenever you click on the button or menu item. It is
notified against ActionEvent.
 The ActionListener interface is found in java.awt.event package. It has only one method:
actionPerformed().
 The actionPerformed() method is invoked automatically whenever you click on the
registered component.
 public abstract void actionPerformed(ActionEvent e);
 How to write ActionListener:
 Step 1: Implement the ActionListener Interface in the class.
 public class ActionListenerDemo Implements ActionListener
 Step 2: Now Register all the components with the Listener.
 component.addActionListener(instanceOfListenerclass);
 Step 3: Aylast override the actionPerformed() method.
 public void actionPerformed(ActionEvent e)
 {
 //statements
 }
Java Database
Connectivity(JDBC)
Java Database Connectivity(JDBC) is an Application Programming
Interface(API) used to connect Java application with Database.
 JDBC is used to interact with various type of Database such as Oracle, MS
Access, My SQL and SQL Server.
 JDBC can also be defined as the platform-independent interface between a
relational database and Java programming.
 It allows java program to execute SQL statement and retrieve result from
database.
 The JDBC API consists of classes and methods that are used to perform various
operations like: connect, read, write and store data in the database.
 JDBC has four major components that are used for the interaction with
the database.
1. JDBC API
2. JDBC Test Suite
3. JDBC Driver Manger
4. JDBC ODBC Bridge Driver
 1.JDBC API: JDBC API provides various interfaces and methods to
establish easy connection with different databases.
1. javax.sql.*; java.sql.*;
2. 2.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.
3. 3) JDBC Driver manager: JDBC Driver manager loads the database-
specific driver into an application in order to establish the connection
with the database.
4. 4) JDBC-ODBC Bridge Drivers: JDBC-ODBC Bridge Drivers are used to
connect the database drivers to the database.
5.
JDBC Driver
 JDBC Driver is required to establish connection between application and database. It
also helps to process SQL requests and generating result.
 The following are the different types of driver available in JDBC.
1) Type-1 Driver or JDBC-ODBC bridge
2) Type-2 Driver or Native API Partly Java Driver
3) Type-3 Driver or Network Protocol Driver
4) Type-4 Driver or Thin Driver.
 1.Type-1 Driver act as a bridge between JDBC and other database connectivity
mechanism(ODBC). This driver converts JDBC calls into ODBC calls and redirects the
request to the ODBC driver.
 Note: In Java 8, the JDBC-ODBC Bridge has been removed.
 Advantage
 Easy to use
 Allow easy connectivity to all database supported by the ODBC Driver.
 Disadvantage
 Slow execution time
 Dependent on ODBC Driver.
 2.Native API Driver:
 This type of driver make use of Java Native Interface(JNI) call on database specific native
client API. These native client API are usually written in C and C++.
 Advantage
• faster as compared to Type-1 Driver
 Disadvantage
• Requires native library
• Increased cost of Application.
 3.Network Protocol Driver:
 This driver translate the JDBC calls into a database server independent and Middleware
server-specific calls. Middleware server further translate JDBC calls into database specific
calls.
 Advantage
• Does not require any native library to be installed.
• Database Independency.
 Disadvantage
• Slow due to increase number of network call.
 4.Thin Driver
 This is Driver called Pure Java Driver because. This driver interact
directly with database. It does not require any native database
library, that is why it is also known as Thin Driver.
 Advantage
• Does not require any native library.
• Does not require any Middleware server.
• Better Performance than other driver.
 Disadvantage
• Slow due to increase number of network call.
 Java Database Connectivity:
• There are 5 steps to connect any java application with the database using JDBC. These steps
are as follows:
1) Register the Driver class
2) Create connection
3) Create statement
4) Execute queries
5) Close connection
 1) Register the driver class(Oracle database)
 The forName() method of Class class is used to register the driver class. This method is used
to dynamically load the driver class.
1. EX: Class.forName("oracle.jdbc.driver.OracleDriver");
2. 2) Create the connection object:
3. The getConnection() method of DriverManager class is used to establish connection with
the database.
4. Ex: Connection con=DriverManager.getConnection(
5. "jdbc:oracle:thin:@localhost:1521:xe","system","password");
 3) 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.
 Ex: Statement stmt=con.createStatement();

 4) 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.
 Ex: ResultSet rs=stmt.executeQuery("select * from emp");

 5) Close the connection object:


 By closing connection object statement and ResultSet will be closed
automatically.
 EX:con.close();

You might also like