javapackages notes.doc
javapackages notes.doc
Advantages of packages
Syntax
package Package_Name;
Example
package P1;
1.Predefined or Built in
2.Userdefined
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but
not subpackages.
The import keyword is used to make the classes and interface of another package accessible
to the current package.
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
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
3) Using fully qualified name
If you use fully qualified name then only declared class of this package will be accessible.
Now there is no need to import. But you need to use fully qualified name every time when
you are accessing the class or interface.
t is generally used when two packages have same class name e.g. java.util and java.sql
packages contain Date class.
Subpackage in java
Package inside the package is called the subpackage. It should be created to categorize the
package further
Example of Subpackage
package com.javatpoint.core;
class Simple{
public static void main(String args[]){
System.out.println("Hello subpackage");
}
}
To Compile: javac -d . Simple.java
Output:Hello subpackage
Access specifiers
The access modifiers in Java specifies the accessibility or scope of a field, method,
constructor, or class. We can change the access level of fields, constructors, methods, and
class by applying the access modifier on it.
1. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot
be accessed from outside the package. If you do not specify any access level, it will be
the default.
3. Protected: The access level of a protected modifier is within the package and outside
the package through child class. If you do not make the child class, it cannot be
accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
Java API
An API stands for Application Programming Interface, and it is an interface that allows
communication between different applications using the packages it comprises. Java API
comprises a collection of interfaces, classes, and packages. It helps us to use the packaged
classes and interfaces to build our applications and supports reusability. Whenever we write
any program in java, we use the Java API to do so. For example, we use JDBC API in java to
connect to any database server to perform several transactions using java.
Step 1: Click on the Windows button and choose Control Panel. Select System.
Step 4: If the CLASSPATH already exists in System Variables, click on the Edit button then
put a semicolon (;) at the end. Paste the Path of MySQL-Connector Java.jar file.
If the CLASSPATH doesn't exist in System Variables, then click on the New button and type
Variable name as CLASSPATH and Variable value as C:\Program Files\Java\jre1.8\
MySQL-Connector Java.jar;.;
Types of streams:
Byte Stream : It provides a convenient means for handling input and output of
byte.
Character Stream : It provides a convenient means for handling input and output
of characters. Character stream uses Unicode and therefore can be
internationalized.
1. Byte Stream:
Byte Stream Classes are used to read bytes from an input stream and write bytes to an output
stream.
Java I/O (Input and Output) is used to process the input and produce the output.
Java uses the concept of a stream to make I/O operation fast. The java.io package contains all
the classes required for input and output operations.
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.
n Java, 3 streams are created for us automatically. All these streams are attached with the
console.
Let's see the code to print output and an error message to the console.
1. System.out.println("simple message");
2. System.err.println("error message");
o How to write a common data to multiple files using a single stream only?
o How can we access multiple files by a single stream?
o How can we improve the performance of Input and Output operation?
o How many ways can we read data from the keyboard?
o What does the console class?
o How to compress and uncompress the data of a file?
OutputStream vs InputStream
OutputStream
Java application uses an output stream to write data to a destination; it may be a file, an array,
peripheral device or socket.
InputStream
Java application uses an input stream to read data from a source; it may be a file, an array,
peripheral device or socket.
Let's understand the working of Java OutputStream and InputStream by the figure given
below.
OutputStream class
2) public void write(byte[])throws IOException is used to write an array of byte to the current output stre
4) public void close()throws IOException is used to close the current output stream.
OutputStream Hierarchy
InputStream class
InputStream class is an abstract class. It is the superclass of all classes representing an input
stream of bytes.
1) public abstract int read()throws reads the next byte of data from the input stream. It returns -1 a
IOException end of the file.
2) public int available()throws returns an estimate of the number of bytes that can be read from
IOException current input stream.
is a special type of program embedded in the web page to generate dynamic content. Applet
is a class in Java.
The applet life cycle can be defined as the process of how the object is created, started,
stopped, and destroyed during the entire execution of its application. It basically has five core
methods namely init(), start(), stop(), paint() and destroy().These methods are invoked by the
browser to execute.
Along with the browser, the applet also works on the client side, thus having less processing
time.
Hierarchy of Applet
There are five methods of an applet life cycle, and they are:
o nit(): The init() method is the first method to run that initializes the applet. It can be
invoked only once at the time of initialization. The web browser creates the initialized
objects, i.e., the web browser (after checking the security settings) runs the init()
method within the applet.
o start(): The start() method contains the actual code of the applet and starts the applet.
It is invoked immediately after the init() method is invoked. Every time the browser is
loaded or refreshed, the start() method is invoked. It is also invoked whenever the
applet is maximized, restored, or moving from one tab to another in the browser. It is
in an inactive state until the init() method is invoked.
o stop(): The stop() method stops the execution of the applet. The stop () method is
invoked whenever the applet is stopped, minimized, or moving from one tab to
another in the browser, the stop() method is invoked. When we go back to that page,
the start() method is invoked again.
o destroy(): The destroy() method destroys the applet after its work is done. It is
invoked when the applet window is closed or when the tab containing the webpage is
closed. It removes the applet object from memory and is executed only once. We
cannot start the applet once it is destroyed.
o paint(): The paint() method belongs to the Graphics class in Java. It is used to draw
shapes like circle, square, trapezium, etc., in the applet. It is executed after the start()
method and when the browser or applet windows are resized.
1. init()
2. start()
3. paint()
1. stop()
2. destroy()
These methods are invoked by the browser automatically. There is no need to call them
explicitly.
How to run an Applet?
1. By html file.
2. By appletViewer tool (for testing purpose).
myapplet.html
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>
Simple example of Applet by appletviewer tool:
To execute the applet by appletviewer tool, create an applet that contains applet tag in
comment and compile it. After that run it by: appletviewer First.java. Now Html file is not
required but it is for testing purpose only.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
}
/*
<applet code="First.class" width="300" height="300">
</applet>
*/
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. AWT is heavy weight i.e. its components are using the
resources of underlying operating system (OS).
provides classes
, Label
, TextArea
, RadioButton, CheckBox
, Choice
, List
etc.
The hierarchy of Java AWT classes are given below, all the classes are available
in java.awt package.
1. Window
2. Panel
3. Frame
4. Dialog
Window
The window is the container that have no borders and menu bars. You must use frame, dialog
or another window for creating a window. We need to create an instance of Window class to
create this container.
Panel
The Panel is the container that doesn't contain title bar, border or menu bar. It is generic
container for holding the components. It can have other components like button, text field etc.
An instance of Panel class creates a container, in which we can add components.
Frame
The Frame is the container that contain title bar and border and can have menu bars. It can
have other components like button, text field, scrollbar etc. Frame is most widely used
container while developing an AWT application.
public void setSize(int width,int height) Sets the size (width and height) of the component.
public void setLayout(LayoutManager m) Defines the layout manager for the component.
public void setVisible(boolean status) Changes the visibility of the component, by default false.
To create simple AWT example, you need a frame. There are two ways to create a GUI using
Frame in AWT.
package testawt;
import java.awt.*;
import java.awt.event.*;
import java.awt.*;
public class Testawt
{
Testawt()
{
Frame fm=new Frame(); //Creating a frame
Label lb = new Label("welcome to java graphics"); //Creating a label
fm.add(lb); //adding label to the frame
fm.setSize(300, 300); //setting frame size.
fm.setVisible(true); //set frame visibilty true
}
public static void main(String args[])
{
Testawt ta = new Testawt();
}
}
AWT classes
AWT Button
In Java, AWT contains a Button Class. It is used for creating a labelled button which can
perform an action.
import java.awt.*;
public class ButtonDemo1
{
public static void main(String[] args)
{
Frame f1=new Frame("studytonight ==> Button Demo");
Button b1=new Button("Press Here");
b1.setBounds(80,200,80,50);
f1.add(b1);
f1.setSize(500,500);
f1.setLayout(null);
f1.setVisible(true);
}
AWT Label
In Java, AWT contains a Label Class. It is used for placing text in a container. Only Single
line text is allowed and the text can not be changed directly.
Label Declaration:
Example:
In this example, we are creating two labels to display text to the frame
import java.awt.*;
class LabelDemo1
Label lab1,lab2;
lab1.setBounds(50,50,200,30);
lab2.setBounds(50,100,200,30);
l_Frame.add(lab1);
l_Frame.add(lab2);
l_Frame.setSize(500,500);
l_Frame.setLayout(null);
l_Frame.setVisible(true);
}
AWT TextField
In Java, AWT contains aTextField Class. It is used for displaying single line text.
TextField Declaration:
Example:
We are creating two textfields to display single line text string. This text is editable in nature,
see the below example.
import java.awt.*;
class TextFieldDemo1{
TextField text1,text2;
text1.setBounds(60,100, 230,40);
text2.setBounds(60,150, 230,40);
TextF_f.add(text1);
TextF_f.add(text2);
TextF_f.setSize(500,500);
TextF_f.setLayout(null);
TextF_f.setVisible(true);
AWT TextArea
In Java, AWT contains aTextArea Class. It is used for displaying multiple-line text.
TextArea Declaration:
Example:
In this example, we are creating a TextArea that is used to display multiple-line text string
and allows text editing as well.
TextAreaDemo1()
area.setBounds(30,40, 200,200);
textArea_f.add(area);
textArea_f.setSize(300,300);
textArea_f.setLayout(null);
textArea_f.setVisible(true);
new TextAreaDemo1();
AWT Checkbox
In Java, AWT contains a Checkbox Class. It is used when we want to select only one option
i.e true or false. When the checkbox is checked then its state is "on" (true) else it is
"off"(false).
Checkbox Syntax
Example:
In this example, we are creating checkbox that are used to get user input. If checkbox is
checked it returns true else returns false.
import java.awt.*;
CheckboxDemo1(){
ckbox1.setBounds(100,100, 60,60);
ckbox2.setBounds(100,150, 60,60);
checkB_f.add(ckbox1);
checkB_f.add(ckbox2);
checkB_f.setSize(400,400);
checkB_f.setLayout(null);
checkB_f.setVisible(true);
new CheckboxDemo1();
}
AWT CheckboxGroup
In Java, AWT contains aCheckboxGroup Class. It is used to group a set of Checkbox. When
Checkboxes are grouped then only one box can be checked at a time.
CheckboxGroup Declaration:
Example:
This example creates a checkboxgroup that is used to group multiple checkbox in a single
unit. It is helpful when we have to select single choice among the multiples.
import java.awt.*;
CheckboxGroupDemo(){
ckBox1.setBounds(100,100, 50,50);
ckBox2.setBounds(100,150, 50,50);
ck_groupf.add(ckBox1);
ck_groupf.add(ckBox2);
ck_groupf.setSize(400,400);
ck_groupf.setLayout(null);
ck_groupf.setVisible(true);
}
public static void main(String args[])
new CheckboxGroupDemo();
AWT Choice
In Java, AWT contains a Choice Class. It is used for creating a drop-down menu of choices.
When a user selects a particular item from the drop-down then it is shown on the top of the
menu.
Choice Declaration:
Example:
In this example, we are creating drop-down menu that is used to get user choice from
multiple choices.
import java.awt.*;
ChoiceDemo()
{
Frame choice_f= new Frame();
obj.setBounds(80,80, 100,100);
obj.add("Red");
obj.add("Blue");
obj.add("Black");
obj.add("Pink");
obj.add("White");
obj.add("Green");
choice_f.add(obj);
choice_f.setSize(400,400);
choice_f.setLayout(null);
choice_f.setVisible(true);
new ChoiceDemo();
}
AWT List
In Java, AWT contains a List Class. It is used to represent a list of items together. One or
more than one item can be selected from the list.
List Declaration:
Example:
In this example, we are creating a list that is used to list out the items.
import java.awt.*;
ListDemo()
obj.setBounds(80,80, 100,100);
obj.add("Red");
obj.add("Blue");
obj.add("Black");
obj.add("Pink");
obj.add("White");
obj.add("Green");
list_f.add(obj);
list_f.setSize(400,400);
list_f.setLayout(null);
list_f.setVisible(true);
new ListDemo();
Classification of Events
Foreground Events
Background Events
Types of Events
1. Foreground Events
Foreground events are the events that require user interaction to generate,
i.e., foreground events are generated due to interaction by the user on
components in Graphic User Interface (GUI). Interactions are nothing but
clicking on a button, scrolling the scroll bar, cursor moments, etc.
2. Background Events
Events that don’t require interactions of users to generate are known as
background events. Examples of these events are operating system
failures/interrupts, operation completion, etc.
Event Handling
It is a mechanism to control the events and to decide what should
happen after an event occur. To handle the events, Java follows
the Delegation Event model.
Source: Events are generated from the source. There are various
sources like buttons, checkboxes, list, menu-item, choice, scrollbar, text
components, windows, etc., to generate events.
Listeners: Listeners are used for handling the events generated from the
source. Each of these listeners represents interfaces that are responsible
for handling events.
To perform Event Handling, we need to register the source with the listener.
ActionListener
actionPerformed()
AdjustmentListener
adjustmentValueChanged()
componentResized()
componentShown()
componentMoved()
ComponentListener
componentHidden()
componentAdded()
ContainerListener
componentRemoved()
focusGained()
FocusListener
focusLost()
ItemListener
itemStateChanged()
keyTyped()
keyPressed()
KeyListener
keyReleased()
Listener Interface Methods
mousePressed()
mouseClicked()
mouseEntered()
mouseExited()
MouseListener
mouseReleased()
MouseMotionListene mouseMoved()
r
mouseDragged()
import java.awt.*;
import java.awt.event.*;
TextField textField;
GFGTop()
// Component Creation
button.addActionListener(this);
// add Components
add(textField);
add(button);
// set visibility
setVisible(true);
textField.setText("GFG!");
new GFGTop();
}
}
protected void disppress(KeyEvent e,String s)
{
String charString,keyCodeString,modString,tmpString;
char c=e.getKeyChar();
int keyCode=e.getKeyCode();
int modifiers=e.getModifiers();
if(Character.isISOControl(c))
{
charString="key character=(an unprintable control
character)";
}
else
{
charString="key character='"+c+"'";
}
modString="modifiers="+modifiers;
tmpString=KeyEvent.getKeyModifiersText(modifiers);
if(tmpString.length()>0)
{
modString+="("+tmpString+")";
}
else
{
modString+="(no modifiers)";
}
keyCodeString="key
code="+keyCode+"("+KeyEvent.getKeyText(keyCode)+")";
tpress.setText(s+charString+keyCodeString+modString);
}
}