0% found this document useful (0 votes)
11 views

COM211_JAVA2 ND2 1st Sem

The document provides a comprehensive overview of arrays in Java, including their declaration, initialization, and types. It explains how to create and manipulate both one-dimensional and multidimensional arrays, as well as arrays of objects, with examples demonstrating their usage. Key concepts such as zero-based indexing, fixed length, and memory allocation are also discussed.

Uploaded by

Iorlaha Samuel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

COM211_JAVA2 ND2 1st Sem

The document provides a comprehensive overview of arrays in Java, including their declaration, initialization, and types. It explains how to create and manipulate both one-dimensional and multidimensional arrays, as well as arrays of objects, with examples demonstrating their usage. Key concepts such as zero-based indexing, fixed length, and memory allocation are also discussed.

Uploaded by

Iorlaha Samuel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

Page 1 of 31

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

The new operator is used to initialize an array.

Example :

int[] arr = new int[10]; //10 is the size of array.


OR
int[] arr = {10,20,30,40,50};

Accessing array element

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

Example : To access 4th element of a given array;

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

foreach or enhanced for loop

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:

byte[] buffer = new byte[1024];


String[] lines = new String[50];

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

//creating another matrix to store the sum of two matrices


int c[][]=newint[2][3];

//adding and printing addition of 2 matrices


for(int i=0;i<2;i++){
for(int j=0;j<3;j++){
c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}
}
}

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:

float[][][] globalTemperatureData = new float[360][180][100];

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:

float[][][] globalTemperatureData = new float[360][][];


float[][][] globalTemperatureData = new float[360][180][];

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:

float[][][] globalTemperatureData = new float[360][][100]; // Error!


float[][][] globalTemperatureData = new float[][180][100]; // Error!

What is an Array of Objects?

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.

How to Create An Array Of Objects In Java?

An array of objects is created using the ‘Object’ class.

The following statement creates an Array of Objects.

Class_name [] objArray;

Alternatively, you can also declare an Array of Objects as shown below:

Class_name objArray[];

Both the above declarations imply that objArray is an array of objects.

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:

Employee[] empObjects = new Employee[2];

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.

