Arrays: Department of Computer Science & Engineering Web Technologies-Kcs-602 Unit-I

Download as pdf or txt
Download as pdf or txt
You are on page 1of 15

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

WEB TECHNOLOGIES-KCS-602
UNIT-I

TOPICS COVERED:

ARRAYS AND METHODS

Arrays
Java provides a data structure, the array, which stores a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is often more useful
to think of an array as a collection of variables of the same type.

Instead of declaring individual variables, such as number0, number1, ..., and number99, you
declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99]
to represent individual variables.

This tutorial introduces how to declare array variables, create arrays, and process arrays using
indexed variables.

Declaring Array Variables:


To use an array in a program, you must declare a variable to reference the array, and you must
specify the type of array the variable can reference. Here is the syntax for declaring an array
variable:

dataType[] arrayRefVar; // preferred way.


or
dataType arrayRefVar[]; // works but not preferred way.
Note: The style dataType[] arrayRefVar is preferred. The style dataType arrayRefVar[]
comes from the C/C++ language and was adopted in Java to accommodate C/C++ programmers.

Example:

The following code snippets are examples of this syntax:

double[] myList; // preferred way.


or
double myList[]; // works but not preferred way.

Creating Arrays:

Page 1
You can create an array by using the new operator with the following syntax:

arrayRefVar = new dataType[arraySize];


The above statement does two things:

• It creates an array using new dataType[arraySize];

• It assigns the reference of the newly created array to the variable arrayRefVar.

Declaring an array variable, creating an array, and assigning the reference of the array to the
variable can be combined in one statement, as shown below:

dataType[] arrayRefVar = new dataType[arraySize];


Alternatively you can create arrays as follows:

dataType[] arrayRefVar = {value0, value1, ..., valuek};


The array elements are accessed through the index. Array indices are 0-based; that is, they start
from 0 to arrayRefVar.length-1.

Example:
Following statement declares an array variable, myList, creates an array of 10 elements of
double type and assigns its reference to myList:

double[] myList = new double[10];


Following picture represents array myList. Here, myList holds ten double values and the indices
are from 0 to 9.

Processing Arrays:
When processing array elements, we often use either for loop or for each loop because all of the
elements in an array are of the same type and the size of the array is known.

Example:
Here is a complete example of showing how to create, initialize and process arrays:

Page 2
public class TestArray
{
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (int i = 0; i < myList.length; i++)
{
System.out.println(myList[i] + " ");
}
// Summing all elements
double total = 0;
for (int i = 0; i < myList.length; i++)
{ total += myList[i];
}
System.out.println("Total is " + total);
// Finding the largest element
double max = myList[0];
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max =
myList[i];
}
System.out.println("Max is " + max);
}
This} would produce the following result:

1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5

Page 3
Java -Methods
A Java method is a collection of statements that are grouped together to perform an operation.
When you call the System.out.println() method, for example, the system actually executes several
statements in order to display a message on the console.

Now you will learn how to create your own methods with or without return values, invoke a
method with or without parameters, and apply method abstraction in the program design.

Creating Method
Considering the following example to explain the syntax of a method −

Syntax

public static int methodName(int a, int b) {


// body
}
Here,

• public static − modifier

• int − return type

• methodName − name of the method

• a, b − formal parameters

• int a, int b − list of parameters

Method definition consists of a method header and a method body. The same is shown in the
following syntax −

Syntax

modifier returnType nameOfMethod (Parameter List) {


// method body
}
The syntax shown above includes −

• modifier − It defines the access type of the method and it is optional to use.

• returnType − Method may return a value.

• nameOfMethod − This is the method name. The method signature consists of the method

Page 4
name and the parameter list.

• Parameter List − The list of parameters, it is the type, order, and number of parameters
of a method. These are optional, method may contain zero parameters.

• method body − The method body defines what the method does with the statements.

Call by Value and Call by Reference in Java


There is only call by value in java, not call by reference. If we call a method passing a value, it
is known as call by value. The changes being done in the called method, is not affected in the
calling method.

Example of call by value in java


