Java 'this' keyword - java

I'm just beginning in programming and I'd like to make exercise from a book, but I can't. That's my problem:
public class increment {
int increment() {
return this + 1; // aka this++
}
public static void main(String[] args) {
int a = 0;
System.out.println(a.increment());
}
}
As you for sure guessed already, that it doesn't works, I want to ask you how to get outputed integer a incremented by one, but using keyword 'this'.
Regards and sorry for stupid questions.

It is strange to name a class like a method.
I guess you wanted this:
public class Counter {
int val;
public Counter (int start) {
val = start;
}
public void increment() {
val ++;
}
public String toString () {
return Integer.toString (val);
}
public static void main(String[] args) {
Counter counter = new Counter (0);
counter.increment ();
System.out.println(counter.toString ());
}
}

this is an object (the current object). You cannot "increment" it.
A way to do it is:
public class Increment {
int a = 0;
int increment() {
return a + 1;
// or: return this.a + 1;
// or: a++; return a; if you want a to be incremented from now on
}
public static void main(String[] args) {
Increment inc = new Increment();
System.out.println(inc.increment());
}
}

The this keyword in Java refers to the current scope's object instance. I don't think it's what you're looking for in this case.
In your example, a isn't an object of the class increment, it is a primitive int. In order to use the .increment() function you defined, it would have to be an object of type increment.
One option that may be what you're looking for would be the following.
public class Increment { //Java likes capitalized class names
private int myInt;
public Increment(int a) { //constructor
myInt = a;
}
public int increment() {
return ++myInt;
}
public static void main(String[] args) {
Increment a = new Increment(0);
System.out.println(a.increment());
}
}
In this example, we make a new class of type increment, which internally contains an integer. Its increment method increments that internal integer, and then returns the number.

you are using operator + for your current object (this). Operator overloading is not supported in java.

Something like this will work:
class MyInteger {
private int internal;
public MyInteger( int value ){
this.internal = value;
}
public int incerment(){
return ++this.internal;
}
}
public class Increment {
public static void main(String[] args) {
MyInteger a = new MyInteger(0);
System.out.println(a.increment());
}
}
You see, you can only implement methods for your own classes, not for existing classes, or for primitives like int.

i don't think you can use this to return the value, except if you're making a new class like this:
class Increment1
{
private int a;
public int increment2(int a)
{
this.a=a;
return this.a + 1;
}
}
public class Increment
{
static Increment1 b = new Increment1();
public static void main(String[] args)
{
int a = 0;
System.out.println(b.increment2(a));
}
}

You cannot increment a class like this.
You have to use a member variable that you can increment.
public class Test {
private int var;
public Test(int i) {
this.var = i;
}
int increment() {
this.var++;
}
}
public static void main(String[] args) {
Test t = new Test(0);
System.out.println(t.increment());
}

