+ 5
Explain this (java)
Please somebody explain me how this works in java. https://www.sololearn.com/post/83153/?ref=app
2 Answers
+ 3
1) "This" is a reference variable which refers instance variable and current class object.
For better understanding follow the example given below
public class ThisDemo
{
int value; //instance variable
ThisDemo(int value){ //constructor
this.value=value;
}
int getData(){
return value;
}
public static void main(String[] args) {
ThisDemo d=new ThisDemo(10);
System.out.println(d.getData());
}
}
Output:
10
2) "this" is also used to call constructors..
Example:
public class Thisdemo2{
int value1,value2;
Thisdemo2(){
this(20);
value1=10;
}
Thisdemo2(int value){
value2=value;
}
void getData(){
System.out.println("value1= "+value1);
System.out.println("value2= "+value2);
}
}
public class Program
{
public static void main(String[] args) {
Thisdemo2 f=new Thisdemo2();
f.getData();
}
}
Output:
value1=10
value2=20
If you like my theory hit like my comment and follow my page...đ
+ 5
It's quite easy.
You have an array of strings a, b, c and d.
Then, there's a for each loop or enhanced for loop. It will take a value of string in each iteration from the array.
In 1st iteration, s is actually a. It will print a.
Now, there is if condition, but since it is wrong, it will skip it out. Next, it will print don as per command and then because of break, loop will break and program will terminate.
The tricky part is that if if condition is defined without curly braces, it will take only one life after it as its condition. Hence, only continue; lies in the range of if.