Arrays: Department of Computer Science & Engineering Web Technologies-Kcs-602 Unit-I
Arrays: Department of Computer Science & Engineering Web Technologies-Kcs-602 Unit-I
Arrays: Department of Computer Science & Engineering Web Technologies-Kcs-602 Unit-I
WEB TECHNOLOGIES-KCS-602
UNIT-I
TOPICS COVERED:
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.
Example:
Creating Arrays:
Page 1
You can create an array by using the new operator with the following syntax:
• 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:
Example:
Following statement declares an array variable, myList, creates an array of 10 elements of
double type and assigns its reference to myList:
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
• a, b − formal parameters
Method definition consists of a method header and a method body. The same is shown in the
following syntax −
Syntax
• modifier − It defines the access type of the method and it is optional to use.
• 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.
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);
}
}
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.
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.
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
If you apply static keyword with any method, it is known as static method.
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
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
In the above example, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package.
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.
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
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
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
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.
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.
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.
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);
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 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
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).
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