This refers to the current instance of the class, not a particular member.
You want to increment a property (I'm guessing of type long or int), and not the instance of your increment class (should be Increment, by the way).
Something like this would work:
public class increment {
private int innerValue = 0;
int increment() {
innerValue+=1
return innerValue; // aka this++
}
public static void main(String[] args) {
increment a = new increment()
System.out.println(a.increment());
}
}

Related

How can I pass a value from one constructor to another constructor?

I'm working with Java. I have a class with 2 constructors. The first constructor takes an int value as a parameter and sets an int variable as that value. The second constructor takes a string and prints it out. The idea is that when I call the first constructor from my main class, it sets an integer value. And when I call the second constructor in the main class, it takes the string representation of int variable of the first constructor and prints it out.
Here's how I made the constructors:
public class Test
{
int val;
public Test(int x)
{
val = x;
return val; //I know this won't work. So I'm looking for an alternative
}
public Test(String y)
{
System.out.println("The value is " + y);
}
}
And the main method (in a different class) looks like this:
public static void main(String [] args)
{
Test t1 = new Test(6);
Test t2 = new Test(String.valueOf(t1)); //This won't work because the first constructor can't return a value
}
So how exactly can I change the contents of the constructors so that I can pass val into the 2nd constructor?
Override toString() to return value so when you so String.valueOf(t1) it will do the toString() method;
public class Test
{
int val;
public Test(int x)
{
val = x;
}
public Test(String y)
{
System.out.println("The value is " + y);
}
#Override
public String toString()
{
return String.valueOf(val);
}
}
I think what you are probably actually trying to do is to override the toString() method of Test.
public class Test
{
int val;
public Test(int x)
{
val = x;
}
#Override
public String toString() {
return "Test:"+val;
}
}
Then you can do this:
public static void main(String [] args)
{
Test t1 = new Test(6);
String s = t1.toString();
// or this
System.out.println( t1 ); // prints "Test: 6"
}
What you're describing is actually impossible without some changes.
First and foremost, t1 and t2 are two separate instances and the values inside of them have no bearing on one another. So t1 has x=6 and t2 has x=0 (because of default values).
If you want your second constructor to have a value of x that isn't 0, then you'll need to pass that in too.
public Test(int x, String s) {
super(x);
System.out.println(x);
}
I think you don't really want two constructors. It seems like you're wanting to do something like the following:
public class Test
{
int val;
public Test(int x)
{
val = x;
}
public void printVal()
{
System.out.println("The value is " + val);
}
public static void main(String [] args)
{
Test t1 = new Test(6);
t1.printVal();
}
}
Your requirement is kinda weird. But this will work even it is kinda weird
public class Test {
private static int val;
public Test(int x) {
val = x;
}
public Test() {
System.out.println("The value is " + String.valueOf(val));
}
public static void main(String[] args) {
Test t1 = new Test(6);
Test t2 = new Test();
}
}

How to return Mutiple values from a function in java [duplicate]

I am trying to return 2 values from a Java method but I get these errors. Here is my code:
// Method code
public static int something(){
int number1 = 1;
int number2 = 2;
return number1, number2;
}
// Main method code
public static void main(String[] args) {
something();
System.out.println(number1 + number2);
}
Error:
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - missing return statement
at assignment.Main.something(Main.java:86)
at assignment.Main.main(Main.java:53)
Java Result: 1
Instead of returning an array that contains the two values or using a generic Pair class, consider creating a class that represents the result that you want to return, and return an instance of that class. Give the class a meaningful name. The benefits of this approach over using an array are type safety and it will make your program much easier to understand.
Note: A generic Pair class, as proposed in some of the other answers here, also gives you type safety, but doesn't convey what the result represents.
Example (which doesn't use really meaningful names):
final class MyResult {
private final int first;
private final int second;
public MyResult(int first, int second) {
this.first = first;
this.second = second;
}
public int getFirst() {
return first;
}
public int getSecond() {
return second;
}
}
// ...
public static MyResult something() {
int number1 = 1;
int number2 = 2;
return new MyResult(number1, number2);
}
public static void main(String[] args) {
MyResult result = something();
System.out.println(result.getFirst() + result.getSecond());
}
Java does not support multi-value returns. Return an array of values.
// Function code
public static int[] something(){
int number1 = 1;
int number2 = 2;
return new int[] {number1, number2};
}
// Main class code
public static void main(String[] args) {
int result[] = something();
System.out.println(result[0] + result[1]);
}
You could implement a generic Pair if you are sure that you just need to return two values:
public class Pair<U, V> {
/**
* The first element of this <code>Pair</code>
*/
private U first;
/**
* The second element of this <code>Pair</code>
*/
private V second;
/**
* Constructs a new <code>Pair</code> with the given values.
*
* #param first the first element
* #param second the second element
*/
public Pair(U first, V second) {
this.first = first;
this.second = second;
}
//getter for first and second
and then have the method return that Pair:
public Pair<Object, Object> getSomePair();
You can only return one value in Java, so the neatest way is like this:
return new Pair<Integer>(number1, number2);
Here's an updated version of your code:
public class Scratch
{
// Function code
public static Pair<Integer> something() {
int number1 = 1;
int number2 = 2;
return new Pair<Integer>(number1, number2);
}
// Main class code
public static void main(String[] args) {
Pair<Integer> pair = something();
System.out.println(pair.first() + pair.second());
}
}
class Pair<T> {
private final T m_first;
private final T m_second;
public Pair(T first, T second) {
m_first = first;
m_second = second;
}
public T first() {
return m_first;
}
public T second() {
return m_second;
}
}
Here is the really simple and short solution with SimpleEntry:
AbstractMap.Entry<String, Float> myTwoCents=new AbstractMap.SimpleEntry<>("maximum possible performance reached" , 99.9f);
String question=myTwoCents.getKey();
Float answer=myTwoCents.getValue();
Only uses Java built in functions and it comes with the type safty benefit.
Use a Pair/Tuple type object , you don't even need to create one if u depend on Apache commons-lang. Just use the Pair class.
you have to use collections to return more then one return values
in your case you write your code as
public static List something(){
List<Integer> list = new ArrayList<Integer>();
int number1 = 1;
int number2 = 2;
list.add(number1);
list.add(number2);
return list;
}
// Main class code
public static void main(String[] args) {
something();
List<Integer> numList = something();
}
public class Mulretun
{
public String name;;
public String location;
public String[] getExample()
{
String ar[] = new String[2];
ar[0]="siva";
ar[1]="dallas";
return ar; //returning two values at once
}
public static void main(String[] args)
{
Mulretun m=new Mulretun();
String ar[] =m.getExample();
int i;
for(i=0;i<ar.length;i++)
System.out.println("return values are: " + ar[i]);
}
}
o/p:
return values are: siva
return values are: dallas
I'm curious as to why nobody has come up with the more elegant callback solution. So instead of using a return type you use a handler passed into the method as an argument. The example below has the two contrasting approaches. I know which of the two is more elegant to me. :-)
public class DiceExample {
public interface Pair<T1, T2> {
T1 getLeft();
T2 getRight();
}
private Pair<Integer, Integer> rollDiceWithReturnType() {
double dice1 = (Math.random() * 6);
double dice2 = (Math.random() * 6);
return new Pair<Integer, Integer>() {
#Override
public Integer getLeft() {
return (int) Math.ceil(dice1);
}
#Override
public Integer getRight() {
return (int) Math.ceil(dice2);
}
};
}
#FunctionalInterface
public interface ResultHandler {
void handleDice(int ceil, int ceil2);
}
private void rollDiceWithResultHandler(ResultHandler resultHandler) {
double dice1 = (Math.random() * 6);
double dice2 = (Math.random() * 6);
resultHandler.handleDice((int) Math.ceil(dice1), (int) Math.ceil(dice2));
}
public static void main(String[] args) {
DiceExample object = new DiceExample();
Pair<Integer, Integer> result = object.rollDiceWithReturnType();
System.out.println("Dice 1: " + result.getLeft());
System.out.println("Dice 2: " + result.getRight());
object.rollDiceWithResultHandler((dice1, dice2) -> {
System.out.println("Dice 1: " + dice1);
System.out.println("Dice 2: " + dice2);
});
}
}
You don't need to create your own class to return two different values. Just use a HashMap like this:
private HashMap<Toy, GameLevel> getToyAndLevelOfSpatial(Spatial spatial)
{
Toy toyWithSpatial = firstValue;
GameLevel levelToyFound = secondValue;
HashMap<Toy,GameLevel> hm=new HashMap<>();
hm.put(toyWithSpatial, levelToyFound);
return hm;
}
private void findStuff()
{
HashMap<Toy, GameLevel> hm = getToyAndLevelOfSpatial(spatial);
Toy firstValue = hm.keySet().iterator().next();
GameLevel secondValue = hm.get(firstValue);
}
You even have the benefit of type safety.
Return an Array Of Objects
private static Object[] f ()
{
double x =1.0;
int y= 2 ;
return new Object[]{Double.valueOf(x),Integer.valueOf(y)};
}
In my opinion the best is to create a new class which constructor is the function you need, e.g.:
public class pairReturn{
//name your parameters:
public int sth1;
public double sth2;
public pairReturn(int param){
//place the code of your function, e.g.:
sth1=param*5;
sth2=param*10;
}
}
Then simply use the constructor as you would use the function:
pairReturn pR = new pairReturn(15);
and you can use pR.sth1, pR.sth2 as "2 results of the function"
You also can send in mutable objects as parameters, if you use methods to modify them then they will be modified when you return from the function. It won't work on stuff like Float, since it is immutable.
public class HelloWorld{
public static void main(String []args){
HelloWorld world = new HelloWorld();
world.run();
}
private class Dog
{
private String name;
public void setName(String s)
{
name = s;
}
public String getName() { return name;}
public Dog(String name)
{
setName(name);
}
}
public void run()
{
Dog newDog = new Dog("John");
nameThatDog(newDog);
System.out.println(newDog.getName());
}
public void nameThatDog(Dog dog)
{
dog.setName("Rutger");
}
}
The result is:
Rutger
You can create a record (available since Java 14) to return the values with type safety, naming and brevity.
public record MyResult(int number1, int number2) {
}
public static MyResult something() {
int number1 = 1;
int number2 = 2;
return new MyResult(number1, number2);
}
public static void main(String[] args) {
MyResult result = something();
System.out.println(result.number1() + result.number2());
}
First, it would be better if Java had tuples for returning multiple values.
Second, code the simplest possible Pair class, or use an array.
But, if you do need to return a pair, consider what concept it represents (starting with its field names, then class name) - and whether it plays a larger role than you thought, and if it would help your overall design to have an explicit abstraction for it. Maybe it's a code hint...
Please Note: I'm not dogmatically saying it will help, but just to look, to see if it does... or if it does not.

Implementing Static Methods In A Class

From a book I'm going through:
"Design a class name MyInteger. The class contains:
...blah, blah, blah...
The methods isEven(), isOdd(), and isPrime() that return true if the value in this object is even, odd, or prime, respectively.
The static methods isEven(int), isOdd(int), and isPrime(int) that return true if the specified value is even, odd, or prime, respectively.
The static methods isEven(MyInteger), isOdd(MyInteger), isPrime(MyInteger), that return true if the specified value is even, odd, or prime, respectively."
Here's what I've got so far. The top is easy to implement with object.isEven()...
The second, I assume this is just to display results without actually setting the value and changing the object? So I could just do object.isEven(2)?
The last one... that's throwing me off a lot. I have no idea. =/ Please help me out. Thanks in advance.
To clarify:
1.
public boolean isEven(){
// code
}
MyInteger object = new MyIntger(50);
object.isEven();
2.
public boolean isEven(int num){
// code
}
MyInteger.isEven(50)???
3.
public boolean isEven(int MyInteger)???
???
class MyInteger {
int number;
// CONSTRUCTOR
public MyInteger(int a) {
number = a;
}
public int getNumber() {
return number;
}
static boolean isEven(MyInteger myint) {
if (myint.getNumber() % 2 == 0)
return true;
else
return false;
}
}
Now the main class:
public class MainClass {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MyInteger myInteger=new MyInteger(10);
boolean result=MyInteger.isEven(myInteger);
if(result==true)
System.out.println("true result");
else
System.out.println("false result");
}
}
This seems to be the one that's confusing
boolean odd2 = MyInteger.isOdd(new MyInteger(5)); // static call
You use use an instance of MyInteger to pass as an argument. Another way to pass MyInteger as an argument is:
MyInteger num = new MyInteger(5);
boolean odd2 = MyInteger.isOdd(num); // static call
class MyInteger{
int num;
public MyIntger(int num){
this.num = num;
}
// Method 1
public static boolean isOdd(int num){
...
}
// Method 2
public boolean isOdd(){
...
}
// Method 3
public static boolean isOdd(MyInteger num){
...
}
}
public class TestMyInteger{
public static void main(String[] args){
// Method 1 call
boolean odd1 = MyIntger.isOdd(5); // static call
// Method 3 call
boolean odd2 = MyInteger.isOdd(new MyInteger(5)); // static call
// Method 2 call
MyIntger num = new MyIntger(5); // create instance
boolean odd3 = num.isOdd(); // instance call
System.out.println(odd1);
System.out.println(odd2);
System.out.println(odd3);
}
}
For second one, the method is belong to the class. But not the created object.
If Your code like this :
MyInteger myInteger = new MyInteger(100);
You can call the method by this
MyInteger.isEven(50);
or
myInteger.isEven(50);
It is not related to 100 which set in object.
Consider this as a pointer, and then you might want to look at this question.
public class MyInteger {
private int value;
public MyInteger(int value) {
super();
this.value = value;
}
public static boolean isPrime(int value) {
// I would increment counter then test if the result of value modulo counter
// (that is if value % counter != 0) until counter >= square_root(value).
// Then the value is prime, otherwise
return false;
}
public static boolean isEven(int value) {
return (value & 1) == 0;
}
public static boolean isEven(MyInteger m) {
return isEven(m.value);
}
public static boolean isPrime(MyInteger m) {
return isPrime(m.value);
}
public static boolean isOdd(int value) {
return !isEven(value);
}
public static boolean isOdd(MyInteger m) {
return isOdd(m.value);
}
public boolean isEven() {
return isEven(this.value);
}
public boolean isOdd() {
return isOdd(this.value);
}
public boolean isPrime() {
return isPrime(value);
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
You would be performing actions upon the MyInteger object rather than just a straight int.
Let's say your private variables and constructor look like this (we don't know exactly because it isn't posted):
private int myInt;
public MyInteger(int thisInt) {
myInt = thisInt;
}
You will need to implement an accessor method that returns the value of myInt within an instance of the MyInteger class and then use this accessor method in your static method to perform the operation.
So as an accessor method:
public int getInt()
{
return myInt;
}
And then your static method would reference this method in the same way you would in another program. Note that you have to specify the use of the MyInteger object even within the class:
public static boolean isEven(MyInteger myInteger)
{
//Code here
}
In terms of calling the static method, it would look something like this:
MyInteger myInteger = new MyInteger(50);
MyInteger.isEven(myInteger);
Here, you are referencing an instance of the MyInteger object (myInteger) rather than the primitive int, but because isEven isn't directly connected to a specific object, you have to tell your code where to find the isEven() method, the MyInteger class.

Communication between 2 Classes

I'm a newbie java programer and I'm trying to make my first project.
I need to pass a variable between 2 classes, which is going fine. The problem is that the variable has a changing value and i cannot pass the actual value. Here is an example:
public class A{
private int counter = 0;
public int getCounter(){
return counter;
}
//here some code which will increase or decrease the value of the counter variable
//lets say for the sake of the example that at this point the value of the variable is 1.
//counter = 1;
}
public class B{
public static void main(String[] args) {
A a = new A();
System.out.println(a.getCounter());// here I need the actual counter variable value which is currently: 1
}
}
My problem is that i always receive 0. How can i pass the actual value of the variable.
Any help or advice is greatly appreciated.
A a = new A();
After instantiation (above statement) you need to call the method which will increment the counter here.
Example:
a.incrementCounter();
Then below statement will get counter value.
System.out.println(a.getCounter());
lets say for the sake of the example that at this point the value of the variable is 1.
No, by the time that code is read, the value did not change. All you do inside a class-block is to define a class, the “template” for an object. At that time, no values are set though.
The a.getCounter() you use already does the correct job: It returns the current value of a’s counter variable. If it does not return 1, then obviously the value hasn’t changed yet.
public class A {
private int counter = 0;
public int getCounter() {
return counter;
}
public void increaseCounter() {
counter++;
}
}
public class B {
public static void main() {
A a = new A();
System.out.println(a.getCounter());
a.increaseCounter();
System.out.println(a.getCounter());
}
}
Make variable static so that it will be associated with class.
public class A{
private static int counter = 0;
public int getCounter(){
counter++;
return counter;
}
public static void main(String[] args) {
A a = new A();
a.setCounter(5);
System.out.println(a.getCounter());
}
public class A{
private int counter = 0;
public int getCounter(){
return counter;
}
public void setCounter(int count ){
this.counter=count;
}
}
Use constructors/setter...
public class A{
private int counter = 0;
public A(int c){
counter = c
}
public int getCounter(){
return counter;
}
public void setCounter(int c){
counter = c;
}
public void incCounter(){
counter++;
}
}
public class B{
public static void main(String[] args) {
A a = new A(123);
System.out.println(a.getCounter());
a.setCounter(456);
System.out.println(a.getCounter());
a.incCounter();
System.out.println(a.getCounter());
}
}
class A {
private int counter = 0;
public int getCounter() {
return counter;
}
public int increment() {//////////create increment Method which will increase the counter , or do any function you want
return counter++;
}
public void setCounter(int c) {///////////this method will allow you to set the counter
counter=c;
}
}
class B {
public static void main(String[] args) {
A a = new A();
a.increment();///////if you call this function will change your counter , if not , you will get it = 0
System.out.println(a.getCounter());
}
}
A a = new A();
System.out.println(a.getCounter());
The Output = 0
A a = new A();
a.increment();
System.out.println(a.getCounter());
The Output =1
a = new A();
a.setCounter(10);//////////here you set the `counter` by 10
System.out.println(a.getCounter());
The Output =10;
You have one class (Counter) which manages the counter int variable.
You would like for one or more other classes to be able to increment and/or get the counter value.
In that case, each instance of those classes should have a reference to the same instance of Counter (stored as member variable, passed to their constructor or a setter method).
class Counter {
private int counter = 0;
public int getValue() { return counter; }
public void increment() { counter++; }
public String toString() { return Integer.toString(counter); }
}
class CounterUser {
private final Counter counter;
public CounterUser(Counter counter) { this.counter = counter; }
public String toString() { return Integer.toString(counter.getValue()); }
}
class Test {
public static void main(String[] args) throws Exception {
Counter counter = new Counter();
CounterUser a = new CounterUser(counter);
CounterUser b = new CounterUser(counter);
System.out.printf("%s %s %s\n", counter, a, b);
counter.increment();
System.out.printf("%s %s %s\n", counter, a, b);
b.increment();
System.out.printf("%s %s %s\n", counter, a, b); }
}
Output:
0 0 0
1 1 1
2 2 2
You can do it from the constructor and/or create method that changes the value.
public class A
{
private int counter = 0;
public A()
{
// value is set first time you create an instance of A. (e.g when you do A a = new A();
counter = 1;
}
public int getCounter()
{
return counter;
}
public void incrementCounter()
{
counter++;
}
}
public class B
{
public static void main(String[] args)
{
A a = new A();
System.out.println(a.getCounter());// Output : 1
a.incrementCounter();
System.out.println(a.getCounter());// Output : 2
a.incrementCounter();
a.incrementCounter();
a.incrementCounter();
System.out.println(a.getCounter());// Output : 5
}
}

Passing dynamic primitive type (int) to a method

In Java, the output of s is 0. I do not understand why and would it be possible to somehow get the correct value of s (1000 here)?
public static void main(String args) {
int s = 0;
List<Integer> list = getList(s);
System.out.println("s = " + s);
}
public static List<Integer> getList(int s) {
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 1000; i++) {
list.add(i); s++;
}
}
In C# there were out descriptors to indicate that the variable is going to change if I'm not mistaken..
I'm not going to get the list.size() in general!
In Java, all method arguments are passed by value, i.e. copy. So, changes to the copy are not visible to the caller.
To address your second question, you can just use list.size() on the caller side.
I see two ways
1) Make 's' as static variable and move it to class level
2) Create class with getter/setter for list and int and return the object for getList call
public static MyWrapperObj getList(int s) {
......
return wrapperObj
}
class MyWrapperObj
{
private List<Integer>;
private countS;
....
//getter/setters.
}
Java doesn't allow for passing parameters by reference - but you could wrap it in an object like this:
class IntHolder {
private int s;
IntHolder(int s){
this.s = s;
}
public void setS(int s){
this.s = s;
}
public int getS(){
return s;
}
public void increment(){
s++;
}
}
class Test{
public static void main(String[] args) {
IntHolder s = new IntHolder(0);
List<Integer> list = getList(s);
System.out.println("s = " + s.getS());
}
public static List<Integer> getList(IntHolder s) {
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 1000; i++) {
list.add(i); s.increment();
}
return list;
}
}
In java, arguments passed to methods are passed by value.. you will need to make s a global or instance variable in order to modify it in other methods. This is just the way java works. e.g.
public class Test{
private int s;
public Test(){
s=0;
increment();
//print now will be 1000.
}
private void increment(){
s = 1000;
}
}

Categories

Resources