***I need full and good answer. ***Don\'t copy and paste. ***Don\'t use your han
ID: 3751124 • Letter: #
Question
***I need full and good answer. ***Don't copy and paste.
***Don't use your handwriting.*** I need Reference.
Explanation / Answer
1. Various usages of "this" keyword :
1.this keyword in java is a reference variable that refers to the current object.
Example:
class Account{
int a;
int b;
public void setdata(int a,int b){
a=a;
b=b;
}
public void showdata(){
System.out.println("Value of A ="+a);
System.out.println("Value of B ="+b);
}
public static void main(String[] args){
Account ac=new Account();
ac.setdata(2,3);
ac.showdata();
}
}
For the above program,our expected output will be 2 and 3. But it gives 0 and 0.
Because, during the execution the compiler is confused. Whether a on the left side of the assigned operator is instance variable or local variable.Hence it doesn't set the value of a and b to 2 and 3.
Solution for this problem is "this" keyword. Using this.a = a and this.b = b in place of a=a and b=b we can avoid the above problem.
2.this keyword is used to invoke current class method
Example:
class A{
void m()
{System.out.println("hello user");}
void n(){
System.out.println("hello world");
this.m();
}
}
class TestThis{
public static void main(String args[]){
A a=new A();
a.n();
}}
3. this keyword is used to invoke current class constructor
Example:
class Cur
{ int a;
int b;
//Default constructor
Cur()
{
Cur(10, 20);
System.out.println("Inside constructor ");
}
//Parameterized constructor
Cur(int a, int b)
{
this.a = a;
this.b = b;
System.out.println("Inside parameterized constructor");
}
public static void main(String[] args)
{
Cur object = new Cur();
}
}
4. this keyword is used to pass as an argument in the method
Example:
class arg{
void m(arg obj){
System.out.println("method is invoked");
}
void p(){
m(this); //this keyword is used here as an argument
}
public static void main(String args[]){
arg s1 = new arg();
s1.p();
}
}
5.this keyword is used to return current class instance
class cls{
cls getA(){
return this;
}
void msg(){System.out.println("Hello java");}
}
class Test1{
public static void main(String args[]){
new cls().getA().msg();
}
}
2.Java program for password
import java.util.Scanner; //Importing Scanner
class passwd {
public static void main(String[] args) { //main class
Scanner input = new Scanner(System.in); //decaring scanner
System.out.println("Please enter a password: "); //Taking input as password
String str = input.nextLine();
int len = str.length(); //Finding length of the string
System.out.println(str.substring(0, str.length() / 2) + len); //Printing half string with string length.
}
}
Thank you,
With regards.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.