You are on page 1of 136

OOPS concepts has the following four features:

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:

 Every Constructor of a class calls its parent class non-parameterized constructor as


the first line of execution unless this default behavior is overridden by explicitly calling
any other constructor of its own class or parent class.
 If a class does not possess any constructor then the compiler itself supplies a non-
parameterized constructor to the class which is also known as the default constructor.
 Constructors are not inherited but they are called.
 Constructors of the parent class can be called using the “super” keyword and the
current class can be called using the “this” keyword.
=====EXCEPTION====
An exception is an abnormal condition arising due to wrong user input, network or
hardware failure, programming logic errors which causes abrupt termination of the running
program which is yet to be completed.
Exceptions are mainly of two kinds:

 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

 One Try-One Catch


 One Try-Multiple Catch
 One Try-One Catch-One finally
 One Try- Multiple Catch-One finally
 One Try-One finally

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:

 A Java source file can consist of multiple classes.


 If a source file consists of multiple classes then it is going to generate multiple class
files
 A class file consists of Byte Code.
 If a Java source consists of multiple classes then only one class can be public in
nature (if required).
 If a source file consists of a public class then the source file has to be of the same
name as that of the public class
 A non – static method cannot be directly used within a static method.
 A non – static variable cannot be used directly within a static method.
 A Java class cannot execute unless it consists of the main method rather it can help
other classes which may contain a main method.
 If you print an empty object of a class using System.out.println() function then it
prints the ClassName@Address in Hexadecimal. By default the object calls the
toString() method inherited from the object class.
 Whenever a class is created in Java it by defaults inherits the Object class present in
the java.lang package.
 Every program in java by default imports the java.lang package.
 A parent class object can be instantiated by the child class but the reverse is not true.
That object will run all the methods of the child class.

RULES OF INHERITANCE IN JAVA


 In java one class can inherit another single class only i.e java support multi-level
inheritance not multiple inheritance as viewed in C++.
 One class can inherit another class by using the “extends” keyword.
 All the non-private members except the constructors of the parent class are inherited
within the child class.
 The current class members can be referred using the “this” keyword and the parent
class members can be referred by using the “super” keyword.

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.

A Simple swing example


In the below example we would be using several swing components that you have not
learnt so far in this tutorial. We will be discussing each and everything in detail in the
coming swing tutorials.
The below swing program would create a login screen.

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 {

public static void main(String[] args) {


// Creating instance of JFrame
JFrame frame = new JFrame("My First Swing Example");
// Setting the width and height of frame
frame.setSize(350, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

/* Creating panel. This is same as a div tag in HTML


* We can create several panels and add them to specific
* positions in a JFrame. Inside panels we can add text
* fields, buttons and other components.
*/
JPanel panel = new JPanel();
// adding panel to frame
frame.add(panel);
/* calling user defined method for adding components
* to the panel.
*/
placeComponents(panel);
// Setting the frame visibility to true
frame.setVisible(true);
}

private static void placeComponents(JPanel panel) {

/* We will discuss about layouts in the later sections


* of this tutorial. For now we are setting the layout
* to null
*/
panel.setLayout(null);

// 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);

/* Creating text field where user is supposed to


* enter user name.
*/
JTextField userText = new JTextField(20);
userText.setBounds(100,20,165,25);
panel.add(userText);

// Same process for password label and text field.


JLabel passwordLabel = new JLabel("Password");
passwordLabel.setBounds(10,50,80,25);
panel.add(passwordLabel);

/*This is similar to text field but it hides the user


* entered data and displays dots instead to protect
* the password like we normally see on login screens.
*/
JPasswordField passwordText = new JPasswordField(20);
passwordText.setBounds(100,50,165,25);
panel.add(passwordText);

// Creating login button


JButton loginButton = new JButton("login");
loginButton.setBounds(10, 80, 80, 25);
panel.add(loginButton);
}
}
Output:

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”.

Swing – JButton tutorial and examples


CHAITANYA SINGH | FILED UNDER: SWING | UPDATED: JULY 17, 2015

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.

Swing JButton Example


This example shows how to create a button in a Swing application and how to add it to a
frame. Along with this, we will see various methods of JButton class.

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);

//Adding button onto the frame


