You are on page 1of 16

Unit 1 (Part 2 )(Array,class,methods)

Declaration and Initialization :

Declaration is the process of defining the variable along with its type and name.

Here, we're declaring the id variable:

int id;

Initialization, on the other hand, is all about assigning a value; for example:

id = 1;

Java Arrays:

Normally, an array is a collection of similar type of elements which have a contiguous memory
location.

Java array is an object which contains elements of a similar data type. Additionally, the
elements of an array are stored in a contiguous memory location. It is a data structure where
we store similar elements. We can store only a fixed set of elements in a Java array.

Arrays in Java are homogeneous data structures implemented in Java as objects. Array’s store
one or more values of a specific data type and provide indexed access to store the same. A
specific element in an array is accessed by its index. Arrays offer a convenient means of
grouping related information. As Array in Java is index-based, the first element of the array is
stored at the 0th index, 2nd element is stored on 1st index and so on.

Unlike C/C++, we can get the length of the array using the length member. In C/C++, we need
to use the sizeof operator. Like C/C++, we can also create single dimensional or
multidimensional arrays in Java.

Array is a fundamental construct in Java that allows you to store and access large number of
values conveniently.
➢ Advantages

Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.

Random access: We can get any data located at an index position.

➢ Disadvantages

Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at
runtime. To solve this problem, collection framework is used in Java which grows
automatically.

➢ Types of Array in java

There are two types of array.

1. Single Dimensional Array


2. Multidimensional Array

Single Dimensional Array in Java :

A one-dimensional array (or single dimension array) is a type of linear array. Accessing its
elements involves a single subscript which can either represent a row or column index.

➢ Syntax to Declare an Array in Java

datatype[] arr; (or)

datatype []arr; (or)

datatype arr[];
Where, datatype can be a primitive data type like: int, char, Double, byte etc. or an object.

arr is an identifier/name given to an array.

➢ Creation of an Array in Java


arr=new datatype[size];

Let's take example:

int[] age;

age = new int[5]; it creates array of size 5.

It's possible to declare and allocate memory of an array in one statement. You can replace two
statements above with a single statement.

int[] age = new int[5];

➢ Initialization of an Array
arr[0]=12;
arr[1]=4; so on..

➢ Declaration,Creation and Initialization in one line :

datatype[] arr = {12, 4, 5, 2, 5};

The length of the array is determined by the number of values provided which is separated by
commas. In our example, the length of age array is 5.

➢ Let's write a simple program to print elements of this array.


Multidimensional Arrays

The Java multidimensional arrays are arranged as an array of arrays i.e. each element of a multi-
dimensional array is another array. The representation of the elements is in rows and columns.

Basically two type of multidimensional array :

Two Dimensional

Three Dimensional or more

1) Two Dimensional Array :

The simplest of the multi-dimensional array is a two-dimensional array. A simple definition of


2D arrays is: A 2D array is an array of one-dimensional arrays. In Java, a two-dimensional
array is stored in the form of rows and columns and is represented in the form of a matrix.

➢ Syntax to Declare an Array in Java

datatype[][] arr; (or)

datatype [][]arr; (or)

datatype arr[][]; (or)

datatype[] arr[];

Where, datatype can be a primitive data type like: int, char, Double, byte etc. or an object.

arr is an identifier/name given to an array.

➢ Creation of an Array in Java

arr=new datatype[row size][column size];

Let's take example:

int[][] age;

age = new int[2] [3]; It creates two rows and three columns.
It's possible to declare and allocate memory of an array in one statement. You can replace two
statements above with a single statement.

int[][] age = new int[2][3];

➢ Initialization of an Array

arr[0] [0] =10;

arr[0][1]=20;

arr[0][2]=30;

arr[1][0]=40;

arr[1][1]=50;

arr[1][2]=60; as above given expression has 2 rows (index 0 and 1) and 3 columns (index
0,1,2)

➢ Declaration,Creation and Initialization in one line :

datatype[][] arr = {{10,20,30}{40,50,60}};

➢ Program Example :
2 ) Three Dimensional Array :

Three-dimensional arrays are complex for multi-dimensional arrays. A three dimensional can
be defined as an array of two-dimensional arrays.

➢ Syntax to Declare an Array in Java

datatype[][][] arr; (or)

datatype[] [][]arr; (or)

datatype[][] arr[]; (or)

datatype[] arr[][];

Where, datatype can be a primitive data type like: int, char, Double, byte etc. or an object.

arr is an identifier/name given to an array.

➢ Creation of an Array in Java

arr=new datatype[Grand Parent array size][Parent array size][child array size];

