JAVA UNIT 1
Array, String
JAVA ARRAY
• Java array is an object which contains elements of a similar data type
• The elements of an array are stored in a contiguous memory location.
• It is a data structure where we store similar elements.
Types of Array in java
• Single Dimensional Array
• Two-dimensional array
• Multidimensional Array
Single Dimensional Array in Java
• Syntax to Declare an Array in Java
• dataType[] arr; (or)
• dataType []arr; (or)
• dataType arr[];
• Creating array
• Arrayname = new type[size];
• Rollno = new int[10];
Declaration, Instantiation and Initialization of
Java Array
• int a[]={33,3,4,5};//declaration, instantiation and initialization
Multidimensional Array in Java
In such case, data is stored in row and column-based index (also known as matrix form).
• dataType[][] arrayRefVar; (or)
• dataType [][]arrayRefVar; (or)
• dataType arrayRefVar[][]; (or)
• dataType []arrayRefVar[];
Example to instantiate Multidimensional Array in Java
• int[][] arr=new int[3][3];//3 row and 3 column
Example to initialize Multidimensional Array in Java
• arr[0][0]=1;
• arr[0][1]=2;
• arr[0][2]=3;
• arr[1][0]=4;
• arr[1][1]=5;
• arr[1][2]=6;
• arr[2][0]=7;
• arr[2][1]=8;
• arr[2][2]=9;
Java String
In Java, string is basically an object that represents sequence of char
values. An array of characters works same as Java string.
For example:
• char[] ch={'j','a','v','a','t','p','o','i','n','t'};
• String s=new String(ch);
• is same as:
• String s="javatpoint";
How to create a string object?
There are two ways to create String object:
• By string literal
• By new keyword
1) String Literal
Java String literal is created by using double quotes.
For Example:
String s="welcome";
2) By new keyword
String s=new String("Welcome");//creates two objects and
one reference variable