Arrays
- My first question is can we add, remove value in array ? NO, we can add or remove a value from a array, we cannot manipulate because array is fixed size so we need to create another array to add or remove a value
void pushValueArray(){
int [] arr = {1,2,3,4};
int [] arrCopy = new int[5];
int i = 0 ;
while(i<arr.length){
arrCopy[i]=arr[i];
i++;
}
arrCopy[arr.length]=5;
System.out.println(Arrays.toString(arrCopy));
}
- Can we replace a value in array? YES,array is fixed but we can change the values in that array by accessing their index like this
void replaceValueInArray(){
int[] arr = {10, 20, 30};
arr[2]= 40;
System.out.println(Arrays.toString(arr));
}
- Can we print a Object? this is a tricky one ,
- String is object
- array is object
- Object(new) is object
1. String is object
we can print String using System.out.println()
String str = "helllo";
System.out.println(str);
String is object so the referece address of the String should print but the Output will be helllo,why ?
Because String calls toString() method automatically,
public String toString(String x) {
return this;
}
this happens in the behind the screens
2. array is object
we can print a Array? Yes we can!
int [] arr = {1,2,3,4};
System.out.println(arr); // ref address
System.out.println(Arrays.toString(arr)); // o/p : [1,2,3,4]
- Is the output is array or string?
The output is String but in array Format because the array is object we cant print directly so we use
Arrays.toString()
3. Object(new) is object(TBD)
can we print Object? Yes but we need to override it
class ClassName {
int x = 10;
@Override //TBD
public String toString() {
return "x = " + x;
}
public static void main(String[] args){
ClassName obj = new ClassName();
System.out.println(obj); // o/p : x = 10
}
}
What is auto boxing and auto unboxing ?
*1. Auto Boxing *
Autoboxing = converting primitive → object automatically
int x = 10;
Integer obj = x; // autoboxing
2. Auto Unboxing
Unboxing = converting object → primitive automatically
Integer obj = 10;
int x = obj; // unboxing
Top comments (0)