frame.add(b);
// Setting Frame size. This is the window size
frame.setSize(300,200);

frame.setLayout(null);
frame.setVisible(true);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

public static void main(String[] args) {


new JButtonExample();
}
}
Output:
Some Useful JButton examples
You would find some useful code snippets in this section that you can use in your projects.

1) Adding image to JButton


The simplest way is this:

JButton b=new JButton(new ImageIcon("imageName.png"));


The above statement would work if you have the image in the folder where your Swing
program files are stored.
However if you have image in some other folder then do like this:
For example if you have programs in “src” folder and image in “src/resources” folder then
code it like this: This is the recommended way of adding image/icons to your buttons as this
will reduce the chances of any ambiguities further.

JButton button = new JButton();


try {
Image img = ImageIO.read(getClass().getResource("resources/myimage.png"));
button.setIcon(new ImageIcon(img));
} catch (IOException ex) {
}
Here is the complete code: Here I have a image play.gif placed in the folder where my
program files are.
import java.awt.Image;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.*;

public class JButtonIcon {


JButtonIcon(){
/* JFrame is a top level container (window)
* where we would be adding our button
*/
JFrame frame=new JFrame();

// 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);

//Adding button onto the frame


frame.add(b);
// Setting Frame size. This is the window size
frame.setSize(300,200);

frame.setLayout(null);
frame.setVisible(true);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

public static void main(String[] args) {


new JButtonIcon();
}
}
Output:
Objectives
• Describe the Abstract Windowing Toolkit (AWT)
package and its components
• Define the terms containers, components, and layout
managers, and describe how they work together to
build a graphical user interface (GUI)
• Use layout managers
• Use the FlowLayout, BorderLayout, and GridLayout
managers to achieve a desired dynamic layout
• Add components to a container
• Use the Frame and Panel containers appropriately
Containers
• Add components with the add() method.
• The two main types of containers are Window and
Panel.
• AWindow is a free floating window on the display.
• APanel is a container of GUI components that must
exist in the context of some other container, such as a
window or applet.
Positioning Components
• The position and size of a component in a container is
determined by a layout manager.
• You can control the size or position of components by
disabling the layout manager.
You must then use setLocation(), setSize(), or
setBounds() on components to locate them in the
container.

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 }

Hierarchy of Java Swing classes

The hierarchy of java swing API is given below.


w3resource
 Tutorials
 HTMLCSSJavaScriptHTML5BootstrapFoundation
3Schema.orgphp.jsJavaPHPPythonNodejsRubyCSQLMySQLOracle
11gPostgreSQLSQLiteNoSQLMongoDBRedisAJAXJSONXMLGoogle Plus APIYoutube
APIFirebugWebPWeb Dev ToolsExercises
 HTML CSSJavaScriptC Programming ExerciseC# Sharp
ExerciseJavaPHPPythonjQueryMySQLSQLPostgreSQL ExercisesSQLite
ExercisesMongoDB ExercisesTwitter Bootstrap ExamplesEuler ProjectPosts
 WordpressWebhostingjQueryJavaScriptCSS3MySQLSQLHTML5PHPLinux

Featured: SQL Exercises, MongoDB Exercises, SQL Injection Tutorial, SQL


Procedure,

 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

Inheritance (IS-A) vs. Composition (HAS-A) Relationship


Last update on March 25 2016 06:24:29 (UTC/GMT +8 hours)
<<PreviousNext>>

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.

Let’s understand these concepts with example of Car class.


view plaincopy to clipboardprint?

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.

view plaincopy to clipboardprint?

1. class Maruti extends Car{


2. //Maruti extends Car and thus inherits all methods from Car (except final and static)
3. //Maruti can also define all its specific functionality
4. public void MarutiStartDemo(){
5. Engine MarutiEngine = new Engine();
6. MarutiEngine.start();
7. }
8. }

Maruti class uses Engine object’s start() method via composition. We can say that Maruti
class HAS-A Engine.

view plaincopy to clipboardprint?

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.

view plaincopy to clipboardprint?

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. }

If we run RelationsDemo class we can see output like below.


Comparing Composition and Inheritance

 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.

Is this content useful for you?


YesNo
This work is licensed under a Creative Commons Attribution-NonCommercial-
ShareAlike 3.0 Unported License.