In case of call by value original value is not changed. Let's take a simple example:
class Operation{
int data=50;
void change(int data){
data=data+100;//changes will be in the local variable only
}
public static void main(String args[]){
Operation op=new Operation();
System.out.println("before change "+op.data);
op.change(500);
System.out.println("after change "+op.data);
}
}
Output:before change 50
after change 50

In Java, parameters are always passed by value. For example, following program prints
i = 10, j = 20.
// Test.java
class Test {
// swap() doesn't swap i and j
public static void swap(Integer i, Integer j) {
Integer temp = new Integer(i);
i = j;
j = temp;
}
public static void main(String[] args) {
Integer i = new Integer(10);
Page 5
Integer j = new Integer(20);
swap(i, j);
System.out.println("i = " + i + ", j = " + j);

}
}

Static Fields and Methods

The static keyword in java is used for memory management mainly. We can apply java static
keyword with variables, methods, blocks and nested class. The static keyword belongs to the class
than instance of the class.

The static can be:

1. variable (also known as class variable)


2. method (also known as class method)
3. block
4. nested class

Java static variable

If you declare any variable as static, it is known static variable.

o The static variable can be used to refer the common property of all objects (that is not unique for
each object) e.g. company name of employees,college name of students etc.

o The static variable gets memory only once in class area at the time of class loading.

Advantage of static variable

It makes your program memory efficient (i.e it saves memory).

Understanding problem without static variable


1. class Student{
2. int rollno;
3. String name;
4. String college="ITS";
5. }

Example of static variable


//Program of static variable
class Student8{
Page 6
int rollno;

String name;
static String college ="ITS";
Student8(int r,String n){
rollno = r;
name = n;
}
void display (){System.out.println(rollno+" "+name+" "+college);}
public static void main(String args[]){
Student8 s1 = new Student8(111,"Karan");
Student8 s2 = new Student8(222,"Aryan");

s1.display();
s2.display();
}}
Output:111 Karan ITS
222 Aryan ITS

Java static method

If you apply static keyword with any method, it is known as static method.

o A static method belongs to the class rather than object of a class.


o A static method can be invoked without the need for creating an instance of a class.
o static method can access static data member and can change the value of it.

Example of static method


//Program of changing the common property of all objects(static field).

class Student9{
int rollno;
String name;
static String college = "ITS";
static void change(){
college = "BBDIT";
}
Student9(int r, String n){
rollno = r;

Page 7
name = n;

}
void display (){System.out.println(rollno+" "+name+" "+college);}
public static void main(String args[]){
Student9.change();
Student9 s1 = new Student9 (111,"Karan");
Student9 s2 = new Student9 (222,"Aryan");
Student9 s3 = new Student9 (333,"Sonoo");
s1.display();
s2.display();
s3.display();
}}
Output:111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT

Java static block

o Is used to initialize the static data member.


o It is executed before main method at the time of class loading.

Example of static block


class A2{
static{System.out.println("static block is invoked");}
public static void main(String args[]){
System.out.println("Hello main");
}}
Output: static block is invoked
Hello main

Access Control
Access Modifiers in java

There are two types of modifiers in java: access modifiers and non-access modifiers.

The access modifiers in java specifies accessibility (scope) of a data member, method, constructor
or class.

Page 8
There are 4 types of java access modifiers:

1. private
2. default
3. protected
4. public

private access modifier


The private access modifier is accessible only within class.

Simple example of private access modifier


In this example, we have created two classes A and Simple. A class contains private data
member and private method. We are accessing these private members from outside the class, so
there is compile time error.
class A{
private int data=40;
private void msg(){System.out.println("Hello java");} }
public class Simple{
public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}}

2) default access modifier


If you don't use any modifier, it is treated as default bydefault. The default modifier is
accessible only within package.

Example of default access modifier


In this example, we have created two packages pack and mypack. We are accessing the A class
from outside its package, since A class is not public, so it cannot be accessed from outside the
package.
//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
Page 9
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error } }

In the above example, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package.

3) protected access modifier

The protected access modifier is accessible within package and outside the package but through
inheritance only.

The protected access modifier can be applied on the data member, method and constructor. It can't
be applied on the class.

Example of protected access modifier