Let's take example:

int[][][] age;

age = new int[2][2][3];

It's possible to declare and allocate memory of an array in one statement. You can replace two
statements above with a single statement.

int[][][] age = new int[2][3][2]; It creates following structure :


➢ Initialization of an Array :

arr[0][0][0]=10;

arr[0][0][1]=20;

arr[0][1][0]=30;

arr[0][1][1]=40;

arr[0][2][0]=50;

arr[0][2][1]=60;

arr[1][0][0]=70;

arr[1][0][1]=80;

arr[1][1][0]=90; and so on.

➢ Declaration,Creation and Initialization in one line :

int[][][] arr = { {{10,20},{30,40},{50,60}}, {{70,80},{90,10},{25,35}} };

➢ Program Example :
Defining a class in Java:

Java classes are some of the core building blocks of Java applications, toolkits, frameworks,
APIs etc. A small Java application may consist of a single Java class with a main() method in.

A Java class is a single, coherent unit of Java code which belongs together. A Java class may
contain a mix of data (variables) and actions (methods). Grouping variables and operations on
these variables into Java classes makes it easier to structure your Java program when it gets too
big to fit comfortably inside a single Java class. A Java class must be stored in its own file.

Java application will typically have to contain at least a single Java class, but it may contain as
many classes as you see fit to divide your application into. Java also comes with a lot of
predefined classes, so that user don't have to code every little function they might desire.

A class is declared by use of the class keyword. The class body is enclosed between curly
braces { and }. The data or variables, defined within a class are called instance variables. The
code is contained within methods. Collectively, the methods and variables defined within a
class are called members of the class.

The above class definition should be put in its own file named Vehicle.java. Java files should
be named the same as the name of the class they contain, with the .java as file name extension.
Make sure you keep the same uppercase and lowercase characters from the class name in the
file name too.

A Java class can contain the following building blocks:

• Fields
• Constructors
• Methods
• Nested Classes
1. Fields are variables (data) that are local to the class, or instances (objects) of that class.

The example shows a Java class which is to model a car. Therefore the class has named Car
and has two fields. Here is the Java class in code:

