SlideShare a Scribd company logo
Chap1 array
 An array is a collection of variables of the
same type , referred by a common name.
 Advantage of an array is that it organizes
data in such a way that it can be easily
manipulated.
 If data is stored in array, it can be easily
sorted.
 In java, arrays are implemented as objects.
 A one-dimensional array is list of related
objects
 type array_name[]=new type[size];
 Type declares the element type of the array
 Size determines the number of elements in
the array created.
 Two steps, declaration and allocation of
memory for array
 First declare any array reference variable
 Second, allocate memory for the array using
“new” operator.
 Ex: int sample[]=new int[10];
 Can be split into two statements as
int sample[];
sample=new int[10];
 In this , first statement , when sample array is
created , no physical object is referred
 Second statement , executes that sample is
linked with an array.
class ArrayDemo{
public static void main(String args[]){
int sample[]=new int[10];
int i;
for(i=0;i<10;i++)
sample[i]=i;
for(i=0;i<10;i++)
System.out.print("Sample["+i+"]:"+sample[i]+"n"
);
}
}
class MinMax{
public static void main(String args[]){
int nums[]=new int[10];
int min,max;
nums[0]=99;
nums[1]=-10;
nums[2]=100123;
nums[3]=18;
nums[4]=-978;
nums[5]=5623;
nums[6]=463;
nums[7]=-9;
nums[8]=287;
nums[9]=49;
min=max=nums[0];
for(int i=0;i<10;i++) {
if(nums[i]<min)
min=nums[i];
if(nums[i]>max)
max=nums[i]; }
System.out.print("Minimum="+min+"nMaximum:"+max);
} }
 Rather than having 10 different assignment
statements, there is an easier way to do this
in a single assignment step
 type array_name[]={val1,val2,val3 … val N};
 Rather than giving a value for size directly the
values can be given for the array in a single
step.
 They are assigned in the index order from left
to right side.
 No need to use new operator in this case
class MinMax2{
public static void main(String args[]){
int nums[]={ 99,-10,100123,18,-978,5623,463,-
9,287,49};
int min,max;
min=max=nums[0];
for(int i=0;i<10;i++)
{
if(nums[i]<min)
min=nums[i];
if(nums[i]>max)
max=nums[i];
}
System.out.print("Minimum="+min+"nMaximum:"+max);
}
}
 Array boundaries are strictly enforced in Java
 Gives run time error in case of end of an array or
over run or under run of an array
class ArrayErr{
public static void main(String args[]){
int sample[]=new int[10];
int i;
for(i=0;i<100;i++)
sample[i]=i;
}
}
 Arrays of two or more dimensions, in java
language multidimensional arrays means
arrays of arrays.
 Two dimensional arrays
 Irregular arrays
 Arrays of three or more dimensions
 To declare a two dimensional array of size
10, 20 you would write,
 int table[][]=new int[10][20];
 Other languages use of comma is done for
array dimensions, here square brackets are
used.
class TwoD{
public static void main(String args[]){
int table[][]=new int[3][4];
int i,t;
for(t=0;t<3;t++)
{
for(i=0;i<4;i++){
table[t][i]=t+i;
System.out.print(table[t][i]+" ");
}
System.out.println();
}
}
}
 In case of multidimensional array, we should
mention the memory of the left first
 You can give the rightmost dimension separately
 Used in the situation where a very large two
dimensional array is required which is sparsely
populated (on in which not all the elements will
be used)
 int table[ ][ ]=new int[3][ ];
 table[0]=new int[4];
 table[1]=new int[3];
 table[2]=new int[2];
 General form of three or more dimensional array
 type name[][]…[ ]= new
type[size1][size2]…[sizeN];
 int multidimen[ ][ ][ ]=new int [3][10][5];
 A multidimensional array can be initialized by
enclosing each dimension initializer list
within its own set of curly braces.
type array_name[ ][ ]={
{val,val,val…val},
{val,val,val…val},
.
.
{val,val,val…val},
};
class squares{
public static void main(String args[]){
int square[][]={{1,1},{2,4},{3,9},{4,16},{5,25}};
int i,j;
for(i=0;i<5;i++){
for(j=0;j<2;j++)
System.out.print(square[i][j]+" ");
System.out.println();
}
}
}
 type[ ] var_name;
 Eg : int counter[]=new int[3];
 int [] counter=new int[3];
 Both the above statements are same
 This approach is helpful when you want to