In this example, we have created the two packages pack and mypack. The A class of pack package
is public, so can be accessed from outside the package. But msg method of this package is declared
as protected, so it can be accessed from outside the class only through inheritance.

//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");} }
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}}
Output:Hello

4) public access modifier


The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.

Page 10
Example of public access modifier
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");} }
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}}
Output:Hello

Understanding all java access modifiers

Let's understand the access modifiers by a simple table.

Access within within outside package by outside


Modifier class package subclass only package

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

this keyword in java

Usage of java this keyword

Here is given the 6 usage of java this keyword.

1. this can be used to refer current class instance variable.


2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
Page 11
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.

class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}

Output:
111 ankit 5000
112 sumit 6000

Recursion in Java
Recursion in java is a process in which a method calls itself continuously. A method in java that
calls itself is called recursive method.

Java Recursion Example 1: Factorial Number

public class RecursionExample3 {


static int factorial(int n){
if (n == 1)
return 1;
else
return(n * factorial(n-1));
}}
public static void main(String[] args) {
System.out.println("Factorial of 5 is: "+factorial(5));
}}
Output:

Factorial of 5 is: 120

Java Garbage Collection

In java, garbage means unreferenced objects.

Garbage Collection is process of reclaiming the runtime unused memory automatically. In other
words, it is a way to destroy the unused objects.

To do so, we were using free() function in C language and delete() in C++. But, in java it is
performed automatically. So, java provides better memory management.

Advantage of Garbage Collection


o It makes java memory efficient because garbage collector removes the unreferenced
objects from heap memory.
o It is automatically done by the garbage collector(a part of JVM) so we don't need to make
extra efforts.

gc() method
The gc() method is used to invoke the garbage collector to perform cleanup processing. The
gc() is found in System and Runtime classes.

public static void gc(){}

Simple Example of garbage collection in java


public class TestGarbage1{
public void finalize(){System.out.println("object is garbage collected");}
public static void main(String args[]){
TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null;
System.gc();
}}

object is garbage collected


object is garbage collected
Java String

string is basically an object that represents sequence of char values. An array of characters works
same as java string. For example:

1. char[] ch={‘k’,’r’,’i’,’s’,’h’,’n’,’a’};
2. String s=new String(ch);

Is same as: String s="krishna";

1. Java String class provides a lot of methods to perform operations on string such as
compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring()
etc.
2. The java.lang.String class
implements Serializable, Comparable and CharSequence interfaces.

CharSequence Interface

The CharSequence interface is used to represent sequence of characters. It is implemented by String,


StringBuffer and StringBuilder classes. It means, we can create string in java by using these 3
classes.

The java String is immutable i.e. it cannot be changed. Whenever we change any string, a new
instance is created. For mutable string, you can use StringBuffer and StringBuilder classes.
There are two ways to create String object:
1. By string literal
2. By new keyword

String Literal

Java String literal is created by using double quotes. For Example:

14
1. String s="welcome";

Each time you create a string literal, the JVM checks the string constant pool first. If the string
already exists in the pool, a reference to the pooled instance is returned. If string doesn't exist in the
pool, a new string instance is created and placed in the pool. For example:

1. String s1="Welcome";
2. String s2="Welcome";//will not create new instance

By new keyword
1. String s=new String("Welcome");//creates two objects and one reference variable

In such case, JVM will create a new string object in normal (non pool) heap memory and the literal
"Welcome" will be placed in the string constant pool. The variable s will refer to the object in heap
(non pool).

Java String Example


public class StringExample{
public static void main(String args[]){
String s1="java";//creating string by java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}

Immutable String in Java

In java, string objects are immutable. Immutable simply means unmodifiable or unchangeable.

Once string object is created its data or state can't be changed but a new string object is created.

Let's try to understand the immutability concept by the example given below:

class Testimmutablestring{
public static void main(String args[]){
String s="Sachin";
s.concat(" Tendulkar");//concat() method appends the string at the end
System.out.println(s);//will print Sachin because strings are immutable objects
}}
Output:Sachin
class Testimmutablestring1{
public static void main(String args[]){
String s="Sachin";
s=s.concat(" Tendulkar");
System.out.println(s);
}} Output:Sachin Tendulkar

15

You might also like