©w3resource.com 2011-16 | Privacy | About | Contact | Feedback | Advertise

 ©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
{

System.out.print("New Student Roll:");


int r=scan.nextInt();
System.out.print("New Student name:");
String nm=scan.next();
System.out.print("New Student Marks:");
float m=scan.nextFloat();
Student s=new Student(r,nm,m);
al.add(s);

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.*;

public class ObjectInputStreamDemo {

public static void main(String[] args) {

String s = "Hello World";


byte[] b = {'e', 'x', 'a', 'm', 'p', 'l', 'e'};
try {

// create a new file with an ObjectOutputStream


FileOutputStream out = new FileOutputStream("test.txt");
ObjectOutputStream oout = new ObjectOutputStream(out);

// write something in the file


oout.writeObject(s);
oout.writeObject(b);
oout.flush();

// create an ObjectInputStream for the file we created before


ObjectInputStream ois =
new ObjectInputStream(new FileInputStream("test.txt"));

// read and print an object and cast it as string


System.out.println("" + (String) ois.readObject());

// read and print an object and cast it as string


byte[] read = (byte[]) ois.readObject();
String s2 = new String(read);
System.out.println("" + s2);

} catch (Exception ex) {


ex.printStackTrace();
}

}
}
Creating a JDialog
import javax.swing.*;
import java.awt.*;
class JDialogExample extends JFrame
{
JDialog d1;

public JDialogExample()
{
createAndShowGUI();
}

private void createAndShowGUI()


{
setTitle("JDialog Example");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());

// Must be called before creating JDialog for


// the desired effect
JDialog.setDefaultLookAndFeelDecorated(true);
// A perfect constructor, mostly used.
// A dialog with current frame as parent
// a given title, and modal
d1=new JDialog(this,"This is title",true);

// Set size
d1.setSize(400,400);

// Set some layout


d1.setLayout(new FlowLayout());

d1.add(new JButton("Button"));
d1.add(new JLabel("Label"));
d1.add(new JTextField(20));

setSize(400,400);
setVisible(true);

// Like JFrame, JDialog isn't visible, you'll


// have to make it visible
// Remember to show JDialog after its parent is
// shown so that its parent is visible
d1.setVisible(true);
}

public static void main(String args[])


{
new JDialogExample();
}
}
FINAL VARIABLES:


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

STEPS TO CONNECT WITH ORACLE FROM JAVA:


A. KINDLY PROVIDE WITH THE FOLLOWING INFORMATION:
 HOSTNAME
 SID
 PORT NO
 USERNAME
 PASSWORD
B. CREATE AN URL(ADDRESS) FOR ORACLE CONNECTION USING:
 HOSTNAME
 PORTNO
 SID
C. REGISTER THE JAVA PROGRAM WITH ORACLE DRIVERS
D. CREATE THE CONNECTION WITH ORACLE USING THE FOLLOWING
INFORMATION:
 URL
 USERNAME
 PASSWORD

 AUTHENTICATION-IT IS THE PROCESS BY WHICH A USER IS IDENTIFIED BY A


SOFTWARE.

 AUTHORIZATION-IT IS THE PROCESS BY WHICH AN AUTHENTICATED USER IS


USED TO DETERMINE THE LEVEL OF USAGE OF THE SOFTWARE.
COLLECTION CLASSES IN JAVA
VECTOR CLASS:
The Vector class implements a growable array of objects. Like an array, it contains
components that can be accessed using an integer index. However, the size of a Vector
can grow or shrink as needed to accommodate adding and removing items after the Vector
has been created.
DEQUE INTERFACE:
Usually pronounced as deck, a deque is a double-ended-queue. A double-ended-queue is
a linear collection of elements that supports the insertion and removal of elements at both
end points. The Deque interface is a richer abstract data type than both Stack and Queue
because it implements both stacks and queues at the same time. The Deque interface,
defines methods to access the elements at both ends of the Deque instance. Methods are
provided to insert, remove, and examine the elements. Predefined classes like ArrayDeque
and LinkedList implement the Deque interface.

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.

CHARACTERISTICS OF FOREACH LOOP

 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.

No. Java AWT Java Swing

1) AWT components are platform-dependent. Java swing components are


platform-independent.

2) AWT components are heavyweight. Swing components are


