COM211_JAVA2 ND2 1st Sem
COM211_JAVA2 ND2 1st Sem
ARRAYS
Arrays of Primitive Data Types
An array is a collection of similar data types. Array is a container object that holds values of
homogenous type. It is also known as static data structure because its size must be specified at the time
of its declaration.
An array can be either primitive or reference type. The Index of array starts from zero to size-1.
Array Declaration
Syntax :
Datatype [] identifier;
OR
Datatype identifier [];
Both are valid syntax for array declaration. But the former is more readable.
Example :
int[] arr;
char[] arr;
short[] arr;
long[] arr;
int[][] arr; //two dimensional array.
Initialization of Array
Example :
As mentioned earlier on, array index starts from 0. To access the nth element of an array, the following
syntax is used:
arrayName[n-1];
int[] arr={10,20,30,40};
System.out.println("Element at 4th place"+arr[3]);
The above code will print the 4th element of array arr on console.
Page 2 of 31
J2SE 5 introduces special type of for loop called foreach loop to access elements of array. Using
foreach loop you can access complete array sequentially without using index of array. Let us see an
example of foreach loop.
Class Arraydemo
{
Public static void main(String[] args)
{
int[] arr={10,20,30,40};
for(int x:arr)
{
System.out.println(x);
}
}
}
Output:
10
20
30
40
Array Types
Array types are the second kind of reference types in Java. An array is an ordered collection, or
numbered list, of values. The values can be primitive values, objects, or even other arrays, but all of the
values in an array must be of the same type. The type of the array is the type of the values it holds,
followed by the characters [].
For example:
int[] arrayOfIntegers; // int[] is an array type: array of integer
byte b; // byte is a primitive type
byte[] arrayOfBytes; // byte[] is an array type: array of byte
byte[][] arrayOfArrayOfBytes; // byte[][] is another type: array of byte[]
Point[] points; // Point[] is an array of Point objects
Creating Arrays
To create an array value in Java, you use the new keyword, just as you do to create an object. Arrays
don't need to be initialized like objects do, however, so you don't pass a list of arguments between
parentheses. What you must specify, though, is how big you want the array to be. If you are creating a
byte[], for example, you must specify how many byte values you want it to hold. Array values have a
fixed size in Java. Once an array is created, it can never grow or shrink. Specify the desired size of your
array as a non-negative integer between square brackets:
Multidimensional Arrays
Addition of 2 matrices in java By using two dimensional array
Page 3 of 31
Example:
Class Arraydemo {
Public static void main(String args[]){
//creating two matrices
int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};
Output:
268
6 8 10
The new keyword performs this additional initialization automatically for you. It works with arrays with
more than two dimensions as well:
When using new with multidimensional arrays, you do not have to specify a size for all dimensions of
the array, only the leftmost dimension or dimensions. For example, the following two lines are legal:
The first line creates a single-dimensional array, where each element of the array can hold a float[][].
The second line creates a two-dimensional array, where each element of the array is a float[]. If you
specify a size for only some of the dimensions of an array, however, those dimensions must be the
leftmost ones. The following lines are not legal:
As we all know, the Java programming language is all about objects as it is an object-oriented
programming language.
If you want to store a single object in your program, then you can do so with the help of a variable of
type object. But when you are dealing with numerous objects, then it is advisable to use an array of
objects.
Page 4 of 31
Java is capable of storing objects as elements of the array along with other primitive and custom data
types. Note that when you say ‘array of objects’, it is not the object itself that is stored in the array but
the references of the object.
Java is an object-oriented programming language. We know that an array is a collection of the same
data type that dynamically creates objects and can have elements of primitive types. Java allows us to
store objects in an array. In Java, the class is also a user-defined data type. An array that conations class
type elements are known as an array of objects. It stores the reference variable of the object.
Class_name [] objArray;
Class_name objArray[];
So, if you have a class ‘Employee’ then you can create an array of Employee objects as given
below:
Employee[] empObjects;
OR
Employee empObjects[];
The declarations of the array of objects above will need to be instantiated using ‘new’ before being used
in the program.
You can declare and instantiate the array of objects as shown below:
Note that once an array of objects is instantiated like above, the individual elements of the array of
objects need to be created using ‘new’.
Page 5 of 31
The above statement will create an array of objects ‘empObjects’ with 2 elements/object references.
Once the array of objects is instantiated, you have to initialize it with values. As the array of objects is
different from an array of primitive types, you cannot initialize the array in the way you do with
primitive types.
In the case of an array of objects, each element of array i.e. an object needs to be initialized. We already
discussed that an array of objects contains references to the actual class objects. Thus, once the array of
objects is declared and instantiated, you have to create actual objects of the class.
One way to initialize the array of objects is by using the constructors. When you create actual objects,
you can assign initial values to each of the objects by passing values to the constructor. You can also
have a separate member method in a class that will assign data to the objects.
The following program shows the initialization of array objects using the constructor.
Here we have used the class Employee. The class has a constructor that takes in two parameters i.e.
employee name and employee Id. In the main function, after an array of employees is created, we go
ahead and create individual objects of the class employee.
Then we pass initial values to each of the objects using the constructor.
The output of the program shows the contents of each object that was initialized previously.
Example 1
Class Main{
obj[0].showData();
obj[1].showData();
Class Employee{
int empId;
String name;
empId = eid;
name = n;
System.out.println();
Exercise:
Write the above code in any editor and run the code to get the output. Copy out the output and/or print.
Example 2:
The example program that we have given below shows a member function of the Employee class that is
used to assign the initial values to the Employee objects.
Given is a complete example that demonstrates the array of objects in Java. In this program, we have an
Employee class that has employee Id (empId) and employee name (name) as fields and ‘setData’ &
‘showData’ as methods that assign data to employee objects and display the contents of employee
objects respectively.
In the main method of the program, we first define an array of Employee objects. Note that this is an
array of references and not actual objects. Then using the default constructor, we create actual objects
for the Employee class. Next, the objects are assigned data using the setData method.
Lastly, objects invoke the showData method to display the contents of the Employee class objects.
Class Main{
obj[0].setData(100,"ABC");
obj[1].setData(200,"XYZ");
obj[0].showData();
obj[1].showData();
Class Employee{
int empId;
String name;
empId=c;
name=d;
System.out.println();
Exercise:
Write the above code in any editor and run the code to get the output. Copy out the output and/or print.
Example 3
In the following program, we have created a class named Product and initialized an array of objects
using the constructor. We have created a constructor of the class Product that contains product id and
product name. In the main function, we have created individual objects of the class Product. After that,
we have passed initial values to each of the objects using the constructor.
ArrayOfObjects.java
15. obj[0].display();
16. System.out.println("Product Object 2:");
17. obj[1].display();
18. System.out.println("Product Object 3:");
19. obj[2].display();
20. System.out.println("Product Object 4:");
21. obj[3].display();
22. System.out.println("Product Object 5:");
23. obj[4].display();
24. }
25. }
26. //Product class with product Id and product name as attributes
33. {
34. pro_Id = pid;
35. pro_name = n;
36. }
41. }
42. }
Output:
Product Object 1:
Product Id = 23907 Product Name = Dell Laptop
Product Object 2:
Product Id = 91240 Product Name = HP 630
Product Object 3:
Product Id = 29823 Product Name = LG OLED TV
Product Object 4:
Product Id = 11908 Product Name = MI Note Pro Max 9
Product Object 5:
Product Id = 43590 Product Name = Kingston USB
Zero-based indexing. We always refer to the first element of an array a[] as a[0], the second as
a[1], and so forth. It might seem more natural to you to refer to the first element as a[1], the
second value as a[2], and so forth, but starting the indexing with 0 has some advantages and has
emerged as the convention used in most modern programming languages.
Array length. Once we create an array, its length is fixed. You can refer to the length of an a[] in
your program with the code a.length.
Default array initialization. For economy in code, we often take advantage of Java's default
array initialization convention. For example, the following statement is equivalent to the four
lines of code at the top of this page:
The default initial value is 0 for all numeric primitive types and false for type boolean.
Memory representation. When you use new to create an array, Java reserves space in memory
for it (and initializes the values). This process is called memory allocation.
Bounds checking. When programming with arrays, you must be careful. It is your responsibility
to use legal indices when accessing an array element.
Setting array values at compile time. When we have a small number of literal values that we
want to keep in array, we can initialize it by listing the values between curly braces, separated by
Page 10 of 31
a comma. For example, we might use the following code in a program that processes playing
cards.
String[] SUITS = {
"Clubs", "Diamonds", "Hearts", "Spades"
};
String[] RANKS = {
"2", "3", "4", "5", "6", "7", "8", "9", "10",
"Jack", "Queen", "King", "Ace"
};
After creating the two arrays, we might use them to print a random card name such as Queen of
Clubs, as follows.
Setting array values at run time. A more typical situation is when we wish to compute the values
to be stored in an array. For example, we might use the following code to initialize an array of
length 52 that represents a deck of playing cards, using the arrays RANKS[] and SUITS[] just
defined.
Two-dimensional arrays.
In many applications, a natural way to organize information is to use a table of numbers organized in a
rectangle and to refer to rows and columns in the table. The mathematical abstraction corresponding to
such tables is a matrix; the corresponding Java construct is a two-dimensional array.
Two-dimensional arrays in Java. To refer to the element in row i and column j of a two-
dimensional array a[][], we use the notation a[i][j]; to declare a two-dimensional array, we add
another pair of brackets; to create the array, we specify the number of rows followed by the
number of columns after the type name (both within brackets), as follows:
We refer to such an array as an m-by-n array. By convention, the first dimension is the number
of rows and the second dimension is the number of columns.
Default initialization. As with one-dimensional arrays, Java initializes all entries in arrays of
numbers to 0 and in arrays of booleans to false. Default initialization of two-dimensional arrays
is useful because it masks more code than for one-dimensional arrays. To access each of the
elements in a two-dimensional array, we need nested loops:
double[][] a;
a = new double[m][n];
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
a[i][j] = 0;
double[][] a = {
{ 99.0, 85.0, 98.0, 0.0 },
{ 98.0, 57.0, 79.0, 0.0 },
{ 92.0, 77.0, 74.0, 0.0 },
{ 94.0, 62.0, 81.0, 0.0 },
{ 99.0, 94.0, 92.0, 0.0 },
{ 80.0, 76.5, 67.0, 0.0 },
{ 76.0, 58.5, 90.5, 0.0 },
{ 92.0, 66.0, 91.0, 0.0 },
{ 97.0, 70.5, 66.5, 0.0 },
{ 89.0, 89.5, 81.0, 0.0 },
{ 0.0, 0.0, 0.0, 0.0 }
};
Ragged arrays. There is no requirement that all rows in a two-dimensional array have the same
length—an array with rows of nonuniform length is known as a ragged array. The possibility of
Page 12 of 31
ragged arrays creates the need for more care in crafting array-processing code. For example, this
code prints the contents of a ragged array:
Multidimensional arrays. The same notation extends to arrays that have any number of
dimensions. For instance, we can declare and initialize a three-dimensional array with the code
Matrix operations.
Typical applications in science and engineering involve implementing various mathematical operations
with matrix operands. For example, we can add two n-by-n matrices as follows:
double[][] c = new double[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
c[i][j] = a[i][j] + b[i][j];
}
}
Similarly, we can multiply two matrices. Each entry c[i][j] in the product of a[] and b[] is computed
by taking the dot product of row i of a[] with column j of b[].
Exercises
1. Describe and explain what happens when you try to compile a program HugeArray.java with the
following statement:
int n = 1000;
int[] a = new int[n*n*n*n];
Page 13 of 31
2. Write a code fragment that reverses the order of values in a one-dimensional string array. Do not create
another array to hold the result. Hint: Use the code in the text for exchanging two elements.
Solution.
int n = a.length;
for (int i = 0; i < n/2; i++) {
String temp = a[n-i-1];
a[n-i-1] = a[i];
a[i] = temp;
}
int[] a;
for (int i = 0; i < 10; i++)
a[i] = i * i;
Solution: It does not allocate memory for a[] with new. The code results in a variable might
not have been initialized compile-time error.
int[] a = { 1, 2, 3 };
int[] b = { 1, 2, 3 };
System.out.println(a == b);
Solution: It prints false. The == operator compares whether the (memory addresses of the) two arrays
are identical, not whether their corresponding values are equal.
5. Write a program Deal.java that takes an integer command-line argument n and prints n poker hands
(five cards each) from a shuffled deck, separated by blank lines.
6. Write a program HowMany.java that takes a variable number of command-line arguments and prints
how many there are.
7. Write a program DiscreteDistribution.java that takes a variable number of integer command-line
arguments and prints the integer i with probability proportional to the ith command-line argument.
8. Write a code fragment Transpose.java to transpose a square two-dimensional array in place without
creating a second array.
Constructor is a block of code that initializes the newly created object. A constructor resembles an
instance method in java but it’s not a method as it doesn’t have a return type. In short constructor and
method are different. People often refer constructor as special type of method in Java.
Constructor has same name as the class and looks like this in a java code.
Note that the constructor name matches with the class name and it doesn’t have a return type.
To understand the working of constructor, let’s take an example. lets say we have a class MyClass.
When we create the object of MyClass like this:
The new keyword here creates the object of class MyClass and invokes the constructor to initialize this
newly created object.
Output:
Types of Constructors
There are three types of constructors: Default, No-arg. Constructor and Parameterized.
Default Constructor
If you do not implement any constructor in your class, Java compiler inserts a default constructor into
your code on your behalf. This constructor is known as default constructor. You would not find it in
your source code (the java file) as it would be inserted into the code during compilation and exists
in .class file.
If you implement any constructor then you no longer receive a default constructor from Java compiler.
No-Arg Constructor:
Constructor with no arguments is known as no-arg constructor. The signature is same as default
constructor; however body can have any code unlike default constructor where the body of the
constructor is empty.
Although you may see some people claim that that default and no-arg constructor is same but in fact
they are not, even if you write public Demo() { } in your class Demo it cannot be called default
constructor since you have written the code of it.
Output:
This is a no argument constructor
Parameterized Constructor
Constructor with arguments (or you can say parameters) is known as Parameterized constructor.
In this example we have a parameterized constructor with two parameters id and name. While creating
the objects obj1 and obj2; two arguments have been passed so that this constructor gets invoked after
creation of obj1 and obj2.
Int empId;
Page 16 of 31
String empName;
Output:
Id:10245 Name:Chaitanya
Id:92232 Name:Negan
Example2: Parameterized Constructor
In this example, we have two constructors, a default constructor and a parameterized constructor. When
we do not pass any parameter while creating the object using new keyword then default constructor is
invoked, however when you pass a parameter then parameterized constructor that matches with the
passed parameters list gets invoked.
Class Example2
{
Private int var;
//default constructor
Public Example2()
{
this.var=10;
}
//parameterized constructor
Public Example2(int num)
{
this.var=num;
}
Public int getValue()
{
Return var;
}
Public static void main(Stringargs[])
{
Example2 obj=new Example2();
Example2 obj2 =new Example2(100);
System.out.println("var is: "+obj.getValue());
System.out.println("var is: "+obj2.getValue());
}
}
Page 17 of 31
Output:
varis:10
varis:100
Calling a constructor from the another constructor of same class is known as Constructor chaining. The
real purpose of Constructor Chaining is that you can pass parameters through a bunch of different
constructors, but only have the initialization done in a single place. This allows you to maintain your
initializations from a single location, while providing multiple constructors to the user. If we don’t
chain, and two different constructors require a specific parameter, you will have to initialize that
parameter twice, and when the initialization changes, you’ll have to change it in every constructor,
instead of just the one.
As a rule, constructors with fewer arguments should call those with more
In this example, we have several constructors, one constructor is calling another constructor using this
keyword. this() should always be the first statement in constructor otherwise you will get this error
message: Exception in thread “main” java.lang.Error: Unresolved compilation problem:
Constructor call must be the first statement in a constructor
Class Employee
Page 18 of 31
{
Public String empName;
Public int empSalary;
Public String address;
Void disp(){
System.out.println("Employee Name: "+empName);
System.out.println("Employee Salary: "+empSalary);
System.out.println("Employee Address: "+address);
}
Public static void main(String[]args)
{
Employee obj=new Employee();
obj.disp();
}
}
Output:
Employee Name:Charity
Employee Salary:120035
Employee Address:Mkar
Like methods, constructors can also be overloaded. In this guide we will see Constructor overloading
with the help of examples. Before we proceed further let’s understand what is constructor overloading
and why we do it.
Page 19 of 31
Constructor overloading is a concept of having more than one constructor with different parameters list,
in such a way so that each constructor performs a different task. For e.g. Vector class has 4 types of
constructors. If you do not want to specify the initial capacity and capacity increment then you can
simply use default constructor of Vector class like this Vector v = new Vector(); however if you
need to specify the capacity and increment then you call the parameterized constructor of Vector class
with two int arguments like this:
Here we are creating two objects of class StudentData. One is with default constructor and another one
using parameterized constructor. Both the constructors have different initialization code, similarly you
can create any number of constructors with different-2 initialization codes for different-2 purposes.
StudentData.java
Class StudentData
{
Private int stuID;
Private String stuName;
Private int stuAge;
StudentData()
{
//Default constructor
stuID=100;
stuName="New Student";
stuAge=18;
}
StudentData(int num1,String str,int num2)
{
//Parameterized constructor
stuID= num1;
stuName=str;
stuAge= num2;
}
//Getter and setter methods
Public int getStuID(){
return stuID;
}
Public void setStuID(int stuID){
this.stuID=stuID;
}
Public String getStuName(){
return stuName;
}
Public void setStuName(String stuName){
this.stuName = stuName;
}
Public int getStuAge(){
return stuAge;
}
Public void setStuAge(int stuAge){
Page 20 of 31
this.stuAge=stuAge;
}
Output:
Quick Recap
1. Every class has a constructor whether it’s a normal class or a abstract class.
2. Constructors are not methods and they don’t have any return type.
3. Constructor name should match with class name .
4. Constructor can use any access specifier, they can be declared as private also. Private constructors are
possible in java but there scope is within the class only.
5. Like constructors method can also have name same as class name, but still they have return type,
though which we can identify them that they are methods not constructors.
6. If you don’t implement any constructor within the class, compiler will do it for.
7. this() and super() should be the first statement in the constructor code. If you don’t mention them,
compiler does it for you accordingly.
8. Constructor overloading is possible but overriding is not possible. Which means we can have
overloaded constructor in our class but we can’t override a constructor.
9. Constructors cannot be inherited.
10. If Super class doesn’t have a no-arg(default) constructor then compiler would not insert a default
constructor in child class as it does in normal scenario.
11. Interfaces do not have constructors.
12. Abstract class can have constructor and it gets invoked when a class, which implements interface, is
instantiated. (i.e. object creation of concrete class).
13. A constructor can also invoke another constructor of the same class – By using this(). If you want to
invoke a parameterized constructor then do it like this: this (parameter list).
Page 21 of 31
1. The purpose of constructor is to initialize the object of a class while the purpose of a method is to
perform a task by executing java code.
2. Constructors cannot be abstract, final, static and synchronised while methods can be.
3. Constructors do not have return types while methods do.
Event-driven Programming
Event-driven programs can be written in any programming language, although some languages(Visual
Basic for example) are specifically designed to facilitate event-driven programming, and provide an
integrated development environment (IDE) that partially automates the production of code, and provides
a comprehensive selection of built-in objects and controls, each of which can respond to a range of
events. Virtually all object-oriented and visual languages support event-driven programming. Visual
Basic, Visual C++ and Java are examples of such languages.
One of the fundamental ideas behind object-oriented programming is that of representing programmable
entities as objects. An entity in this context could be literally anything with which the application is
concerned. A program dealing with tracking the progress of customer orders for a manufacturing
company, for example, might involve objects such as "customer", "order", and "order item".
An object encompasses both the data (attributes) that can be stored about an entity, the actions
(methods) that can be used to access or modify the entity’s attributes, and the events that can cause the
entity's methods to be invoked.
The central element of an event-driven application is a scheduler that receives a stream of events and
passes each event to the relevant event-handler. The scheduler will continue to remain active until it
encounters an event (e.g. "End_Program") that causes it to terminate the application. Under certain
circumstances, the scheduler may encounter an event for which it cannot assign an appropriate event
handler. Depending on the nature of the event, the scheduler can either ignore it or raise an exception
(this is sometimes referred to as "throwing" an exception).
Events are often actions performed by the user during the execution of a program, but can also be
messages generated by the operating system or another application, or an interrupt generated by a
peripheral device or system hardware. If the user clicks on a button with the mouse or hits the Enter
key, it generates an event. If a file download completes, it generates an event. And if there is a hardware
or software error, it generates an event.
The events are dealt with by a central event-handler (usually called a dispatcher or scheduler) that runs
continuously in the background and waits for an even to occur. When an event does occur, the scheduler
must determine the type of event and call the appropriate event-handler to deal with it. The information
Page 22 of 31
passed to the event handler by the scheduler will vary, but will include sufficient information to allow
the event-handler to take any action necessary.
Event-handlers can be seen as small blocks of procedural code that deal with a very specific occurrence.
They will usually produce a visual response to inform or direct the user, and will often change the
system’s state. The state of the system encompasses both the data used by the system (e.g. the value
stored in a database field), and the state of the user interface itself (for example, which on-screen object
currently has the focus, or the background colour of a text box).
An event handler may even trigger another event too occur that will cause a second event-handler to be
called (note that care should be taken when writing event handlers that invoke other event-handlers, in
order to avoid the possibility of putting the application into an infinite loop). Similarly, an event-handler
may cause any queued events to be discarded (for example, when the user clicks on the Quit button to
terminate the program).The diagram below illustrates the relationship between events, the scheduler,
and the application’s event-handlers.
UI Elements − These are the core visual elements the user eventually sees and interacts with.
GWT provides a huge list of widely used and common elements varying from basic to complex.
Layouts − They define how UI elements should be organized on the screen and provide a final
look and feel to the GUI (Graphical User Interface).
Behavior − These are the events which occur when the user interacts with UI elements.
Every SWING controls inherits properties from the following Component class hierarchy.
Component
1
A Component is the abstract base class for the non menu user-interface controls of SWING.
Component represents an object with graphical representation
2 Container
Page 23 of 31
3 A JComponent is a base class for all SWING UI components. In order to use a SWING
component that inherits from JComponent, the component must be in a containment
hierarchy whose root is a top-level SWING container
SWING UI Elements
Following is the list of commonly used controls while designing GUI using SWING.
The JRadioButton class is a graphical component that can be in either an on (true) or off
(false) state. in a group.
6 JList
A JList component presents the user with a scrolling list of text items.
7 JComboBox
A JTextField object is a text component that allows for the editing of a single line of text.
9 JPasswordField
A JTextArea object is a text component that allows editing of a multiple lines of text.
11 ImageIcon
A ImageIcon control is an implementation of the Icon interface that paints Icons from
Images
12 JScrollbar
A Scrollbar control represents a scroll bar component in order to enable the user to select
from range of values.
Page 24 of 31
13 JOptionPane
JOptionPane provides set of standard dialog boxes that prompt users for a value or
informs them of something.
14 JFileChooser
A JFileChooser control represents a dialog window from which the user can select a file.
What is an Event?
Change in the state of an object is known as Event, i.e., event describes the change in the state of the
source. Events are generated as a result of user interaction with the graphical user interface components.
For example, clicking on a button, moving the mouse, entering a character through keyboard, selecting
an item from the list, and scrolling the page are the activities that cause events to occur.
Types of Event
Foreground Events − These events require direct interaction of the user. They are generated as
consequences of a person interacting with the graphical components in the Graphical User
Interface. For example, clicking on a button, moving the mouse, entering a character through
keyboard, selecting an item from list, scrolling the page, etc.
Background Events − These events require the interaction of the end user. Operating system
interrupts, hardware or software failure, timer expiration, and operation completion are some
examples of background events.
Event Handling is the mechanism that controls the event and decides what should happen if an event
occurs. This mechanism has a code which is known as an event handler, that is executed when an event
occurs.
Java uses the Delegation Event Model to handle the events. This model defines the standard mechanism
to generate and handle the events.
Source − The source is an object on which the event occurs. Source is responsible for providing
information of the occurred event to it's handler. Java provide us with classes for the source
object.
Listener − It is also known as event handler. The listener is responsible for generating a
response to an event. From the point of view of Java implementation, the listener is also an
object. The listener waits till it receives an event. Once the event is received, the listener
processes the event and then returns.
The benefit of this approach is that the user interface logic is completely separated from the logic that
generates the event. The user interface element is able to delegate the processing of an event to a
separate piece of code.
Page 25 of 31
Create a component i.e. label and set the dimensions using setBounds(). Here, you can set the location
in the form of x and y coordinates and place the button anywhere in a frame −
Example
Package my;
import java.awt.Dimension;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
public class SwingDemo{
public static void main(String[] args){
JFrame frame =new JFrame("Demo Frame");
JPanel panel =new JPanel();
frame.getContentPane();
JButton button =new JButton("Demo Button");
Dimension size = button.getPreferredSize();
button.setBounds(300,180, size.width, size.height);
panel.setLayout(null);
panel.add(button);
panel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(panel);
frame.setSize(500,300);
frame.setVisible(true);
}
}
Exercise:
Copy this code in any text editor and run the program to get the output.
The Vector class implements a growable array of objects. Vectors basically fall in legacy classes but
now it is fully compatible with collections. It is found in the java.util package and implements the List
interface, so we can use all the methods of List interface here.
Vector implements a dynamic array that means it can grow or shrink as required. Like an array,
it contains components that can be accessed using an integer index
They are very similar to ArrayList but Vector is synchronized and has some legacy method that
the collection framework does not contain.
It also maintains an insertion order like an ArrayList but it is rarely used in a non-thread
environment as it is synchronized and due to which it gives a poor performance in adding,
searching, delete and update of its elements.
The Iterators returned by the Vector class are fail-fast. In the case of concurrent modification, it
fails and throws the ConcurrentModificationException.
Declaration:
Constructors:
3. Vector(int size, int incr): Creates a vector whose initial capacity is specified by size and increment
is specified by incr. It specifies the number of elements to allocate each time that a vector is resized
upward.
Example: The following implementation demonstrates how to create and use a Vector.
int n = 5;
// Declaring the Vector with initial size n
Vector<Integer> v = new Vector<Integer>(n);
v.add(i);
// Printing elements
System.out.println(v);
// Remove element at index 3
v.remove(3);
Output
[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1 2 3 5
Page 28 of 31
1. Adding Elements: In order to add the elements to the Vector, we use the add() method. This method
is overloaded to perform multiple operations based on different parameters. They are:
add(Object): This method is used to add an element at the end of the Vector.
add(int index, Object): This method is used to add an element at a specific index in the Vector.
importjava.util.*;
importjava.io.*;
class AddElementsToVector {
v1.add(1);
v1.add(2);
v1.add("geeks");
v1.add("forGeeks");
v1.add(3);
v2.add(1);
v2.add(2);
v2.add(3);
Output:
2. Changing Elements: After adding the elements, if we wish to change the element, it can be done
using the set() method. Since a Vector is indexed, the element which we wish to change is referenced by
Page 29 of 31
the index of the element. Therefore, this method takes an index and the updated element which needs to
be inserted at that index.
import java.util.*;
Output
Vector: [12, 23, 22, 10, 20]
The Object that is replaced is: 12
The Object that is replaced is: 20
The new Vector is:[21, 23, 22, 10, 50]
3. Removing Elements: In order to remove an element from a Vector, we can use the remove()
method. This method is overloaded to perform multiple operations based on different parameters. They
are:
remove(Object): This method is used to simply remove an object from the Vector. If there are multiple
such objects, then the first occurrence of the object is removed.
Page 30 of 31
remove(int index): Since a Vector is indexed, this method takes an integer value which simply removes
the element present at that specific index in the Vector. After removing the element, all the elements
are moved to the left to fill the space and the indices of the objects are updated.
import java.util.*;
import java.io.*;
class RemovingElementsFromVector {
v.add(1);
v.add(2);
v.add("Geeks");
v.add("forGeeks");
v.add(4);
Output:
4. Iterating the Vector: There are multiple ways to iterate through the Vector. The most famous ways
are by using the basic for loop in combination with a get() method to get the element at a specific index
and the advanced for loop.
import java.util.*;
v.add("Geeks");
Page 31 of 31
v.add("Geeks");
System.out.println();
for(String str : v)
Output
If the increment is specified, Vector will expand according to it in each allocation cycle but if the
increment is not specified then the vector’s capacity gets doubled in each allocation cycle. Vector
defines three protected data member: