0% found this document useful (0 votes)
14 views27 pages

Array

The document provides an overview of arrays in Java, including their definition, advantages, disadvantages, and methods for accessing and manipulating them. It also covers the concept of strings, type casting, and examples of both widening and narrowing type casting. Additionally, it explains the use of multidimensional arrays and various string methods available in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views27 pages

Array

The document provides an overview of arrays in Java, including their definition, advantages, disadvantages, and methods for accessing and manipulating them. It also covers the concept of strings, type casting, and examples of both widening and narrowing type casting. Additionally, it explains the use of multidimensional arrays and various string methods available in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

ARRAYS in JAVA

ARRAY
• An array is a collection of similar types of data
having contiguous memory allocation.
• The indexing of the array starts from 0., i.e 1st
element will be stored at the 0th index, 2nd
element at 1st index, 3rd at 2nd index, and so
on.
• The size of the array can not be increased at run
time therefore we can store only a fixed size of
elements in array.
• Use Case: Storing marks of 5 students
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.
Accessing Array Elements
• int[] marks; //Declaration!
• marks = new int[5]; //Memory allocation!
• int[] marks = new int[5]; //Declaration +
Memory allocation!
• int[] marks = {100,70,80,71,98} // Declare +
Initialize!

Note : Array indices start from 0 and go till (n-1)


where n is the size of the array.
Array length
Unlike C/C++, we don't need to use the
sizeof() operator to get the length of arrays
in Java because arrays are objects in Java
therefore we can use the length property.
Example
[Link] //Gives 5 if marks is a reference to
an array with 5 elements
FOR EACH LOOP
• For each loop is an enhanced version of for loop.
• It travels each element of the data structure one by
one.
• Note that you can not skip any element in for loop and
it is also not possible to traverse elements in reverse
order with the help of for each loop.
• It increases the readability of the code.
• If you just want to simply traverse an array from start
to end then it is recommended to use for each loop.
Class Main{
public static void main(String args[]){
//declaring an array
int arr[]={1,2,3,3,4,5};
//traversing the array with for-each loop
for(int i:arr){
[Link](i);
}
}
}
EXAMPLE-FOR EACH LOOP
class ForEachExample1{
public static void main(String args[]){
int arr[]={12,13,14,44};
int total=0;
for(int i:arr){
total=total+i;
}
[Link]("Total: "+total);
}
}
Passing Array to a Method in Java
• We can pass the java array to method so
that we can reuse the same logic on any
array.

• Let's see the simple example to get the


minimum number of an array using a
method.
class Testarray2{
//creating a method which receives an array as a parameter
static void min(int arr[]){
int min=arr[0];
for(int i=1;i<[Link];i++)
if(min>arr[i])
min=arr[i];
[Link](min);
}
public static void main(String args[]){
int a[]={33,3,4,5};//declaring and initializing an array
min(a);//passing array to method
}}
Anonymous Array in Java
Java supports the feature of an anonymous array, so you don't need to
declare the array while passing an array to the method.

public class TestAnonymousArray{


//creating a method which receives an array as a parameter
static void printArray(int arr[]){
for(int i=0;i<[Link];i++)
[Link](arr[i]);
}
public static void main(String args[]){
printArray(new int[]{10,22,44,66});//passing anonymous array to method
}}
Multidimensional Arrays in Java
• Multidimensional Arrays are an Array of Arrays.
Each elements of an M-D array is an array itself.
Marks in the previous example was a 1-D array.
package [Link];
public class cwh_28_multi_dim_arrays {
public static void main(String[] args) {
int [] marks; // A 1-D Array
int [][] flats; // A 2-D Array
flats = new int [2][3];
flats[0][0] = 101;
flats[0][1] = 102;
flats[0][2] = 103;
flats[1][0] = 201;
flats[1][1] = 202;
flats[1][2] = 203;
// Displaying the 2-D Array (for loop)
[Link]("Printing a 2-D array using for loop");
for(int i=0;i<[Link];i++){
for(int j=0;j<flats[i].length;j++) {
[Link](flats[i][j]);
[Link](" ");
}
[Link]("");
STRINGS
• A string is a sequence of characters.
• Strings are objects that represent a char array.
For example :
char[] str = {‘J',,‘A',‘V',‘A'};

In java , string is not a primitive datatype. String is a


class with special abilities so it looks like primitive
datatype.
Different ways to create a string in Java :
In Java, strings can be created in two ways :
• By using string literal
• By using the new

Creating String using String literal :


String s1= "String literal“;
Creating String using new

String s=new String(“JAVA”);


String str1 = new String("Keepcoding");
String str2 = new String("Keep coding");
[Link](str1 == str2); //F

String str1 = "CodeWithHarry";


String str2 = "CodeWithHarry"
[Link](str1 == str2); //T
String Methods in Java
•String Methods operate on Java Strings.
They can be used to find the length of
the string, convert to lowercase, etc.
•Some of the commonly used String
methods are:
String name = “JAVA”;
Method Description

1. length() Returns the length of String name. (4 in this case)

2. toLowerCase() Converts all the characters of the string to the lower case letters.

3. toUpperCase() Converts all the characters of the string to the upper case letters.

Returns a new String after removing all the leading and trailing spaces
4. trim()
from the original string.

Returns a substring from start to the end. Substring(2) returns “va”.


5. substring(int start)
[Note that indexing starts from 0]

6. replace(‘r’, ‘p’) Returns a new string after replacing r with p.


Returns true if the name starts with the
7. startsWith(“JA”) string “JA”. (True in this case)

8. endsWith(“va”) Returns true if the name ends with the string


“va”. (True in this case)

9. charAt(2) Returns the character at a given index


position. (v in this case)
TYPE CASTING IN JAVA
• In Java, type casting is a method or process that converts a data type
into another data type in both ways manually and automatically. The
automatic conversion is done by the compiler and manual conversion
performed by the programmer.
EXAMPLE WIDENING TYPE
public class WideningTypeCastingExample
{
public static void main(String[] args)
{
int x = 7;
long y = x;
float z = y;
[Link]("Before conversion, int value "+x);
[Link]("After conversion, long value "+y);
[Link]("After conversion, float value "+z);
} }
EXAMPLE NARROWING TYPE
public class NarrowingTypeCastingExample
{
public static void main(String args[])
{
double d = 166.66;
long l = (long)d;
int i = (int)l;
[Link]("Before conversion: "+d);
[Link]("After conversion into long type: "+l);
[Link]("After conversion into int type: "+i);
} }
EXAMPLE

You might also like