lightweight.

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.

5) AWT doesn't follows MVC(Model View


Controller) where model represents data, view
represents presentation and controller acts as
an interface between model and view.

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;

public class Logger extends JFrame implements ActionListener


{
//declarations
private static final long serialVersionUID = 1L;
private JPanel pRow1,pRow2,pRow3;
private JLabel lAuthenticate,lUserName,lPassword;
private JTextField tfUserName;
private JPasswordField pfPassword;
private JRadioButton rbAdmin,rbUser;
private ButtonGroup bg;
private JButton bLogin,bClear,bClose;
private JMenuBar mb;
private JMenu mFile,mWindow,mHelp;
private JMenuItem miMin,miMax,miClose;
Container cont;
public Logger()
{
//instantiation
pRow1 = new JPanel();
pRow2 = new JPanel();
pRow3 = new JPanel();

lAuthenticate = new JLabel("AUTHENTICATE YOURSELF!!!");


lUserName = new JLabel("USERNAME");
lPassword = new JLabel("PASSWORD");

tfUserName = new JTextField(20);

pfPassword = new JPasswordField(20);

rbAdmin = new JRadioButton("Admin");


rbUser = new JRadioButton("User");

bg = new ButtonGroup();

bLogin = new JButton("LOGIN");


bClear = new JButton("CLEAR");
bClose = new JButton("CLOSE");
mb = new JMenuBar();

mFile = new JMenu("FILE");


mWindow = new JMenu("WINDOW");
mHelp = new JMenu("HELP");

miMin = new JMenuItem("MINIMIZE");


miMax = new JMenuItem("MAXIMIZE");
miClose = new JMenuItem("CLOSE");
cont = getContentPane();

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();
}
}

MONOLITHIC : Entire software contained within a single file only.


MODULER : Entire software divided into multiple files

Difference between final, finally and finalize


There are many differences between final, finally and finalize. A list of differences between
final, finally and finalize are given below:
No.
final
finally
finalize
1)
Final is used to apply restrictions on class, method and variable. Final class can't be
inherited, final method can't be overridden and final variable value can't be changed.
Finally is used to place important code, it will be executed whether exception is handled or
not.
Finalize is used to perform clean up processing just before object is garbage collected.
2)
Final is a keyword.
Finally is a block.
Finalize is a method.

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.

String compare by == operator


class Teststringcomparison3{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
System.out.println(s1==s2);//true (because both refer to same instance)
System.out.println(s1==s3);//false(because s3 refers to instance created in nonpool)
}
}
3) String compare by compareTo() method
The String compareTo() method compares values lexicographically and returns an integer
value that describes if first string is less than, equal to or greater than second string.
Suppose s1 and s2 are two string variables. If:
s1 == s2 :0
s1 > s2 :positive value
s1 < s2 :negative value
class Teststringcomparison4{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
System.out.println(s1.compareTo(s2));//0
System.out.println(s1.compareTo(s3));//1(because s1>s3)
System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
}
}
Immutable String in Java
In java, string objects are immutable. Immutable simply means unmodifiable or
unchangeable.
Once string object is created its data or state can't be changed but a new string object is
created.
class Testimmutablestring{
public static void main(String args[]){
String s="Sachin";
s.concat(" Tendulkar");//concat() method appends the string at the end
System.out.println(s);//will print Sachin because strings are immutable objects
}
}
class Testimmutablestring1{
public static void main(String args[]){
String s="Sachin";
s=s.concat(" Tendulkar");
System.out.println(s);
}
}

Java String compare

We can compare string in java on the basis of content and reference.


It is used in authentication (by equals() method), sorting (by compareTo() method),
reference matching (by == operator) etc.
There are three ways to compare string in java:
By equals() method
By = = operator
By compareTo() method
1) String compare by equals() method
The String equals() method compares the original content of the string. It compares values
of string for equality. String class provides two methods:
public boolean equals(Object another) compares this string to the specified object.
public boolean equalsIgnoreCase(String another) compares this String to another string,
ignoring case.
class Teststringcomparison1{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
String s4="Saurav";
System.out.println(s1.equals(s2));//true
System.out.println(s1.equals(s3));//true
System.out.println(s1.equals(s4));//false
}
}
class Teststringcomparison2{
public static void main(String args[]){
String s1="Sachin";
String s2="SACHIN";

System.out.println(s1.equals(s2));//false
System.out.println(s1.equalsIgnoreCase(s2));//true
}
}