Initialize Array Of Objects

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{

Public static void main(String args[]){

//create array of employee object

Employee[] obj = new Employee[2] ;

//create & initialize actual employee objects using constructor

obj[0] = new Employee(100,"ABC");

obj[1] = new Employee(200,"XYZ");

//display the employee object data

System.out.println("Employee Object 1:");

obj[0].showData();

System.out.println("Employee Object 2:");

obj[1].showData();

//Employee class with empId and name as attributes


Page 6 of 31

Class Employee{

int empId;

String name;

//Employee class constructor

Employee(int eid, String n){

empId = eid;

name = n;

Public void showData(){

System.out.print("EmpId = "+empId + " "+ " Employee Name = "+name);

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.

Example Program for An Array Of Objects In Java

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{

public static void main(String args[]){

//create array of employee object

Employee[] obj = new Employee[2] ;

//create actual employee object

obj[0] = new Employee();


Page 7 of 31

obj[1] = new Employee();

//assign data to employee objects

obj[0].setData(100,"ABC");

obj[1].setData(200,"XYZ");

//display the employee object data

System.out.println("Employee Object 1:");

obj[0].showData();

System.out.println("Employee Object 2:");

obj[1].showData();

//Employee class with empId and name as attributes

Class Employee{

int empId;

String name;

Public void setData(int c, String d){

empId=c;

name=d;

Public void showData(){

System.out.print("EmpId = "+empId + " "+ " Employee Name = "+name);

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

1. public class ArrayOfObjects


2. {
Page 8 of 31

3. public static void main(String args[])


4. {

5. //create an array of product object


6. Product[] obj = new Product[5] ;

7. //create & initialize actual product objects using constructor


8. obj[0] = new Product(23907,"Dell Laptop");

9. obj[1] = new Product(91240,"HP 630");


10. obj[2] = new Product(29823,"LG OLED TV");

11. obj[3] = new Product(11908,"MI Note Pro Max 9");


12. obj[4] = new Product(43590,"Kingston USB");

13. //display the product object data


14. System.out.println("Product Object 1:");

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

27. class Product


28. {

29. int pro_Id;


30. String pro_name;

31. //Product class constructor


32. Product(int pid, String n)

33. {
34. pro_Id = pid;

35. pro_name = n;
36. }

37. public void display()


38. {
Page 9 of 31

39. System.out.print("Product Id = "+pro_Id + " " + " Product


Name = "+pro_name);
40. System.out.println();

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

STORAGE & RETRIEVAL PROCESSES OF 1-& 2-DIMENSIONAL


ARRAYS
Programming with Arrays
Before considering more examples, we consider a number of important characteristics of programming
with arrays.

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

double[] a = new double[n];

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.

int i = (int) (Math.random() * RANKS.length);


int j = (int) (Math.random() * SUITS.length);
System.out.println(RANKS[i] + " of " + SUITS[j]);

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

String[] deck = new String[RANKS.length * SUITS.length];


for (int i = 0; i < RANKS.length; i++)
for (int j = 0; j < SUITS.length; j++)
deck[SUITS.length*i + j] = RANKS[i] + " of " + SUITS[j];
System.out.println(RANKS[i] + " of " + SUITS[j]);

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:

double[][] a = new double[m][n];


Page 11 of 31

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;

 Memory representation. Java represents a two-dimensional array as an array of arrays. A matrix


with m rows and n columns is actually an array of length m, each entry of which is an array of
length n. In a two-dimensional Java array, we can use the code a[i] to refer to the ith row (which
is a one-dimensional array). Enables ragged arrays.
 Setting values at compile time. The following code initializes the 11-by-4 array a[][]:

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:

for (int i = 0; i < a.length; i++) {


for (int j = 0; j < a[i].length; j++) {
System.out.print(a[i][j] + " ");
}
System.out.println();
}

 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

double[][][] a = new double[n][n][n];

and then refer to an entry with code like a[i][j][k].

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[].

double[][] c = new double[n][n];


for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
for (int k = 0; k < n; k++) {
c[i][j] += a[i][k]*b[k][j];
}
}
}

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

3. What is wrong with the following code fragment?

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.

4. What does the following code fragment print?

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.

Constructors in Java – A complete study!!


[By Chaitanya Singh]
Page 14 of 31

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.

Public class MyClass{


//This is the constructor
MyClass(){
}
..
}

Note that the constructor name matches with the class name and it doesn’t have a return type.

How Does a Constructor Work

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:

MyClass obj=new MyClass()

The new keyword here creates the object of class MyClass and invokes the constructor to initialize this
newly created object.

A Simple Constructor Program in Java


Here we have created an object obj of class Hello and then we displayed the instance variable name of
the object. As you can see that the output is Java Programming is Sweet, which is what we have passed
to the name during initialization in constructor. This shows that when we created the object obj the
constructor got invoked. In this example we have used this keyword, which refers to the current object,
object obj in this example. We will cover this keyword in detail in the next tutorial.

Public class Hello{


String name;
//Constructor
Hello(){
this.name="Java Programming is Sweet";
}
Public static void main(String[]args){
Hello obj=new Hello();
System.out.println(obj.name);
}
}

Output:

Java Programming is Sweet


Page 15 of 31

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.

Example: no-arg constructor


Class Demo
{
Public Demo()
{
System.out.println("This is a no argument constructor");
}
Public static void main(String args[]){
newDemo();
}
}

Output:
This is a no argument constructor

Parameterized Constructor

Constructor with arguments (or you can say parameters) is known as Parameterized constructor.

Example: 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.

Public class Employee{

Int empId;
Page 16 of 31

String empName;

//parameterized constructor with two parameters


Employee(int id, String name){
this.empId= id;
this.empName= name;
}
void info(){
System.out.println("Id: "+empId+" Name: "+empName);
}

Public static void main(Stringargs[]){


Employee obj1 =new Employee(10245,"Chaitanya");
Employee obj2 =new Employee(92232,"Negan");
obj1.info();
obj2.info();
}
}

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

Constructor Chaining with example

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

Let’s understand this with the help of an example.

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;

//default constructor of the class


Public Employee()
{
//this will call the constructor with String parameters
this("Charity");
}

Public Employee(String name)


{
//call the constructor with (String, int) parameters
this(name,120035);
}
Public Employee(String name, int sal)
{
//call the constructor with (String, int, String) parameter
this(name,sal,"Mkar");
}
Public Employee(String name, int sal, String addr)
{
this.empName=name;
this.empSalary=sal;
this.address=addr;
}

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

Constructor Overloading in Java with Examples

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:

Vector v= new Vector(10, 5);


You must have understood the purpose of constructor overloading. Let’s see how to overload a
constructor with the help of following java program.

Constructor Overloading Example

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

Public static void main(String args[])


{
//This object creation would call the default constructor
StudentData myobj=new StudentData();
System.out.println("Student Name is: "+myobj.getStuName());
System.out.println("Student Age is: "+myobj.getStuAge());
System.out.println("Student ID is: "+myobj.getStuID());

/*This object creation would call the parameterized


* constructor StudentData(int, String, int)*/
StudentData myobj2 =new StudentData(555,"Charity",25);
System.out.println("Student Name is: "+myobj2.getStuName());
System.out.println("Student Age is: "+myobj2.getStuAge());
System.out.println("Student ID is: "+myobj2.getStuID());
}
}

Output:

Student Name is: New Student


Student Age is:18
Student ID is:100
Student Name is:Charity
Student Age is:25
Student ID is:555

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

Difference Between Constructor and Method

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 programming is a programming paradigm in which the flow of program execution is


determined by events - for example a user action such as a mouse click, key press, or a message from
the operating system or another program. An event-driven application is designed to detect events as
they occur, and then deal with them using an appropriate event-handling procedure. The idea is an
extension of interrupt-driven programming of the kind found in early command-line environments such
as DOS, and in embedded systems (where the application is implemented as firmware).

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.

How Event-driven Programming Works

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.

JAVASWING FEATURES USED FOR EVENT-DRIVEN PROGRAMMING

Every user interface considers the following three main aspects −

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

S.No. Class & Description

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

A Container is a component that can contain other SWING components


JComponent

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.

S.No. Class & Description


1 JLabel

A JLabel object is a component for placing text in a container.


2 JButton

This class creates a labeled button.


3 JColorChooser

A JColorChooser provides a pane of controls designed to allow a user to manipulate and


select a color.
4 JCheck Box

A JCheckBox is a graphical component that can be in either an on (true) or off (false)


state.
5 JRadioButton

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 JComboBox component presents the user with a to show up menu of choices.


8 JTextField

A JTextField object is a text component that allows for the editing of a single line of text.
9 JPasswordField

A JPasswordField object is a text component specialized for password entry.


10 JTextArea

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

The events can be broadly classified into two categories −

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

What is Event Handling?

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.

The Delegation Event Model has the following key participants.

 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

How to set the location of a button anywhere in


JFrame?
To set location of a button anywhere a JFrame, use the setBounds() method. Let us first create a frame
and a panel −

JFrame frame = new JFrame("Demo Frame");


JPanel panel = new JPanel();
frame.getContentPane();

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 −

JButton button = new JButton("Demo Button");


Dimension size = button.getPreferredSize();
button.setBounds(300, 180, size.width, size.height);

The following is an example to set the location of a button anywhere in JFrame −

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.

VECTOR CLASS IN JAVA


Page 26 of 31

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:

public class Vector<E> extends AbstractList<E> implements List<E>,


RandomAccess, Cloneable, Serializable

Here, E is the type of element.

 It extends AbstractList and implements List interfaces.


 It implements Serializable, Cloneable, Iterable<E>, Collection<E>, List<E>, RandomAccess interfaces.
 The directly known subclass is Stack.

Constructors:

1. Vector(): Creates a default vector of the initial capacity is 10.

Vector<E> v = new Vector<E>();

2. Vector(int size): Creates a vector whose initial capacity is specified by size.

Vector<E> v = new Vector<E>(int size);


Page 27 of 31

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.

Vector<E> v = new Vector<E>(int size, int incr);

4. Vector(Collection c): Creates a vector that contains the elements of collection c.

Vector<E> v = new Vector<E>(Collection c);

Example: The following implementation demonstrates how to create and use a Vector.

// Java program to demonstrate the working of Vector


Import java.io.*;
Import java.util.*;
Class VectorExample {

Public static voidmain(String[] args)


{
// Size of the Vector

int n = 5;
// Declaring the Vector with initial size n
Vector<Integer> v = new Vector<Integer>(n);

// Appending new elements at the end of the vector


for(int i = 1; i<= n; i++)

v.add(i);
// Printing elements

System.out.println(v);
// Remove element at index 3
v.remove(3);

// Displaying the vector after deletion


System.out.println(v);

// Printing elements one by one


for(int i = 0; i<v.size(); i++)
System.out.print(v.get(i) + " ");
}
}

Output

[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1 2 3 5
Page 28 of 31

Performing Various Operations on Vector class in Java

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.

// Java code for adding the elements in Vector Class

importjava.util.*;

importjava.io.*;

class AddElementsToVector {

public static void main(String[] arg)

// create default vector

Vector v1 = new Vector();

// Add elements using add() method

v1.add(1);

v1.add(2);

v1.add("geeks");

v1.add("forGeeks");

v1.add(3);

// print the vector to the console

System.out.println("Vector v1 is "+ v1);

// create generic vector

Vector<Integer> v2 = new Vector<Integer>();

v2.add(1);

v2.add(2);

v2.add(3);

System.out.println("Vector v2 is "+ v2);

Output:

Vector v1 is [1, 2, geeks, forGeeks, 3]


Vector v2 is [1, 2, 3]

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.

// Java code to change the elements in vector class

import java.util.*;

public class UpdatingVector {

public static void main(String args[]) {


// Creating an empty Vector
Vector<Integer> vec_tor = new Vector<Integer>();

// Use add() method to add elements in the vector


vec_tor.add(12);
vec_tor.add(23);
vec_tor.add(22);
vec_tor.add(10);
vec_tor.add(20);

// Displaying the Vector


System.out.println("Vector= "+ vec_tor);

// Using set() method to replace 12 with 21


System.out.println("The Object that is replaced is: "
+ vec_tor.set(0, 21));

// Using set() method to replace 20 with 50


System.out.println("The Object that is replaced is: "
+ vec_tor.set(4, 50));

// Displaying the modified vector


System.out.println("The new Vector is: "+ vec_tor);
}
}

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.

// Java code illustrating the removal of elements from vector

import java.util.*;

import java.io.*;

class RemovingElementsFromVector {

public static void main(String[] arg) {

// create default vector of capacity 10

Vector v = new Vector();

// Add elements using add() method

v.add(1);

v.add(2);

v.add("Geeks");

v.add("forGeeks");

v.add(4);

System.out.println("after removal: "+ v);//Display vectors added

v.remove(1); // removing first occurrence element at 1

System.out.println("after removal: "+ v); // checking vector

Output:

[1, 2, Geeks, forGeeks, 4]


after removal: [1, Geeks, forGeeks, 4]

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.

// Java program to iterate the elements in a Vector

import java.util.*;

public class IteratingVector {

public static void main(String args[]) {

Vector<String> v = newVector<>(); // create an instance of vector

// Add elements using add() method

v.add("Geeks");
Page 31 of 31

v.add("Geeks");

v.add(1, "For"); // using the index of 1 to insert the value…

// Using the Get method and the for loop

for(int i = 0; i<v.size(); i++) {

System.out.print(v.get(i) + " ");

System.out.println();

// Using the for-each loop

for(String str : v)

System.out.print(str + " ");

Output

Geeks For Geeks


Geeks For Geeks

Important points regarding Increment of vector capacity:

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:

 int capacityIncreament: Contains the increment value.


 int elementCount: Number of elements currently in vector stored in it.
 Object elementData[]: Array that holds the vector is stored in it.

Common Errors in Declaration of Vectors

 Vector throws an IllegalArgumentException if the InitialSize of the vector defined is negative.


 If the specified collection is null, It throws NullPointerException.

You might also like