SILVER OAK COLLEGE OF COMPUTER APPLICATION
SUBJECT :CORE
JAVA
TOPIC :UNIT -2.1 Array
-[Link]
RAVAL
UNIT -2.1 ARRAY
Class Variable and Methods - Static Keyword
This keyword
❖ Arrays
One dimensional, Two dimensional
Using For..each with array
Passing arrays to methods and returning arrays from
method
Command line arguments
Class Variable
• All variables are also known as instance variable.
• This is because of the fact that each instance or object
has its own copy of values for the variables.
• Hence other use of the ―dot” operator is to initialize
the value of variable for that instance.
Methods with parameters
class prg {
int n,n2,sum;
public void take(int x,int y) {
n=x; n2=y; }
public void sum() { sum=n+n2; }
public void print() { [Link]("The Sum is"+sum); }
}
class prg1 {
public static void main(String args[]) { prg obj=new prg();
[Link](10,15); [Link](); [Link](); }
}
Methods with a Return Type
• When method return some value that is the type of
that method.
• For Example: some methods are with parameter but
that method did not return any value that means type
of method is void. And if method return integer value
then the type of method is an integer.
class Demo1
{ int n, n2;
public void take( int x,int y)
{ n=x; n=y; }
public int process()
{ return (n+n2); }
}
class prg
{ public static void main(String args[])
{ int sum;
Demo1 obj=new Demo1();
[Link](15,25);
sum=[Link]();
[Link]("The sum is"+sum);
}
}
Method Overloading
• Method overloading means method name will be
same but each method should be different parameter
list.
class prg1
{ int x=5,y=5,z=0;
public void sum()
{ z=x+y;
[Link]("Sum is "+z); }
public void sum(int a,int b)
{ x=a; y=b;
z=x+y;
[Link]("Sum is "+z); }
public int sum(int a)
{ x=a;
z=x+y;
return z;
}
}
class Demo
{
public static void main(String args[])
{
prg1 obj=new prg1();
[Link]();
[Link](10,12);
[Link](+[Link](15));
}
}
Passing Objects as Parameters
class para123
{ int n,n2,sum,mul;
public void take(int x,int y)
{ n=x; n2=y; }
public void sum() {
sum=n+n2;
[Link]("The Sum is"+sum); }
public void take2(para123 obj)
{ n=obj.n; n2=obj.n2; }
public void multi()
{ mul=n*n2;
[Link]("Product is"+mul); }
}
class DemoPara • We have defined a
{
method “take2” that
public static void
main(String args[]) declares an object
{ named obj as
para123 ob=new parameter.
para123();
• We have passed ob to
[Link](3,7);
[Link](); our method. The
ob.take2(ob); method “take2”
[Link](); automatically gets 3,7
} as values for n and n2.
}
Static Fields and Methods
• A static data field does not belong to any one object
– Also called a class variable
– Only one instance of the variable exists for all instances of the class
• Note that a static data field is not a constant (final)
• All instances of the class reference that one variable
Static Fields and Methods
• Consider the need of a method that does not belong to an object of any type
• Examples
– A method to find the max or min of two or more numbers
– A square root method
• When specified static, a method is still a member of the class
– However, does not need an object as a prefix to the call
• Call with the name of the class
• int maximum = [Link](2, 3);
• double root = [Link](4.2);
this Keyword in Java
• ‘this’ is a reference variable that refers to the current object.
//Java code for using 'this' keyword to
//refer current class instance variables
class Test
{ int a; int b;
// Parameterized constructor
Test(int a, int b)
{ this.a = a; this.b = b; }
void display()
{ //Displaying value of variables a and b
[Link]("a = " + a + " b = " + b); }
public static void main(String[] args)
{ Test object = new Test(10, 20); [Link](); }
}
ARRAY
● Array is collection of related data items
● Creating an array
− Declare an array
− Create memory location
− Putting values to memory locations
Declaring an Array Variable
● Do not have to create an array while declaring array
variable
− <type> [ ] variable_name;
− Double[ ] myList;
− double myList[ ];
● Both syntaxes are equivalent
● No memory allocation at this point
Defining an Array
Define an array as follows:
− variable_name=new <type>[arraySize];
− Number = new int[5];
− Mylist = new int[10];
It creates an array using new dataType[arraySize];
∙ It assigns the reference of the newly created array to
the variable variable_name.
∙ dataType arrayname[ ] = {list of values};
∙ Int a [ ]={1,2,3,4,5,6,7,};
∙ Array index starts from 0 to arraySize-1;
∙ int is of 4 bytes, total space=4*10=40 bytes
Declaring and defining in the same statement:
− Double [ ] mylist = new double[10];
What happens if we define diffrent type…
● We define
− Int[ ] a=new long[20];
incompatible types
found: long[]
required: int[]
● The right hand side defines an array, and thus the array variable should refer to
the same type of array
Example:
int prime[100];
error=> ']' expected
long primes[20];
● The C++ style is not permitted in JAVA syntax
long[] primes = new long[20];
primes[25]=33;
Runtime Error:Exception in thread “main”
[Link]
Array Size through Input
….
BufferedReader stdin = new BufferedReader (new InputStreamReader([Link]));
String inData;
int num;
[Link]("Enter a Size for Array:");
inData = [Link]();
num = [Link]( inData ); // convert inData to int
long[] primes = new long[num];
[Link](“Array Length=”+[Link]);
….
SAMPLE RUN:
Enter a Size for Array:
4
Array Length=4
Example for array
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 (double element: myList) {
[Link](element);
}
}
}
Otput:
1.9
2.9
3.4
3.5
Reusing Array Variables
● int[] primes=new int[10];
……
primes=new int[50];
● Previous array will be discarded
● Cannot alter the type of array
Demonstration
long[] primes = new long[20];
primes[0] = 2;
primes[1] = 3;
[Link](primes[0]);
[Link](primes[1]);
Output:
2
3
Array Length
● Refer to array length using length() method
− A data member of array object
− array_variable_name.length
− for(int k=0; k<[Link];k++)
● Sample Code:
long[ ] primes = new long[20];
[Link]([Link]);
● Output: 20
● If number of elements in the array are changed, JAVA will automatically
change the length attribute!
Sample Program
class MinArray
{
public static void main ( String[] args )
{
int[] array = { 20, 19, 1, 5, 71, 27, 19, 95 } ;
int min=array[0]; // initialize the current minimum
for ( int index=0; index < [Link]; index++ )
if ( array[ index ] < min )
min = array[ index ] ;
[Link]("The minimum of this array is: " + min );
}
}
Two dimenssional array
● Representing 2D arrays
− Int myarray[][];
− Myarray = new int[3][4];
− Int myarray [][] = new int[3][4];
● Example
● Int myarray[2][3]={0,0,0,1,1,1};
2 columns and 3 rows
For-each Loop
• Java For-each Loop | Enhanced For Loop
• The Java for-each loop or enhanced for loop is introduced since J2SE 5.0.
• It provides an alternative approach to traverse the array or collection in
Java.
• It is mainly used to traverse the array or collection elements.
• The advantage of the for-each loop is that it eliminates the possibility of
bugs and makes the code more readable.
• It is known as the for-each loop because it traverses each element one by
one.
Syntax
• The syntax of Java for-each loop consists of data_type
with the variable followed by a colon (:), then array or
collection.
for(data_type variable : array | collection)
{ //body of for-each loop }
• How it works?
• The Java for-each loop traverses the array or collection
until the last element. For each element, it stores the
element in the variable and executes the body of the
for-each loop.
Passing Array To The Method
• Arrays can be passed to other methods just like how you pass primitive
data type’s arguments.
• To pass an array as an argument to a method, you just have to pass the
name of the array without square brackets.
• The method prototype should match to accept the argument of the array
type.
• Given below is the method prototype:
void method_name (int [] array);
• This means method_name will accept an array parameter of type int. So if
you have an int array named myarray, then you can call the above
method as follows:
• method_name (myarray);
How To Return An Array
• Apart from all the primitive types that you can return from Java programs,
you can also return references to arrays.
• While returning a reference to an array from a method, you should keep in
mind that:
• The data type that returns value should be specified as the array of the
appropriate data type.
• The returned value from a method is the reference to the array.
• The array is returned from a method in the cases where you need to
return multiple values of the same type from a method.
• This approach becomes useful as Java doesn’t allow returning multiple
values.
Command Line Arguments
• The java command-line argument is an argument i.e. passed at the time of
running the java program.
• The arguments passed from the console can be received in the java
program and it can be used as an input.
• So, it provides a convenient way to check the behaviour of the program for
the different values. You can pass N (1,2,3 and so on) numbers of
arguments from the command prompt.
class CommandLineExample{
public static void main(String args[]){
[Link]("Your first argument is: "+args[0]); } }
• compile by > javac [Link]
• run by > java CommandLineExample sonoo
• Output: Your first argument is: sonoo
To be continue in Core Java_Unit-2_2…