Java StringBuffer class

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.

What is mutable string

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
}
}

2) StringBuffer insert() method

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
}
}

4) StringBuffer delete() method


The delete() method of StringBuffer class deletes the string from the specified beginIndex
to endIndex.

class StringBufferExample4{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}

5) StringBuffer reverse() method

The reverse() method of StringBuilder class reverses the current string.


class StringBufferExample5{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}

6) StringBuffer capacity() method

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

Difference between String and StringBuffer

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.

}
}

7) StringBuffer ensureCapacity() method

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.

Performance Test of StringBuffer and StringBuilder

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

Java Collection Framework


Hierarchy of Collection Framework
Collection interface
Iterator interface

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

Collection represents a single unit of objects i.e. a group.


What is framework in java

provides readymade architecture.


represents set of classes and interface.
is optional.

What is Collection framework


Collection framework represents a unified architecture for storing and manipulating group of
objects. It has:

Interfaces and its implementations i.e. classes


Algorithm

Hierarchy of Collection Framework

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


Java ArrayList class hierarchy

Java ArrayList class uses a dynamic array for storing the elements. It inherits AbstractList
class and implements List interface.

The important points about Java ArrayList class are:

Java ArrayList class can contain duplicate elements.


Java ArrayList class maintains insertion order.
Java ArrayList class is non synchronized.
Java ArrayList allows random access because array works at the index basis.
In Java ArrayList class, manipulation is slow because a lot of shifting needs to be
occurred if any element is removed from the array list.

Java LinkedList class


Java LinkedList class hierarchy

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.

The important points about Java LinkedList are:

Java LinkedList class can contain duplicate elements.


Java LinkedList class maintains insertion order.
Java LinkedList class is non synchronized.
In Java LinkedList class, manipulation is fast because no shifting needs to be occurred.
Java LinkedList class can be used as list, stack or queue.

Java HashSet class


Java HashSet class hierarchy

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.

The important points about Java HashSet class are:

HashSet stores the elements by using a mechanism called hashing.


HashSet contains unique elements only.

Difference between List and Set


List can contain duplicate elements whereas Set contains unique elements only.

Date example in java


import java.util.*;
02
import java.text.*;
03

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
}

Simple DateFormat Format Codes


To specify the time format, use a time pattern string. In this pattern, all ASCII letters are reserved as pattern
letters, which are defined as the following −

Character Description Example

G Era designator AD

y Year in four digits 2001

M Month in year July or 07


d Day in month 10

h Hour in A.M./P.M. (1~12) 12

H Hour in day (0~23) 22

m Minute in hour 30

s Second in minute 55

S Millisecond 234

E Day in week Tuesday

D Day in year 360

F Day of week in month 2 (second Wed. in July)

w Week in year 40
W Week in month 1

a A.M./P.M. marker PM

k Hour in day (1~24) 24

K Hour in A.M./P.M. (0~11) 10

z Time zone Eastern Standard Time

' Escape for text Delimiter

" Single quote

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.

GregorianCalendar gcalendar = new GregorianCalendar();

// Display current time and date information.


System.out.print("Date: ");
System.out.print(months[gcalendar.get(Calendar.MONTH)]);
System.out.print(" " + gcalendar.get(Calendar.DATE) + " ");
System.out.println(year = gcalendar.get(Calendar.YEAR));
System.out.print("Time: ");
System.out.print(gcalendar.get(Calendar.HOUR) + ":");
System.out.print(gcalendar.get(Calendar.MINUTE) + ":");
System.out.println(gcalendar.get(Calendar.SECOND));

// Test if the current year is a leap year


if(gcalendar.isLeapYear(year)) {
System.out.println("The current year is a leap year");
}else {
System.out.println("The current year is not a leap year");
}
}
}
Serialization: Conversion of any Java Objects into network transferrable format/file storage
format.
DeSerialization : Conversion of any network/file stream back to Java Object is called
Deserialization
TreeMap Class:
A TreeMap contains values based on the key. It implements the NavigableMap interface
and extends AbstractMap class.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order.

You might also like