Professional Documents
Culture Documents
1. Abstraction
2. Inheritance
3. Polymorphism
Polymorphism means many forms. It can be exhibited by two processes:
a. Method Overloading
Whenever the same class consists of multiple methods having the same name but is
differentiated due to the number and type of arguments then that methods are said to
exhibit Method Overloading.
b. Method Overriding
Whenever one method changes its behavior in the inherited class then the method is said
to exhibit method overriding.
4. Encapsulation
CONSTRUCTOR:
A constructor is a special method within the class definition which has the same name of
that of the class, has no return type, is automatically executed whenever an object of that
class is created using the new operator and thus help to allocate memory of the created
object in the heap.
Characteristics of Constructors:
Pre-defined exceptions
User-defined exceptions
Exception handling is necessary to cover up the faulty part of the software and still keep it
running.
Exception handling consist of the following blocks:
Try : -it is the block where the code which can give rise to exception is enclosed.
Catch:- It is the block which will take action once the exception has been raised within the
try block.
Finally:- It is a mandatory executable block…i.e. it will execute whether an exception
occurs or not.
The Exception can have the following block combination
You cannot print or perform other operations on an unassigned local variable. All the
assignment made within the try block will be ignored.
Any variable initialized within the try block is ignored by statements outside the exception
handling blocks.
Float or Double variable can stores results like Infinity(when a number is divided by zero)
and NaN(Not a number- when divided 0 by 0)
Whenever you using multiple catch blocks then the general catch block should be specified
after all the specialized catch blocks.
getMessage() brings out the System Message of the exception.
Abstract Class: It is an incomplete class definition which precedes with the keyword
“abstract” and can consist of one or more abstract (incomplete) methods.
Characteristics of an Abstract Class
An abstract class may or may not contain one or more abstract methods
Pure object instance of an abstract class cannot be instantiated.
Abstract class functionalities can only be implemented by the concrete child classes
inheriting the abstract methods.
If a class consists of an abstract method then the class has needs to be declared as
abstract.
Abstract methods can consist of declaration only, no method definitions are allowed.
If a class inherits an abstract class then the class must redefine the inherited abstract
methods otherwise the child class also needs to be declared as abstract.
CHARACTERISTICS OF PACKAGES:
In Java the system of packaging implies accessing multiple classes within a single
program.
The accessible classes are in folders/subfolders which are all names in small letters.
These folders /subfolders are arranged in a proper hierarchy starting from a root
folder.
All the accessible classes and their associated methods are generally public in nature.
The entire package can be also compressed as an archive and then accessed by
setting the classpath environment variable.
INTERFACES
Interfaces in java are programming constructs which can be implemented in multiple
numbers to a class and can control the class’s behavior.
Characteristics of Interfaces:
An interface can have method declarations only but not method definitions i.e.
automatically the methods within the interface becomes abstract methods even
without the keyword abstract.
Classes implementing the interface must re-define the methods declared within the
interface.
Interface acts as an alternative to multiple inheritance as demonstrated in C++
Pure object instance of an interface cannot be created.
If you are inheriting an interface from another one then you have to use the extends
keyword instead of the implements keyword.
If you are declaring a variable within an interface then that variable the variable must
be initialized and that variable is final in nature i.e. the value of the variable cannot be
changed later in the program. The variable also becomes static.
o Class Class ============Extends
o Interface- Class======Implements
o Interface Interface=======Extends
An interface can inherit an interface only. (Not a class)
An interface cannot consist of a constructor.
All the members of an interface are public by default.
Programs using interfaces are slower than program using abstract classes as
interfaces require an extra indirection.
CHARACTERISTICS OF CLASSES:
Swing is a part of Java Foundation classes (JFC), the other parts of JFC are java2D and
Abstract window toolkit (AWT). AWT, Swing & Java 2D are used for building graphical user
interfaces (GUIs) in java. In this tutorial we will mainly discuss about Swing API which is
used for building GUIs on the top of AWT and are much more light-weight compared to
AWT.
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class SwingFirstExample {
// Creating JLabel
JLabel userLabel = new JLabel("User");
/* This method specifies the location and size
* of component. setBounds(x, y, width, height)
* here (x,y) are cordinates from the top left
* corner and remaining two arguments are the width
* and height of the component.
*/
userLabel.setBounds(10,20,80,25);
panel.add(userLabel);
In the above example we have used several components. Let’s discuss a bit about them
first then we will discuss them in detail in the next tutorials.
JFrame – A frame is an instance of JFrame. Frame is a window that can have title, border,
menu, buttons, text fields and several other components. A Swing application must have a
frame to have the components added to it.
JPanel – A panel is an instance of JPanel. A frame can have more than one panels and
each panel can have several components. You can also call them parts of Frame. Panels
are useful for grouping components and placing them to appropriate locations in a frame.
JLabel – A label is an instance of JLabel class. A label is unselectable text and images. If
you want to display a string or an image on a frame, you can do so by using labels. In the
above example we wanted to display texts “User” & “Password” just before the text fields ,
we did this by creating and adding labels to the appropriate positions.
JTextField – Used for capturing user inputs, these are the text boxes where user enters
the data.
JPasswordField – Similar to text fields but the entered data gets hidden and displayed as
dots on GUI.
JButton – A button is an instance of JButton class. In the above example we have a button
“Login”.
JButton class is used for adding platform independent buttons to a swing application. In this
tutorial we will learn how to create a button in Swing application and how to tweak their
appearance as per the requirement. I have also shared some code snippets that may be
useful for you while developing a Swing application.
import javax.swing.JButton;
import javax.swing.JFrame;
public class JButtonExample {
JButtonExample(){
/* JFrame is a top level container (window)
* where we would be adding our button
*/
JFrame frame=new JFrame();
// Creating Button
JButton b=new JButton("Click Me..");
/* This method specifies the location and size
* of button. In method setBounds(x, y, width, height)
* x,y) are cordinates from the top left
* corner and remaining two arguments are the width
* and height of the button.
*/
b.setBounds(50,50,90, 50);
frame.setLayout(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
import javax.imageio.ImageIO;
import javax.swing.*;
// Creating Button
JButton b = new JButton();
try {
Image img = ImageIO.read(getClass().getResource("play.gif"));
b.setIcon(new ImageIcon(img));
} catch (IOException ex) {
}
b.setBounds(50,50,90, 50);
frame.setLayout(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Frames
• Are a subclass of Window
• Have title and resizing corners
• Are initially invisible, use setVisible(true) to
expose the frame
• Have BorderLayout as the default layout manager
• Use the setLayout method to change the default
layout manager
FrameExample.java
1 import java.awt.*;
2
3 public class FrameExample {
4 private Frame f;
5
6 public FrameExample() {
7 f = new Frame("Hello Out There!");
8}
9
10 public void launchFrame() {
11 f.setSize(170,170);
12 f.setBackground(Color.blue);
13 f.setVisible(true);
14 }
15
16 public static void main(String args[]) {
17 FrameExample guiWindow = new FrameExample();
18 guiWindow.launchFrame();
19 }
20 }
Panels
• Provide a space for components
• Allow subpanels to have their own layout manager
FrameWithPanel.java
1 import java.awt.*;
2
3 public class FrameWithPanel {
4 private Frame f;
5 private Panel pan;
6
7 public FrameWithPanel(String title) {
8 f = new Frame(title);
9 pan = new Panel();
10 }
11
12 public void launchFrame() {
13 f.setSize(200,200);
14 f.setBackground(Color.blue);
15 f.setLayout(null); // Override default layout mgr
16
17 pan.setSize(100,100);
18 pan.setBackground(Color.yellow);
19 f.add(pan);
20 f.setVisible(true);
21 }
22
23 public static void main(String args[]) {
24 FrameWithPanel guiWindow =
25 new FrameWithPanel("Frame with Panel");
26 guiWindow.launchFrame();
27 }
28 }
Container Layouts
• FlowLayout
• BorderLayout
• GridLayout
• CardLayout
• GridBagLayout
ASimple FlowLayout
Example
1 import java.awt.*;
2
3 public class LayoutExample {
4 private Frame f;
5 private Button b1;
6 private Button b2;
7
8 public LayoutExample() {
9 f = new Frame("GUI example");
10 b1 = new Button("Press Me");
11 b2 = new Button("Don’t press Me");
12 }
13
14 public void launchFrame() {
15 f.setLayout(new FlowLayout());
16 f.add(b1);
17 f.add(b2);
18 f.pack();
19 f.setVisible(true);
20 }
21
22 public static void main(String args[]) {
23 LayoutExample guiWindow = new LayoutExample();
24 guiWindow.launchFrame();
25 }
26 }
The FlowLayoutManager
• Default layout for the Panel class
• Components added from left to right
• Default alignment is centered
• Uses components’ preferred sizes
• Uses the constructor to tune behaviour
FlowExample.java
1 import java.awt.*;
2
3 public class FlowExample {
4 private Frame f;
5 private Button button1;
6 private Button button2;
7 private Button button3;
8
9 public FlowExample() {
10 f = new Frame("Flow Layout");
11 button1 = new Button("Ok");
12 button2 = new Button("Open");
13 button3 = new Button("Close");
14 }
15
16 public void launchFrame() {
17 f.setLayout(new FlowLayout());
18 f.add(button1);
19 f.add(button2);
20 f.add(button3);
21 f.setSize(100,100);
22 f.setVisible(true);
23 }
24
25 public static void main(String args[]) {
26 FlowExample guiWindow = new FlowExample();
27 guiWindow.launchFrame();
28 }
29 }
The BorderLayoutManager
• Default layout for the Frame class
• Components added to specific regions
• The resizing behavior:
t North, South, and Center regions adjust horizontally
t East, West, and Center regions adjust vertically
import java.awt.*;
2
3 public class BorderExample {
4 private Frame f;
5 private Button bn, bs, bw, be, bc;
6
7 public BorderExample() {
8 f = new Frame("Border Layout");
9 bn = new Button("B1");
10 bs = new Button("B2");
11 bw = new Button("B3");
12 be = new Button("B4");
13 bc = new Button("B5");
14 }
15
16 public void launchFrame() {
17 f.add(bn, BorderLayout.NORTH);
18 f.add(bs, BorderLayout.SOUTH);
19 f.add(bw, BorderLayout.WEST);
20 f.add(be, BorderLayout.EAST);
21 f.add(bc, BorderLayout.CENTER);
22 f.setSize(200,200);
23 f.setVisible(true);
24 }
25
26 public static void main(String args[]) {
27 BorderExample guiWindow2 = new BorderExample();
28 guiWindow2.launchFrame();
29
The GridLayoutManager
• Components are added left to right, top to bottom.
• All regions are equally sized.
• The constructor specifies the rows and columns.
GridExample.java
1 import java.awt.*;
2
3 public class GridExample {
4 private Frame f;
5 private Button b1, b2, b3, b4, b5, b6;
6
7 public GridExample() {
8 f = new Frame("Grid Example");
9 b1 = new Button("1");
10 b2 = new Button("2");
11 b3 = new Button("3");
12 b4 = new Button("4");
13 b5 = new Button("5");
14 b6 = new Button("6");
15 }
16
17 public void launchFrame() {
18 f.setLayout (new GridLayout(3,2));
19
20 f.add(b1);
21 f.add(b2);
22 f.add(b3);
23 f.add(b4);
24 f.add(b5);
25 f.add(b6);
26
27 f.pack();
28 f.setVisible(true);
29 }
30
31 public static void main(String args[]) {
32 GridExample grid = new GridExample();
33 grid.launchFrame();
34 }
35 }
import java.awt.*;
2
3 public class ComplexLayoutExample {
4 private Frame f;
5 private Panel p;
6 private Button bw, bc;
7 private Button bfile, bhelp;
8
9 public ComplexLayoutExample() {
10 f = new Frame("GUI example 3");
11 bw = new Button("West");
12 bc = new Button("Work space region");
13 bfile = new Button("File");
14 bhelp = new Button("Help");
15 }
16
17 public void launchFrame() {
18 // Add bw and bc buttons in the frame border
19 f.add(bw, BorderLayout.WEST);
20 f.add(bc, BorderLayout.CENTER);
21 // Create panel for the buttons in the north border
22 p = new Panel();
23 p.add(bfile);
24 p.add(bhelp);
25 f.add(p, BorderLayout.NORTH);
26 // Pack the frame and make it visible
27 f.pack();
28 f.setVisible(true);
29 }
30
31 public static void main(String args[]) {
32 ComplexLayoutExample gui = new ComplexLayoutExample();
33 gui.launchFrame();
34 }
35 }
Home
▼Java Tutorial
Introduction
Java Program Structure
Java Primitive data type
▼Development environment setup
Download and Install JDK, Eclipse (IDE)
Compiling, running and debugging Java programs
▼Declaration and Access control
Class, methods, instance variables
Java Packages
▼OOPS Concepts
Java Object Oriented Programming concepts
Is-A and Has-A relationship
▼Assignments
Arrays - 2D array and Multi dimension array
Wrapper classes
▼Operators
Assignment Operator
Arithmetic Operator
Conditional Operator
Logical Operator
▼Flow Control
Switch Satement
While and Do loop
For loop
Java Branching Statements
▼Exceptions
Handling Exceptions
Checked and unchecked
Custom Exception
Try with resource feature of Java 7
▼String Class
String Class
Important methods of String class with example
String buffer class and string builder class
▼File I/O and serialization
File Input and Output
Reading file
Writing file
Java Property File Processing
Java Serialization
▼Java Collection
Java Collection Framework
Java ArrayList and Vector
Java LinkedList Class
Java HashSet
Java TreeSet
Java Linked HashSet
Java Maps
Java Utility Class
▼Java Thread
Java Defining, Instantiating and Starting Thread
Java Thread States and Transitions
Java Thread Interaction
Java Code Synchronization
▼Miscellaneous
Java BigDecimal Class
Garbage Collection in Java
Java ArrayList Class
Description
One of the advantages of Object-Oriented programming language is code reuse. There are
two ways we can do code reuse either by implementation of inheritance (IS-A relationship),
or object composition (HAS-A relationship). Although the compiler and Java virtual machine
(JVM) will do a lot of work for you when you use inheritance, you can also get at the
functionality of inheritance when you use composition.
IS-A Relationship:
In object oriented programming, the concept of IS-A is a totally based on Inheritance, which
can be of two types Class Inheritance or Interface Inheritance. It is just like saying "A is a B
type of thing". For example, Apple is a Fruit, Car is a Vehicle etc. Inheritance is uni-
directional. For example House is a Building. But Building is not a House.
It is key point to note that you can easily identify the IS-A relationship. Wherever you see
an extends keyword or implements keyword in a class declaration, then this class is said to
have IS-A relationship.
HAS-A Relationship:
Composition(HAS-A) simply mean use of instance variables that are references to other
objects. For example: Maruti has Engine, or House has Bathroom.
1. package relationships;
2. class Car {
3. // Methods implementation and class/Instance members
4. private String color;
5. private int maxSpeed;
6. public void carInfo(){
7. System.out.println("Car Color= "+color + " Max Speed= " + maxSpeed);
8. }
9. public void setColor(String color) {
10. this.color = color;
11. }
12. public void setMaxSpeed(int maxSpeed) {
13. this.maxSpeed = maxSpeed;
14. }
15. }
As shown above Car class has couple of instance variable and few methods. Maruti is
specific type of Car which extends Car class means Maruti IS-A Car.
Maruti class uses Engine object’s start() method via composition. We can say that Maruti
class HAS-A Engine.
1. package relationships;
2. public class Engine {
3. public void start(){
4. System.out.println("Engine Started:");
5. }
6. public void stop(){
7. System.out.println("Engine Stopped:");
8. }
9. }
RelationsDemo class is making object of Maruti class and initialized it. Though Maruti class
does not have setColor(), setMaxSpeed() and carInfo() methods still we can use it due to
IS-A relationship of Maruti class with Car class.
1. package relationships;
2. public class RelationsDemo {
3. public static void main(String[] args) {
4. Maruti myMaruti = new Maruti();
5. myMaruti.setColor("RED");
6. myMaruti.setMaxSpeed(180);
7. myMaruti.carInfo();
8. myMaruti.MarutiStartDemo();
9. }
10. }
It is easier to change the class implementing composition than inheritance. The change
of a superclass impacts the inheritance hierarchy to subclasses.
You can't add to a subclass a method with the same signature but a different return type
as a method inherited from a superclass. Composition, on the other hand, allows you to
change the interface of a front-end class without affecting back-end classes.
Composition is dynamic binding (run time binding) while Inheritance is static binding
(compile time binding)
It is easier to add new subclasses (inheritance) than it is to add new front-end classes
(composition), because inheritance comes with polymorphism. If you have a bit of code
that relies only on a superclass interface, that code can work with a new subclass
without change. This is not true of composition, unless you use composition with
interfaces. Used together, composition and interfaces make a very powerful design tool.
With both composition and inheritance, changing the implementation (not the interface)
of any class is easy. The ripple effect of implementation changes remain inside the same
class.
Don't use inheritance just to get code reuse If all you really want is to reuse code
and there is no is-a relationship in sight, use composition.
Don't use inheritance just to get at polymorphism If all you really want is
polymorphism, but there is no natural is-a relationship, use composition with
interfaces.
Summary
IS-A relationship based on Inheritance, which can be of two types Class Inheritance or
Interface Inheritance.
Has-a relationship is composition relationship which is productive way of code reuse.
<<PreviousNext>>
We welcome contributions from you. You may contribute code, explanation, exercise with
solution on any topic listed in our Tutorials and Exercise Menu. Submit your contribution
through Disqus. Thanks.
©w3resource 2011-15
Privacy policy
About
Contact
Feedback
Advertise
What Is an Event?
• Events – Objects that describe what happened
• Event sources – The generator of an event
• Event handlers – A method that receives an event
object, deciphers it, and processes the user’s interaction
import java.awt.*;
2
3 public class TestButton {
4 private Frame f;
5 private Button b;
6
7 public TestButton() {
8 f = new Frame("Test");
9 b = new Button("Press Me!");
10 b.setActionCommand("ButtonPressed");
11 }
12
13 public void launchFrame() {
14 b.addActionListener(new ButtonHandler());
15 f.add(b,BorderLayout.CENTER);
16 f.pack();
17 f.setVisible(true);
18 }
19
20 public static void main(String args[]) {
21 TestButton guiApp = new TestButton();
22 guiApp.launchFrame();
23 }
24 }
1 import java.awt.event.*;
2
3 public class ButtonHandler implements ActionListener {
4 public void actionPerformed(ActionEvent e) {
5 System.out.println("Action occurred");
6 System.out.println("Button’s command is: "
7 + e.getActionCommand());
8}
9}
Delegation Model
• Client objects (handlers) register with a GUI
component they want to observe.
• GUI components only trigger the handlers for the type
of event that has occurred.
t Most components can trigger more than one type of
event.
• Distributes the work among multiple classes.
import java.util.*;
import java.io.*;
public class Program
{
static ArrayList al;
static Scanner scan;
static FileInputStream fin;
static FileOutputStream fout;
static ObjectInputStream ois;
static ObjectOutputStream oos;
public static void main(String []args)
{
al=new ArrayList();
scan=new Scanner(System.in);
while(true)
{
System.out.println("\n1. Add New Student");
System.out.println("2. Show All Student Details");
System.out.println("3. Update marks by Roll no");
System.out.println("4. Delete Student Details");
System.out.println("0. Exit");
System.out.println("\tEnter your Choice:");
int ch=scan.nextInt();
switch(ch)
{
case 1: addStudent();
break;
case 2: showAll() ;
break;
case 3: updateMarks();
break;
case 4:
break;
case 0:
default:
System.exit(0);
}
}
static void addStudent()
{
try
{
fout=new FileOutputStream("student.db");
oos=new ObjectOutputStream(fout);
oos.writeObject(al);
oos.close();
fout.close();
}
catch(Exception e)
{
System.out.println(e.toString());
}
}
public static void showAll()
{
try
{
boolean flag=false;
fin=new FileInputStream("student.db");
ois=new ObjectInputStream(fin);
al=(ArrayList)ois.readObject();
ois.close();
fin.close();
for(Object obj: al)
{
if(obj instanceof Student)
{
Student temp=(Student)obj;
System.out.println(temp.studentDet());
flag=true;
}
}
if(flag==false)
System.out.println("No record");
}
catch(Exception e)
{
System.out.println(e.toString());
}
}
public static void updateMarks()
{
System.out.print("New Student Roll:");
int r=scan.nextInt();
try
{
boolean flag=false;
fin=new FileInputStream("student.db");
ois=new ObjectInputStream(fin);
al=(ArrayList)ois.readObject();
ois.close();
fin.close();
for(Object obj: al)
{
if(obj instanceof Student)
{
Student temp=(Student)obj;
if(temp.getRoll()==r)
{
System.out.print("Found.\t Give new Marks:");
float m=scan.nextFloat();
temp.setMarks(m);
flag=true;
break;
}
}
}
if(flag==false)
System.out.println("Not exist");
else
{
fout=new FileOutputStream("student.db");
oos=new ObjectOutputStream(fout);
oos.writeObject(al);
oos.close();
fout.close();
System.out.println("Updated succ..");
}
}
catch(Exception e)
{
System.out.println(e.toString());
}
}
}
// Student Class
class Student implements Serializable
{
int roll;
String name;
float marks;
char grade;
public Student(int r, String n,float m)
{
roll=r; name=n;marks=m;calGrade();
}
private void calGrade()
{
if(marks>70)
grade='A';
else if(marks>50)
grade='B';
else
grade='C';
}
public String studentDet()
{
String res=roll+"\t"+name+"\t"+marks+"\t"+grade;
return res;
}
public int getRoll()
{
return roll;
}
public void setMarks(float m)
{
marks=m;;calGrade();
}
}
import java.io.*;
}
}
Creating a JDialog
import javax.swing.*;
import java.awt.*;
class JDialogExample extends JFrame
{
JDialog d1;
public JDialogExample()
{
createAndShowGUI();
}
// Set size
d1.setSize(400,400);
d1.add(new JButton("Button"));
d1.add(new JLabel("Label"));
d1.add(new JTextField(20));
setSize(400,400);
setVisible(true);
IT IS A CONSTANT VARIABLE AND HENCE, ITS VALUE CANNOT BE CHANGED
LATER ON WITHIN THE PROGRAM.
ITS VALUE HAS TO BE ASSIGNED IN THE SAME LINE WITHIN WHICH IT IS
DECLARED. EX: final int x = 12;
FINAL CLASS:
If any class is marked as final then it cannot be inherited.
FINAL METHOD:
Final methods cannot be overridden in the inherited class.
ENUMERATIONS:
It is a user-defined data type with user-defined data values.
Ex: enum PowerState {ON,OFF,SLEEP}
Here the data type is PowerState and its associated data values can be ON OFF SLEEP
Note that the Deque interface can be used both as last-in-first-out stacks and first-in-first-
out queues.
ARRAYDEQUE CLASS:
Resizable-array implementation of the Deque interface. Array deques have no capacity
restrictions; they grow as necessary to support usage. They are not thread-safe; in the
absence of external synchronization, they do not support concurrent access by multiple
threads. Null elements are prohibited. This class is likely to be faster than Stack when used
as a stack, and faster than LinkedList when used as a queue.
HASHSET CLASS IN JAVA:
HashSet extends AbstractSet class and implements the Set interface. It creates a collection that
uses a hash table for storage.
A hash table stores information by using a mechanism called hashing. In hashing, the
informational content of a key is used to determine a unique value, called its hash code.
The hash code is then used as the index at which the data associated with the key is stored. The
transformation of the key into its hash code is performed automatically.
HASHTABLE:
o A Hashtable is an array of list.Each list is known as a bucket.The position of bucket
is identified by calling the hashcode() method.A Hashtable contains values based on
the key. It implements the Map interface and extends Dictionary class.
o It contains only unique elements.
o It may have not have any null key or value.
It is synchronized.
It is a read-only loop
It is a forward-only loop
It is increment by 1 loop
It is much faster loop than for loop as it runs on less physical memory(RAM)
We do not require to know the end limit of the array. It is auto determined
It is a completely iterable loop i.e it will go from start to finish, no stopping inbetween.
Difference between AWT and Swing
There are many differences between java awt and swing that are given below.
3) AWT doesn't support pluggable look and Swing supports pluggable look
feel. and feel.
4) AWT provides less components than Swing. Swing provides more powerful
components such as tables,
lists, scrollpanes, colorchooser,
tabbedpane etc.
lOGGER FORM
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
bg = new ButtonGroup();
cont.setLayout(new GridLayout(3,1));
//adding components
cont.add(pRow1);
cont.add(pRow2);
cont.add(pRow3);
pRow1.add(lAuthenticate);
pRow2.setLayout(new GridLayout(3,2,80,40));
pRow2.add(lUserName);
pRow2.add(tfUserName);
pRow2.add(lPassword);
pRow2.add(pfPassword);
pRow2.add(rbAdmin);
pRow2.add(rbUser);
bg.add(rbAdmin);
bg.add(rbUser);
pRow3.setLayout(new FlowLayout());
pRow3.add(bLogin);
pRow3.add(bClear);
pRow3.add(bClose);
mWindow.add(miMin);
mWindow.add(miMax);
mWindow.add(miClose);
mb.add(mFile);
mb.add(mWindow);
mb.add(mHelp);
//setting action commands
bLogin.setActionCommand("bLogin");
bClear.setActionCommand("bClear");
bClose.setActionCommand("bClose");
miMin.setActionCommand("miMin");
miMax.setActionCommand("miMax");
miClose.setActionCommand("miClose");
//add listeners
bLogin.addActionListener(this);
bClear.addActionListener(this);
bClose.addActionListener(this);
miMin.addActionListener(this);
miMax.addActionListener(this);
miClose.addActionListener(this);
}
public void launchFrame()
{
setSize(400,600);
setVisible(true);
setTitle("LOGIN FORM");
setJMenuBar(mb);
}
public static void main(String[] args)
{
Logger l1 = new Logger();
l1.launchFrame();
}
@Override
public void actionPerformed(ActionEvent e)
{
String ac = e.getActionCommand();
switch(ac)
{
case "bLogin":
if(!rbAdmin.isSelected() && !rbUser.isSelected())
{
JOptionPane.showMessageDialog(this,"PLEASE SELECT LOGIN
TYPE --> ADMIN OR USER");
return;
}
if(tfUserName.getText().trim().equals(""))
{
JOptionPane.showMessageDialog(this,"USERNAME CANNOT BE
BLANK...");
clearAll();
return;
}
if(String.valueOf(pfPassword.getPassword()).trim().equals(""))
{
JOptionPane.showMessageDialog(this,"PASSWORD CANNOT BE
BLANK...");
clearAll();
return;
}
if(rbAdmin.isSelected())
{
if(tfUserName.getText().trim().equals("admin") &&
String.valueOf(pfPassword.getPassword()).equals("admin"))
{
JOptionPane.showMessageDialog(this,"ADMIN LOGIN
SUCCEEDED...");
clearAll();
}
else
{
JOptionPane.showMessageDialog(this,"INVALID ADMIN
LOGIN ATTEMPT...");
clearAll();
}
}
else
{
if(tfUserName.getText().trim().equals("user") &&
String.valueOf(pfPassword.getPassword()).equals("user"))
{
JOptionPane.showMessageDialog(this,"USER LOGIN
SUCCEEDED...");
clearAll();
}
else
{
JOptionPane.showMessageDialog(this,"INVALID USER
LOGIN ATTEMPT...");
clearAll();
}
}
break;
case "bClear":
clearAll();
break;
case "bClose":
int x = JOptionPane.showConfirmDialog
(this,"Are you sure to close ???","CLOSE FORM",
JOptionPane.OK_CANCEL_OPTION);
if(x == JOptionPane.OK_OPTION) this.dispose();
break;
case "miMin":
setState(JFrame.ICONIFIED);
break;
case "miMax":
setExtendedState(JFrame.MAXIMIZED_BOTH);
break;
case "miClose":
x = JOptionPane.showConfirmDialog
(this,"Are you sure to close ???","CLOSE FORM",
JOptionPane.OK_CANCEL_OPTION);
if(x == JOptionPane.OK_OPTION) this.dispose();
break;
}
private void clearAll()
{
tfUserName.setText("");
pfPassword.setText("");
tfUserName.requestFocus();
}
}
Finalize example
class FinalizeExample{
public void finalize(){System.out.println("finalize called");}
public static void main(String[] args){
FinalizeExample f1=new FinalizeExample();
FinalizeExample f2=new FinalizeExample();
f1=null;
f2=null;
System.gc();
}}
Java String
In java, string is basically an object that represents sequence of char values. An array of
characters works same as java string. For example:
char[] ch={'j','a','v','a','i','s','g','o','o','d'};
String s=new String(ch);
is same as:
String s="javaisgood";
Java String class provides a lot of methods to perform operations on string such as
compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring()
etc.
The java.lang.String class implements Serializable, Comparable and CharSequence
interfaces.
System.out.println(s1.equals(s2));//false
System.out.println(s1.equalsIgnoreCase(s2));//true
}
}
Java StringBuffer class is used to create mutable (modifiable) string. The StringBuffer class
in java is same as String class except it is mutable i.e. it can be changed.
Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it
simultaneously. So it is safe and will result in an order.
A string that can be modified or changed is known as mutable string. StringBuffer and
StringBuilder classes are used for creating mutable string.
1) StringBuffer append() method
The append() method concatenates the given argument with this string.
class StringBufferExample{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}
The insert() method inserts the given string with this string at the given position.
class StringBufferExample2{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}
3) StringBuffer replace() method
The replace() method replaces the given string from the specified beginIndex and
endIndex.
class StringBufferExample3{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}
class StringBufferExample4{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}
The capacity() method of StringBuffer class returns the current capacity of the buffer. The
default capacity of the buffer is 16. If the number of character increases from its current
capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current
capacity is 16, it will be (16*2)+2=34.
class StringBufferExample6{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
There are many differences between String and StringBuffer. A list of differences between
String and StringBuffer are given below:
No. String StringBuffer
1) String class is immutable. StringBuffer class is mutable.
2) String is slow and consumes more memory when you concat too many strings
because every time it creates new instance. StringBuffer is fast and consumes less
memory when you cancat strings.
3) String class overrides the equals() method of Object class. So you can compare the
contents of two strings by equals() method. StringBuffer class doesn't override the
equals() method of Object class.
}
}
The ensureCapacity() method of StringBuffer class ensures that the given capacity is the
minimum to the current capacity. If it is greater than the current capacity, it increases the
capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be
(16*2)+2=34.
class StringBufferExample7{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
sb.ensureCapacity(10);//now no change
System.out.println(sb.capacity());//now 34
sb.ensureCapacity(50);//now (34*2)+2
System.out.println(sb.capacity());//now 70
}
}
Difference between StringBuffer and StringBuilder
There are many differences between StringBuffer and StringBuilder. A list of differences
between StringBuffer and StringBuilder are given below:
No. StringBuffer StringBuilder
1) StringBuffer is synchronized i.e. thread safe. It means two threads can't call the
methods of StringBuffer simultaneously. StringBuilder is non-synchronized i.e. not thread
safe. It means two threads can call the methods of StringBuilder simultaneously.
2) StringBuffer is less efficient than StringBuilder. StringBuilder is more efficient than
StringBuffer.
Let's see the code to check the performance of StringBuffer and StringBuilder classes.
public class ConcatTest{
public static void main(String[] args){
long startTime = System.currentTimeMillis();
StringBuffer sb = new StringBuffer("Java");
for (int i=0; i<10000; i++){
sb.append("isgood");
}
System.out.println("Time taken by StringBuffer: " + (System.currentTimeMillis() -
startTime) + "ms");
startTime = System.currentTimeMillis();
StringBuilder sb2 = new StringBuilder("Java");
for (int i=0; i<10000; i++){
sb2.append("isgood");
}
System.out.println("Time taken by StringBuilder: " + (System.currentTimeMillis() -
startTime) + "ms");
}
}
Collections in Java
Collections in java is a framework that provides an architecture to store and manipulate the
group of objects.
All the operations that you perform on a data such as searching, sorting, insertion,
manipulation, deletion etc. can be performed by Java Collections.
Java Collection simply means a single unit of objects. Java Collection framework provides
many interfaces (Set, List, Queue, Deque etc.) and classes (ArrayList, Vector, LinkedList,
PriorityQueue, HashSet, LinkedHashSet, TreeSet etc).
What is Collection in java
Let us see the hierarchy of collection framework.The java.util package contains all the
classes and interfaces for Collection framework.
Methods of Collection interface
There are many methods declared in the Collection interface. They are as follows:
No. Method Description
1 public boolean add(Object element) is used to insert an element in this collection.
2 public boolean addAll(Collection c) is used to insert the specified collection elements
in the invoking collection.
3 public boolean remove(Object element) is used to delete an element from this
collection.
4 public boolean removeAll(Collection c) is used to delete all the elements of specified
collection from the invoking collection.
5 public boolean retainAll(Collection c) is used to delete all the elements of invoking
collection except the specified collection.
6 public int size() return the total number of elements in the collection.
7 public void clear() removes the total no of element from the collection.
8 public boolean contains(Object element) is used to search an element.
9 public boolean containsAll(Collection c) is used to search the specified collection in
this collection.
10 public Iterator iterator() returns an iterator.
11 public Object[] toArray() converts collection into array.
12 public boolean isEmpty() checks if collection is empty.
13 public boolean equals(Object element) matches two collection.
14 public int hashCode() returns the hashcode number for collection.
Iterator interface
Iterator interface provides the facility of iterating the elements in forward direction only.
Methods of Iterator interface
There are only three methods in the Iterator interface. They are:
No. Method Description
1 public boolean hasNext() It returns true if iterator has more elements.
2 public Object next() It returns the element and moves the cursor pointer to the next
element.
3 public void remove() It removes the last elements returned by the iterator. It is
rarely used.
Java ArrayList class uses a dynamic array for storing the elements. It inherits AbstractList
class and implements List interface.
Java LinkedList class uses doubly linked list to store the elements. It provides a linked-list
data structure. It inherits the AbstractList class and implements List and Deque interfaces.
Java HashSet class is used to create a collection that uses a hash table for storage. It
inherits the AbstractSet class and implements Set interface.
04
public class DateExample {
05
public static void main(String args[]) {
06
07
// Instantiate a Date object
08
Date date = new Date();
09
10
// Get current date and time
11
12
// 1st way: current time and date using toString()
13
System.out.println("Today's date is: "+date.toString());
14
15
// 2nd way: current time and date using SimpleDateFormat
16
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
17
System.out.println("Today's date is: "+dateFormat.format(date));
18
19
// Convert string to date
20
SimpleDateFormat dateformat2 = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
21
String strdate2 = "02-04-2013 11:35:42";
22
try {
23
Date newdate = dateformat2.parse(strdate2);
24
System.out.println(newdate);
25
} catch (ParseException e) {
26
e.printStackTrace();
27
}
28
29
30
// Date Comparison
31
32
// 1st way: using before(), after(), equals()
33
SimpleDateFormat dateformat3 = new SimpleDateFormat("dd/MM/yyyy");
34
try {
35
Date date1 = dateformat3.parse("17/07/1989");
36
Date date2 = dateformat3.parse("15/10/2007");
37
38
System.out.println("Date1 is: "+dateformat3.format(date1));
39
System.out.println("Date2 is: "+dateformat3.format(date2));
40
41
if (date1.after(date2)) {
42
System.out.println("Date1 is later than Date2");
43
}else if (date1.before(date2)) {
44
System.out.println("Date1 is earlier than Date2");
45
}else if (date1.equals(date2)) {
46
System.out.println("Date1 is the same with Date2");
47
}
48
49
// 2nd way: using compareTo()
50
date1 = dateformat3.parse("27/09/2012");
51
date2 = dateformat3.parse("27/09/2009");
52
53
System.out.println("Date1 is: "+dateformat3.format(date1));
54
System.out.println("Date2 is: "+dateformat3.format(date2));
55
56
if (date1.compareTo(date2) > 0) {
57
System.out.println("Date1 is later than Date2");
58
} else if (date1.compareTo(date2) < 0) {
59
System.out.println("Date1 is earlier than Date2");
60
} else if (date1.compareTo(date2) == 0) {
61
System.out.println("Date1 is the same with Date2");
62
}
63
64
} catch (ParseException e) {
65
e.printStackTrace();
66
}
67
68
}
69
}
G Era designator AD
m Minute in hour 30
s Second in minute 55
S Millisecond 234
w Week in year 40
W Week in month 1
a A.M./P.M. marker PM
Calendar
import java.util.*;
public class GregorianCalendarDemo {
public static void main(String args[]) {
String months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
"Oct", "Nov", "Dec"};
int year;
// Create a Gregorian calendar initialized
// with the current date and time in the
// default locale and timezone.