public class Car {

public String name = “Toyota”;

public String color = “Black”;

2. Constructors are special methods that initialize an instance of the class. Constructors often
sets the values of fields in the given instance.
A Java class can have a constructor. A constructor is a special method that is called when
an object of the given class is created. The purpose of a constructor is to initialize the fields
in the class. The fields are also called the "internal state". Here is an example of a Java class
with two constructors:

public class Car {


public String name = “Toyota”;
public String color = “Black”;
public Car() { //constructor
}
}
3. Methods are operations that the class or instances of that class can perform. A Java class
can also contain operations. These operations are typically called methods. A Java method
contains Java instructions that typically perform some operations on a field in the class, or
on one of the parameters (also variables) values passed to the method when the method was
called.
Here is the Java class, Car example from the previous section with a method added:

public class Car {

public String name = “Toyota”;


public String color = “Black”;
public void setColor(String newColor) { //method
this.color = newColor;
}
}

4. Nested classes are Java classes that are defined inside another class. Nested classes are
typically intended to either be used only internally be the Java class that contains them, or
to be used in connection with the class that contains them.
public class MyClass {

public static class MyNestedClass{

}
}
In the example above, the outer class is called MyClass and the nested class is called
MyNestedClass . Neither of the classes in this example has any fields or methods, but both
the outer and nested class could have as many fields and methods as you see fit.

Not all Java classes have fields, constructors and methods. Sometimes you have classes that
only contain fields (data), and sometimes you have classes that only contain methods
(operations). It depends on what the Java class is supposed to do.

Adding variables to class:

A variable is a name given to a memory location. It is the basic unit of storage in a program.

• The value stored in a variable can be changed during program execution.


• A variable is only a name given to a memory location; all the operations done on the
variable affects that memory location.
• In Java, all the variables must be declared before use.
• A variable is a container which holds the value while the java program is executed.
• A variable is assigned with a datatype.
➢ Declaration of variables:
We can declare variables in java as follows:

Where,

datatype: Type of data that can be stored in this variable.

variable_name: Name given to the variable.

value: It is the initial value stored in the variable.

Examples:

float simpleInterest; //Declaring float variable

int time = 10, speed = 20; //Declaring and Initializing integer variable

char var = 'h'; // Declaring and Initializing character variable

➢ Types of variables

There are two types of variables in Java:

• Local Variables
• Instance Variables

1. Local Variables:
 A variable defined within a block or method or constructor is called local variable.
 These variables are created when the block in entered or the function is called and
destroyed after exiting from the block or when the call returns from the function.
 The scope of these variables exists only within the block in which the variable is
declared. i.e. we can access these variables only within that block.
 Initialisation of Local Variable is Mandatory.
➢ Program Example:

In the above program, the variable age is a local variable to the function StudentAge(). If we
use the variable age outside StudentAge() function, the compiler will produce an error.

2. Instance Variables:
 Instance variables are non-static variables and are declared in a class outside any method,
constructor or block.
 As instance variables are declared in a class, these variables are created when an object of
the class is created and destroyed when the object is destroyed.
 Unlike local variables, we may use access specifiers for instance variables. If we do not
specify any access specifier then the default access specifier will be used.
 Initialization of Instance Variable is not Mandatory. Its default value is 0
 Instance Variable can be accessed only by creating objects.

➢ Program Example :
As you can see in the above program the variables, engMarks , mathsMarks are instance
variables. In case we have multiple objects as in the above program, each object will have its
own copies of instance variables.

Adding Methods to class:

A method is a collection of statements that perform some specific task and return the result to
the caller. A method can perform some specific task without returning anything. Methods allow
us to reuse the code without retyping the code. In Java, every method must be part of some
class which is different from languages like C, C++, and Python. Methods are time savers and
help us to reuse the code without retyping the code.

➢ Method Declaration

In general, method declarations has six components :

1. Modifier-: Defines access type of the method i.e. from where it can be accessed in your
application. In Java, there 4 type of the access specifiers.
• public: The access level of a public modifier is everywhere.
• protected: The access level of a protected modifier is within the package and outside
the package through child class.
• private: The access level of a private modifier is only within the class.
• default (declared/defined without using any modifier) : The access level of a default
modifier is only within the package.
2. The return type : The data type of the value returned by the method or void if does not
return a value.
3. Method Name : the rules for field names apply to method names as well, but the
convention is a little different.
4. Parameter list : Comma separated list of the input parameters are defined, preceded with
their data type, within the enclosed parenthesis. If there are no parameters, you must
use empty parentheses ().
5. Exception list : The exceptions you expect by the method can throw, you can specify
these exception(s).
6. Method body : it is enclosed between braces. The code you need to be executed to
perform your intended operations.

➢ Method signature: It consists of the method name and a parameter list (number of
parameters, type of the parameters and order of the parameters). The return type and
exceptions are not considered as part of it.
Method Signature of above function:
max(int x, int y)
➢ Naming a Method: A method name is typically a single word that should be a verb in
lowercase or multi-word, that begins with a verb in lowercase followed by adjective,
noun….. After the first word, first letter of each word should be capitalized. For example,
findSum,computeMax, setX and getX Generally, A method has a unique name within the
class in which it is defined but sometime a method might have the same name as other
method names within the same class as method overloading is allowed in Java.

➢ Calling a Method :
The method needs to be called for using its functionality. There can be three situations
when a method is called:
A method returns to the code that invoked it when:
• It completes all the statements in the method
• It reaches a return statement
• Throws an exception

➢ Program Example :

Creating Objects :

In Java, you create an object by creating an instance of a class or, in other words, instantiating
a class. Often, you will see a Java object created with a statement like this one:

Date today = new Date();

This statement creates a new Date object (Date is a class in the java.util package). This single
statement actually performs three actions: declaration, instantiation, and initialization. Date
today is a variable declaration which simply declares to the compiler that the name today will
be used to refer to an object whose type is Date, the new operator instantiates the Date class
(thereby creating a new Date object), and Date initializes the object.
• Declaring an Object :
While the declaration of an object is not a necessary part of object creation, object declarations
often appear on the same line as the creation of an object. Like other variable declarations,
object declarations can appear alone like this:
Date today;
Either way, declaring a variable to hold an object is just like declaring a variable to hold a value
of primitive type:
type name;
where type is the data type of the object and name is the name to be used for the object. In Java,
classes and interfaces are just like a data type. So type can be the name of a class such as the
Date class or the name of an interface. Declarations do not create new objects. Date today does
not create a new Date object, just a variable named today to hold a Date object. To instantiate
the Date class, or any other class, use the new operator.
• Initializing an Object :
As mentioned previously, classes provide constructor methods to initialize a new object of that
type. A class may provide multiple constructors to perform different kinds of initialization on
new objects. When looking at the implementation for a class, you can recognize the
constructors because they have the same name as the class and have no return type. If the Date
constructor used doesn't take any arguments, then object will be initialized like below:
Date today = new Date();

You might also like