create multiple arrays of the same type
 int num0[],num1[],num2[];
 Better approach is
 int [ ] num0,num1,num2;
 When you assign one array reference variable
to another, you are simply changing what
object that variable refers to.
 You are not causing a copy of the array to be
made nor you are causing the contents of one
of array to be copied to another.
class AssignAref
{
public static void main(String args[]){
int i;
int nums1[]=new int[10];
int nums2[]=new int[10];
for(i=0;i<10;i++)
nums1[i]= i;
for(i=0;i<10;i++)
nums2[i]= -i;
System.out.print("num1:");
for(i=0;i<10;i++)
System.out.print(nums1[i]+" " );
System.out.println();
System.out.print("num2:");
for(i=0;i<10;i++)
System.out.print(nums2[i]+" " );
System.out.println();
//make num2 refer to num1
nums2=nums1;
System.out.print("here is nums2
after assignment:");
for(i=0;i<10;i++)
System.out.print(nums2[i]+"
" );
System.out.println();
//operate on nums1 array through
nums2
nums2[3]=99;
System.out.print("here is nums1
after change through nums2");
for(i=0;i<10;i++)
System.out.print(nums1[i]+"
" );
System.out.println();
}
}
 Arrays are implemented as objects, each
array is associated with a length instance
variable that contains the number of elements
that array can hold.
 Length contains size of the array
class lengthDemo{
public static void main(String
args[]){
int list[]=new int[10];
int nums[]={1,2,3};
int
table[][]={{1,2,3},{4,5},{6,7,8
,9}};
System.out.println("length
of the list is "+list.length);
System.out.println("length
if nums "+nums.length);
System.out.println("length
of table is: "+table.length);
for(int
i=0;i<table.length;i++)
System.out.println("lengh
of table["+i+"] is
"+table[i].length);
System.out.println();
for(int
j=0;j<list.length;j++)
list[j]=j*j;
for(int
k=0;k<list.length;k++)
System.out.print(list[
k]+" ");
System.out.println();
}
}
 A for-each loop cycles through a collection of
objects such as array in strictly sequential
fashion from start to finish.
 It is released in JDK 5, for-each is also referred as
enhanced for loop
 Syntax:
for(type itr_variable: collection)
statement block;
 type specifies the data type of the iteration
variable i.e itr_variable
 That will receive elements from collections one at
a time from beginning to the end of the
collection
 Itr_variable recieves the data from collection,
hence type of the collection and itr_variable
should be same always
class EnhancedForLoop {
public static void main(String[] args) {
int primes[] = { 2, 3, 5, 7, 11, 13, 17};
for (int t: primes) {
System.out.println(t);
}
}
}
 If we want to terminate the for-each loop before
completion of all the loops, one can use “break”
statement.
class EnhancedForLoop {
public static void main(String[] args) {
int primes[] = { 2, 3, 5, 7, 11, 13, 17};
for (int t: primes) {
System.out.println(t);
if(t==5)break;
}
}
}
 Itr_variable is only for read only purpose.
 An assignement to the iteration variable has no
effect on underlying array.
class EnhancedForLoop {
public static void main(String[] args) {
int primes[] = { 2, 3, 5, 7, 11, 13, 17};
for (int t: primes) {
System.out.print(t+" ");
t=t*2;
}
System.out.println();
for (int t: primes) {
System.out.print(t+" ");
}
}
}
 Enhanced for loop works for
multidimensional arrays.
 Multidimensional array is arrays of array.
 Two dimensional array is an array of one
dimensional array.
 In each iteration, it obtains next array not an
individual element
class Foreach2{
public static void main(String args[])
{
int sum=0;
int nums[][]=new int[3][5];
for(int i=0;i<nums.length;i++)
for(int j=0;j<nums[i].length;j++)
nums[i][j]=(i+1)*(j+1);
System.out.println("Value is :");
for(int x[]:nums){
for(int y:x){
System.out.print(y+" ");
sum+=y;
}
System.out.println();
}
System.out.println("Summation :"+sum);
}
}
 Used for searching of the data in the given
set of numbers.
 Can be used for searching in unsorted array
 It stops when the key is found.
class search{
public static void main(String args[])
{
int nums[]={6,8,3,7,5,6,1,4};
int key=5;
boolean found=true;
for(int x:nums)
if(x==key){
found=true;
break;
}
if(found)
System.out.print("Value found!!");
}
}
 String defines and supports character strings
 In other languages string is an array of
characters
 Here strings are objects.
 By using new and calling String constructor.
 String str=new String(“hello” );
 String object called str will contain a string
called “hello”
Method Meaning
boolean equals(str) Returns true if the involving string
contains the same character
sequence as str
int length() Obtains the length of the str
char chatAt(index) Obtains character at index
mentioned
int compareTo(str) Returns less than zero if the
invoking string is less than str,
gretaer than zero if invking string
is greater than str and zero if they
are equal
int indexOf(str) Searches invoking string for
substring specified by str. Returns
the index of the first match or -1
on failure
int lastIndexOf(str) Searches invoking string for
substring specified by str. Returns
the index of the last match or -1
on failure
class StrOps{
public static void main(String args[]){
String str1="when it come to web
programming, Java is #1.";
String str2=new String(str1);
String str3="Java strings are powerfull";
int result,idx;
char ch;
System.out.println("length of
str1:"+str1.length());
//display one charecter at a time
for(int i=0;i<str1.length();i++)
System.out.print(str1.charAt(i)+" ");
System.out.println();
if(str1.equals(str2))
System.out.println("String 1 and 2 are
equal");
else
System.out.println("String 1 and 2 are
not equal");
if(str1.equals(str3))
System.out.println("String 1 and 3 are
equal");
else
System.out.println("String 1 and 3 are not
equal");
result=str1.compareTo(str3);
if(result==0)
System.out.println("String 1 and 3
are not equal");
else if(result<0)
System.out.println("String 1 is
less than string 3");
else
System.out.println("String 1 is
greater than string 3");
str2="one two three one";
idx=str2.indexOf("one");
System.out.println("Index of first
occurance of one :"+idx);
idx=str2.lastIndexOf("one");
System.out.println("Index of last
occurance of one :"+idx);
}
}
Chap1 array
 Can be easily performed by using + between
strings.
String str=“java”;
String sr1=“programming”;
String finalstring=str+str1;
class StringArrays{
public static void main(String args[]){
String strs[]={"this", "is", "a","test"};
System.out.println("original array");
for(String s:strs)
System.out.print(s+" ");
System.out.println();
//change in a string
strs[1]="was";
strs[3]="test,tool";
System.out.println("After modification");
for(String s:strs)
System.out.print(s+" ");
}
}
 Once created, the character sequence that makes
up the string cannot be altered.
 When a change is required , you just have to create
a new string, the unused strings are automatically
garbage collected.
 substring()- method returns a new string that
contains a specified portion of the invoking string.
class Substr{
public static void main(String args[])
{
String orgstring="java programming is the
best!";
String substring=orgstring.substring(5,12);
System.out.println("original
string:"+orgstring+"nSubstring is
:"+substring);
}
}
class Stringswitch{
public static void main(String args[])
{
String choice="cancel";
switch(choice){
case "connect": System.out.println("Connecting!");
break;
case "cancel":System.out.println("cancelling!");
break;
default: System.out.println("Enter correct string");
break;
}
}
}
 A command line argument is the information
that directly follows the program’s name on
the command line when it is executed.
 They are stored in String array passed in the
main()
class CLDemo
{
public static void main(String args[])
{
System.out.println("These are:"+args.length+"
command line arguements");
System.out.println("they are:");
for(int i=0;i<args.length;i++)
System.out.println("args["+i+"]:"+args[i]);
}
}

More Related Content

PPT
Oop lecture7
PPTX
Java arrays
PPTX
Python Datatypes by SujithKumar
PDF
Mementopython3 english
PPTX
Java arrays
PDF
C Language Lecture 20
PPT
Algo>Arrays
Oop lecture7
Java arrays
Python Datatypes by SujithKumar
Mementopython3 english
Java arrays
C Language Lecture 20
Algo>Arrays

What's hot (18)

PDF
Lec 8 03_sept [compatibility mode]
PPTX
Java notes 1 - operators control-flow
PPTX
Arrays in java
PPTX
Pragmatic metaprogramming
PDF
Python for Dummies
PPT
Java Arrays
PPTX
C# Arrays
PPTX
Introduction to python programming 2
PPTX
Introduction to python programming 1
PDF
Functions in python
PPTX
Array
PDF
Array and Collections in c#
PDF
Basic R Data Manipulation
PPTX
18. Dictionaries, Hash-Tables and Set
PPTX
18. Java associative arrays
PDF
Array&amp;string
PPT
Java: Introduction to Arrays
PPT
Lec 25 - arrays-strings
Lec 8 03_sept [compatibility mode]
Java notes 1 - operators control-flow
Arrays in java
Pragmatic metaprogramming
Python for Dummies
Java Arrays
C# Arrays
Introduction to python programming 2
Introduction to python programming 1
Functions in python
Array
Array and Collections in c#
Basic R Data Manipulation
18. Dictionaries, Hash-Tables and Set
18. Java associative arrays
Array&amp;string
Java: Introduction to Arrays
Lec 25 - arrays-strings
Ad

Viewers also liked (7)

PPT
Control statements
PPTX
Chap2 class,objects
PPTX
Chap1 packages
PPTX
Chap2 class,objects contd
PPTX
Java-Unit 3- Chap2 exception handling
PPTX
output devices
PPT
Printers,types ,working and use.
Control statements
Chap2 class,objects
Chap1 packages
Chap2 class,objects contd
Java-Unit 3- Chap2 exception handling
output devices
Printers,types ,working and use.
Ad

Similar to Chap1 array (20)

PPTX
Arrays in programming
PPTX
ch 7 single dimension array in oop .pptx
PPTX
Arrays in Java with example and types of array.pptx
PPTX
6_Array.pptx
DOCX
Arraysnklkjjkknlnlknnjlnjljljkjnjkjn.docx
PPT
Array
PPT
17-Arrays en java presentación documento
PDF
Lecture 6 - Arrays
PDF
Java arrays (1)
PPTX
Computer programming 2 Lesson 13
PPT
ch06.ppt
PPT
PPT
ch06.ppt
PPT
array Details
PDF
PPTX
Chapter 7.1
PPTX
07+08slide.pptx
DOCX
Java R20 - UNIT-3.docx
PPT
Data Structure Midterm Lesson Arrays
PDF
Arrays a detailed explanation and presentation
Arrays in programming
ch 7 single dimension array in oop .pptx
Arrays in Java with example and types of array.pptx
6_Array.pptx
Arraysnklkjjkknlnlknnjlnjljljkjnjkjn.docx
Array
17-Arrays en java presentación documento
Lecture 6 - Arrays
Java arrays (1)
Computer programming 2 Lesson 13
ch06.ppt
ch06.ppt
array Details
Chapter 7.1
07+08slide.pptx
Java R20 - UNIT-3.docx
Data Structure Midterm Lesson Arrays
Arrays a detailed explanation and presentation

More from raksharao (20)

PPTX
Unit 1-logic
PPTX
Unit 1 rules of inference
PPTX
Unit 1 quantifiers
PPTX
Unit 1 introduction to proofs
PPTX
Unit 7 verification &amp; validation
PPTX
Unit 6 input modeling problems
PPTX
Unit 6 input modeling
PPTX
Unit 5 general principles, simulation software
PPTX
Unit 5 general principles, simulation software problems
PPTX
Unit 4 queuing models
PPTX
Unit 4 queuing models problems
PPTX
Unit 3 random number generation, random-variate generation
PPTX
Unit 1 introduction contd
PPTX
Unit 1 introduction
PDF
Module1 part2
PDF
Module1 Mobile Computing Architecture
PPTX
java-Unit4 chap2- awt controls and layout managers of applet
PPTX
java Unit4 chapter1 applets
PPTX
Chap3 multi threaded programming
PPTX
FIT-Unit3 chapter2- Computer Languages
Unit 1-logic
Unit 1 rules of inference
Unit 1 quantifiers
Unit 1 introduction to proofs
Unit 7 verification &amp; validation
Unit 6 input modeling problems
Unit 6 input modeling
Unit 5 general principles, simulation software
Unit 5 general principles, simulation software problems
Unit 4 queuing models
Unit 4 queuing models problems
Unit 3 random number generation, random-variate generation
Unit 1 introduction contd
Unit 1 introduction
Module1 part2
Module1 Mobile Computing Architecture
java-Unit4 chap2- awt controls and layout managers of applet
java Unit4 chapter1 applets
Chap3 multi threaded programming
FIT-Unit3 chapter2- Computer Languages

Recently uploaded (20)

PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
PDF
Well-logging-methods_new................
PDF
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PPTX
UNIT 4 Total Quality Management .pptx
PDF
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
PDF
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
PDF
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
PPT
Project quality management in manufacturing
PPTX
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
PDF
Automation-in-Manufacturing-Chapter-Introduction.pdf
PDF
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
PPTX
Internet of Things (IOT) - A guide to understanding
PPTX
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
PPTX
web development for engineering and engineering
PDF
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PPTX
Construction Project Organization Group 2.pptx
PPTX
bas. eng. economics group 4 presentation 1.pptx
PPT
Mechanical Engineering MATERIALS Selection
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
Well-logging-methods_new................
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
Model Code of Practice - Construction Work - 21102022 .pdf
UNIT 4 Total Quality Management .pptx
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
Project quality management in manufacturing
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
Automation-in-Manufacturing-Chapter-Introduction.pdf
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
Internet of Things (IOT) - A guide to understanding
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
web development for engineering and engineering
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
Construction Project Organization Group 2.pptx
bas. eng. economics group 4 presentation 1.pptx
Mechanical Engineering MATERIALS Selection

Chap1 array

  • 2.  An array is a collection of variables of the same type , referred by a common name.  Advantage of an array is that it organizes data in such a way that it can be easily manipulated.  If data is stored in array, it can be easily sorted.  In java, arrays are implemented as objects.
  • 3.  A one-dimensional array is list of related objects  type array_name[]=new type[size];  Type declares the element type of the array  Size determines the number of elements in the array created.  Two steps, declaration and allocation of memory for array  First declare any array reference variable  Second, allocate memory for the array using “new” operator.
  • 4.  Ex: int sample[]=new int[10];  Can be split into two statements as int sample[]; sample=new int[10];  In this , first statement , when sample array is created , no physical object is referred  Second statement , executes that sample is linked with an array.
  • 5. class ArrayDemo{ public static void main(String args[]){ int sample[]=new int[10]; int i; for(i=0;i<10;i++) sample[i]=i; for(i=0;i<10;i++) System.out.print("Sample["+i+"]:"+sample[i]+"n" ); } }
  • 6. class MinMax{ public static void main(String args[]){ int nums[]=new int[10]; int min,max; nums[0]=99; nums[1]=-10; nums[2]=100123; nums[3]=18; nums[4]=-978; nums[5]=5623; nums[6]=463; nums[7]=-9; nums[8]=287; nums[9]=49; min=max=nums[0]; for(int i=0;i<10;i++) { if(nums[i]<min) min=nums[i]; if(nums[i]>max) max=nums[i]; } System.out.print("Minimum="+min+"nMaximum:"+max); } }
  • 7.  Rather than having 10 different assignment statements, there is an easier way to do this in a single assignment step  type array_name[]={val1,val2,val3 … val N};  Rather than giving a value for size directly the values can be given for the array in a single step.  They are assigned in the index order from left to right side.  No need to use new operator in this case
  • 8. class MinMax2{ public static void main(String args[]){ int nums[]={ 99,-10,100123,18,-978,5623,463,- 9,287,49}; int min,max; min=max=nums[0]; for(int i=0;i<10;i++) { if(nums[i]<min) min=nums[i]; if(nums[i]>max) max=nums[i]; } System.out.print("Minimum="+min+"nMaximum:"+max); } }
  • 9.  Array boundaries are strictly enforced in Java  Gives run time error in case of end of an array or over run or under run of an array class ArrayErr{ public static void main(String args[]){ int sample[]=new int[10]; int i; for(i=0;i<100;i++) sample[i]=i; } }
  • 10.  Arrays of two or more dimensions, in java language multidimensional arrays means arrays of arrays.  Two dimensional arrays  Irregular arrays  Arrays of three or more dimensions
  • 11.  To declare a two dimensional array of size 10, 20 you would write,  int table[][]=new int[10][20];  Other languages use of comma is done for array dimensions, here square brackets are used.
  • 12. class TwoD{ public static void main(String args[]){ int table[][]=new int[3][4]; int i,t; for(t=0;t<3;t++) { for(i=0;i<4;i++){ table[t][i]=t+i; System.out.print(table[t][i]+" "); } System.out.println(); } } }
  • 13.  In case of multidimensional array, we should mention the memory of the left first  You can give the rightmost dimension separately  Used in the situation where a very large two dimensional array is required which is sparsely populated (on in which not all the elements will be used)  int table[ ][ ]=new int[3][ ];  table[0]=new int[4];  table[1]=new int[3];  table[2]=new int[2];
  • 14.  General form of three or more dimensional array  type name[][]…[ ]= new type[size1][size2]…[sizeN];  int multidimen[ ][ ][ ]=new int [3][10][5];
  • 15.  A multidimensional array can be initialized by enclosing each dimension initializer list within its own set of curly braces. type array_name[ ][ ]={ {val,val,val…val}, {val,val,val…val}, . . {val,val,val…val}, };
  • 16. class squares{ public static void main(String args[]){ int square[][]={{1,1},{2,4},{3,9},{4,16},{5,25}}; int i,j; for(i=0;i<5;i++){ for(j=0;j<2;j++) System.out.print(square[i][j]+" "); System.out.println(); } } }
  • 17.  type[ ] var_name;  Eg : int counter[]=new int[3];  int [] counter=new int[3];  Both the above statements are same  This approach is helpful when you want to create multiple arrays of the same type  int num0[],num1[],num2[];  Better approach is  int [ ] num0,num1,num2;
  • 18.  When you assign one array reference variable to another, you are simply changing what object that variable refers to.  You are not causing a copy of the array to be made nor you are causing the contents of one of array to be copied to another.
  • 19. class AssignAref { public static void main(String args[]){ int i; int nums1[]=new int[10]; int nums2[]=new int[10]; for(i=0;i<10;i++) nums1[i]= i; for(i=0;i<10;i++) nums2[i]= -i; System.out.print("num1:"); for(i=0;i<10;i++) System.out.print(nums1[i]+" " ); System.out.println(); System.out.print("num2:"); for(i=0;i<10;i++) System.out.print(nums2[i]+" " ); System.out.println(); //make num2 refer to num1 nums2=nums1; System.out.print("here is nums2 after assignment:"); for(i=0;i<10;i++) System.out.print(nums2[i]+" " ); System.out.println(); //operate on nums1 array through nums2 nums2[3]=99; System.out.print("here is nums1 after change through nums2"); for(i=0;i<10;i++) System.out.print(nums1[i]+" " ); System.out.println(); } }
  • 20.  Arrays are implemented as objects, each array is associated with a length instance variable that contains the number of elements that array can hold.  Length contains size of the array
  • 21. class lengthDemo{ public static void main(String args[]){ int list[]=new int[10]; int nums[]={1,2,3}; int table[][]={{1,2,3},{4,5},{6,7,8 ,9}}; System.out.println("length of the list is "+list.length); System.out.println("length if nums "+nums.length); System.out.println("length of table is: "+table.length); for(int i=0;i<table.length;i++) System.out.println("lengh of table["+i+"] is "+table[i].length); System.out.println(); for(int j=0;j<list.length;j++) list[j]=j*j; for(int k=0;k<list.length;k++) System.out.print(list[ k]+" "); System.out.println(); } }
  • 22.  A for-each loop cycles through a collection of objects such as array in strictly sequential fashion from start to finish.  It is released in JDK 5, for-each is also referred as enhanced for loop  Syntax: for(type itr_variable: collection) statement block;  type specifies the data type of the iteration variable i.e itr_variable  That will receive elements from collections one at a time from beginning to the end of the collection
  • 23.  Itr_variable recieves the data from collection, hence type of the collection and itr_variable should be same always class EnhancedForLoop { public static void main(String[] args) { int primes[] = { 2, 3, 5, 7, 11, 13, 17}; for (int t: primes) { System.out.println(t); } } }
  • 24.  If we want to terminate the for-each loop before completion of all the loops, one can use “break” statement. class EnhancedForLoop { public static void main(String[] args) { int primes[] = { 2, 3, 5, 7, 11, 13, 17}; for (int t: primes) { System.out.println(t); if(t==5)break; } } }
  • 25.  Itr_variable is only for read only purpose.  An assignement to the iteration variable has no effect on underlying array. class EnhancedForLoop { public static void main(String[] args) { int primes[] = { 2, 3, 5, 7, 11, 13, 17}; for (int t: primes) { System.out.print(t+" "); t=t*2; } System.out.println(); for (int t: primes) { System.out.print(t+" "); } } }
  • 26.  Enhanced for loop works for multidimensional arrays.  Multidimensional array is arrays of array.  Two dimensional array is an array of one dimensional array.  In each iteration, it obtains next array not an individual element
  • 27. class Foreach2{ public static void main(String args[]) { int sum=0; int nums[][]=new int[3][5]; for(int i=0;i<nums.length;i++) for(int j=0;j<nums[i].length;j++) nums[i][j]=(i+1)*(j+1); System.out.println("Value is :"); for(int x[]:nums){ for(int y:x){ System.out.print(y+" "); sum+=y; } System.out.println(); } System.out.println("Summation :"+sum); } }
  • 28.  Used for searching of the data in the given set of numbers.  Can be used for searching in unsorted array  It stops when the key is found.
  • 29. class search{ public static void main(String args[]) { int nums[]={6,8,3,7,5,6,1,4}; int key=5; boolean found=true; for(int x:nums) if(x==key){ found=true; break; } if(found) System.out.print("Value found!!"); } }
  • 30.  String defines and supports character strings  In other languages string is an array of characters  Here strings are objects.
  • 31.  By using new and calling String constructor.  String str=new String(“hello” );  String object called str will contain a string called “hello”
  • 32. Method Meaning boolean equals(str) Returns true if the involving string contains the same character sequence as str int length() Obtains the length of the str char chatAt(index) Obtains character at index mentioned int compareTo(str) Returns less than zero if the invoking string is less than str, gretaer than zero if invking string is greater than str and zero if they are equal int indexOf(str) Searches invoking string for substring specified by str. Returns the index of the first match or -1 on failure int lastIndexOf(str) Searches invoking string for substring specified by str. Returns the index of the last match or -1 on failure
  • 33. class StrOps{ public static void main(String args[]){ String str1="when it come to web programming, Java is #1."; String str2=new String(str1); String str3="Java strings are powerfull"; int result,idx; char ch; System.out.println("length of str1:"+str1.length()); //display one charecter at a time for(int i=0;i<str1.length();i++) System.out.print(str1.charAt(i)+" "); System.out.println(); if(str1.equals(str2)) System.out.println("String 1 and 2 are equal"); else System.out.println("String 1 and 2 are not equal"); if(str1.equals(str3)) System.out.println("String 1 and 3 are equal"); else System.out.println("String 1 and 3 are not equal"); result=str1.compareTo(str3); if(result==0) System.out.println("String 1 and 3 are not equal"); else if(result<0) System.out.println("String 1 is less than string 3"); else System.out.println("String 1 is greater than string 3"); str2="one two three one"; idx=str2.indexOf("one"); System.out.println("Index of first occurance of one :"+idx); idx=str2.lastIndexOf("one"); System.out.println("Index of last occurance of one :"+idx); } }
  • 35.  Can be easily performed by using + between strings. String str=“java”; String sr1=“programming”; String finalstring=str+str1;
  • 36. class StringArrays{ public static void main(String args[]){ String strs[]={"this", "is", "a","test"}; System.out.println("original array"); for(String s:strs) System.out.print(s+" "); System.out.println(); //change in a string strs[1]="was"; strs[3]="test,tool"; System.out.println("After modification"); for(String s:strs) System.out.print(s+" "); } }
  • 37.  Once created, the character sequence that makes up the string cannot be altered.  When a change is required , you just have to create a new string, the unused strings are automatically garbage collected.  substring()- method returns a new string that contains a specified portion of the invoking string.
  • 38. class Substr{ public static void main(String args[]) { String orgstring="java programming is the best!"; String substring=orgstring.substring(5,12); System.out.println("original string:"+orgstring+"nSubstring is :"+substring); } }
  • 39. class Stringswitch{ public static void main(String args[]) { String choice="cancel"; switch(choice){ case "connect": System.out.println("Connecting!"); break; case "cancel":System.out.println("cancelling!"); break; default: System.out.println("Enter correct string"); break; } } }
  • 40.  A command line argument is the information that directly follows the program’s name on the command line when it is executed.  They are stored in String array passed in the main()
  • 41. class CLDemo { public static void main(String args[]) { System.out.println("These are:"+args.length+" command line arguements"); System.out.println("they are:"); for(int i=0;i<args.length;i++) System.out.println("args["+i+"]:"+args[i]); } }