This problem is about overloading methods and I think I understand the basic idea but I get some weird error "Overloading.java:14".
Like my problem is that I don't know how to return two parameters of my method. So I thought maybe convert the method with the two int parameters with toString(), then return it. Something gone miserably wrong.
The output have to be following:
a 10
a and b 10, 20
char a
result 97
My problem as it is, is with the "a and b 10, 20", and have not done the "char a" just to make you guys aware. This is not homework.
Here is my code so far contains a main class and a helper class:
OverMain Class :
class OverMain {
public static void main(String args[]) {
Overload overload = new Overload();
int result;
System.out.println("a " + overload.test(10)); //prints a 10
System.out.println("a and b " + overload.test(10, 20)); //the method I have trouble with
result = overload.test('a'); //prints Result 97
System.out.println("Result " + result);
}
}
Overload Class:
//The class which is suppose to overload test methods
class Overload {
public int test(int a) {
return a;
}
public String test(int a, int b) {
String string = "";
string = test(a, b).toString();
return string;
}
}
It's not really clear what you're trying to do, but you don't return parameters, and I don't think overloading is really the problem here. To take overloading out of the situation, you can always change the methods to have different names - get it working that way, and then you can always change the names back later and work out any conflicts.
In your case I think you just need:
public String test(int a, int b) {
return a + ", " + b;
}
In other words, just use string concatenation and the automatic int to String conversion that the compiler will apply in order to use string concatenation.
Note that if your code actually compiled, you'd get a stack overflow because you're calling test(a, b) from test(int a, int b) - it would just call itself forever, until you ran out of stack space.
The problem is in your method test(int, int)
public String test(int a, int b) {
String string = "";
string = test(a, b).toString(); // Danger
return string;
}
You have a never ending recurrence relation
Solution: return a + ", " + b
Related
I recently started to learn about generics in Java, and I understand the basic concepts of generics. However, one thing I don't understand is that I don't know why the following method doesn't work:
public class Generics<T extends Number> {
T num;
Generics(T n){
num = n;
}
//...
T timesTwo() { //Return the value that's twice as much as 'num'
return num * 2;
}
}
It was my first approach, and I kind of understand why it is not working. The error message said: The operator * is undefined for the argument types(s) T, int.
I guess Java couldn't multiply the T and int type together. (But shouldn't the compiler be able to auto-unbox T since it's involved in an expression AND the class extends Number?)
So I gave up on this method and tried to replace it with this method:
T times(T i) { //This method was supposed to receive another T object as
//an argument and multiply them together, then return the output
return num * i;
}
But once again, the exact same error message appeared (the only change was that int was replaced by T).
Why is the code not working, and how can I fix it?
I agree with the first two comments. Also, it's not a generics problem, it's just that the method doesn't work because it's not supposed to work because the boxing assumption you concluded doesn't apply here.
Autoboxing and Unboxing are supplied for some of the Number types but not all. See table below: https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html
So while this works the way you expect (because both types are in the supported table):
public static void main(String[] args) {
Integer a = 3;
Integer b = 2;
Number answer = a * b;
System.out.println("Answer: " + answer);
}
This intuitively equivalent code will NOT work:
public static void main(String[] args) {
Number a = 3;
Number b = 2;
Number answer = a * b;
System.out.println("Answer: " + answer);
}
In fact, from the Compiler's perspective, it gives you the same cross-eyed look you would get if you tried this:
public static void main(String[] args) {
String a = "what does it even mean to multiply a string with a number..??";
Byte b = 2;
Number answer = a * b;
System.out.println("Answer: " + answer);
}
So to finish the point, from the compiler's perspective, since auto-boxing does not apply, it's just as confused as to how to multiply two Numbers as it is how to multiply two other random objects like a String and a Byte and reports the error accordingly
I have a constructor whose parameters are both int: Berries( int a, int b ) and I need to put a double in the place of "a" in the code: Berries( 23.45, 6). I tried with cast, but it does not work.
Can you help me please ?
the ugly solution
new Berries((new Double(23.45)).intValue(),6)
I am not sure why would you ever need that?
Either change the constructor to accept double, or send an integer value as an argument
Typecasting can be used to change the compile-time type of an expression. For example, a value of type double can be cast into a value of type integer. This is achieved by putting the desired type in parenthesis as in 'new Berries((int)23.45, 6)'. A working example of typecasting the arguments of a constructor is shown below.
public class Berries {
Berries(int a, int b) {
System.out.println("a = " + a + " b = " + b);
}
public static void main(String[] args ) {
Berries b = new Berries((int)23.45, 6);
}
}
The output of running this is:
$ java Berries
a = 23 b = 6
I'm taking those first steps from python to java and here is my first of many Java questions do doubt.
When printing via a shortened print method, I'm running into a problem with the return value from a inherited class. I'm sure it's something simple about Java I don't get yet. I'm also trying to convert any integers the println method receives to a string with .tostring(), but I'm not sure if that is correct.
class Inheritance {
private static void println (Object line){
System.out.println(line.toString());
}
static class A {
public int multiply(int a, int b){
int val = a*b;
return val;
}
}
static class B extends A {
public int multiply(int a, int b) {
int val = a * b * 5;
return val;
}
}
public static void main(String[] args) {
B b_class = new B();
b_class.multiply(3,4);
println(b_class);
println("Hello World");
}
}
The output is as follows:
Inheritance$B#74a14482
Hello World
You can just use the method inside println
public static void main(String[] args) {
B b_class = new B();
println(Integer.ToString(b_class.multiply(3,4)));
println("Hello World");
}
For Java toString method default it will
returns a string consisting of the name of the class of which the object is an instance, the at-sign character `#', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '#' + Integer.toHexString(hashCode())
https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#toString()
so when you println b_class it will print: Inheritance$B#74a14482.
For your println (Object line) it's receiving Reference type(Object) to println, but as multiply method it's return a primitive type(int), it's not an object, you need to convert it to an Object for println method, as #StanteyS's answer, use Integer.toString can convert int to String.
What's the difference between primitive and reference types?
When you are executing println(b_class); implicitly it calls toString method of same class, which is inherited from Object class.
You need to override toString method to display correct output.
static class B extends A {
int val=0;
public int multiply(int a, int b) {
val = a * b * 5;
return val;
}
public String toString(){
return String.valueOf(val);
}
}
Now, println(b_class); will work as per your expectation.
I was trying to print a string and int on a same line. But I get an error. I know my way around this error but why does the line System.out.println("This is a string: %i", c2.a);gives error whereas the line System.out.println("This is class method" + c2.a ); gives the correct output. Below is my code.
public class MyClass
{
private int a;
public double b;
public MyClass(int first, double second)
{
this.a = first;
this.b = second;
}
// new method
public static void incrementBoth(MyClass c1) {
c1.a = c1.a + 1;
c1.b = c1.b + 1.0;
}
//pass by valuye therefore no change
public static void incrementA(int a)
{
a = a+1;
}
public static void main(String[] args)
{
MyClass c1 = new MyClass(10, 20.5);
MyClass c2 = new MyClass(10, 31.5);
// different code below
incrementBoth(c2);
incrementA(c1.a);
System.out.println("This is a object passing: %i",c2.a);
System.out.println("This is object passing: " + c2.a );
System.out.println("This is pass by value: %d",c1.a);
}
}
My other question is does the line incrementBoth(c2) changes value of c2 because here whole object is passed to the method rather than passing by value in incrementA(c1.a)
You need to use the printf method and not println.
println is used to print primitive types, Strings and objects as they are. Also, println takes only one argument as input. That is the reason you are getting an error when you pass multiple arguments to it in your code.
printf on the other hand is used to format and then print the formatted string to the Standard output / error. This is what you should use in your code above for formatting the output.
Here's a reference to the tutorials.
Hope this helps!
Try:
int x = 3;
System.out.println("This is my number" + x);
The output should be:
This is my number 3
I'm playing around with lambdas in eclipse oxygen. I have code something like this
#FunctionalInterface
interface TriFinction<O,I,J, R> {
R whatEver(O object, I input1, J input2);
}
class Dummy {
public String dothingsWithTwoArgs(String a, String b) {
return a+b;
}
}
public class LambdaTest {
public static void main(String[] args) {
Dummy::dothingsWithTwoArgs;
}
}
I'm unable to extract Dummy::dothingsWithTwoArgs. Eclipse is showing a compilation error Syntax error, insert "AssignmentOperator Expression" to complete Expression, but extraction is working perfectly in intellij. Is there any workaround for this in eclipse?
First notice that your dothingsWithTwoArgs is not static, therefore you should not attempt to invoke it in a static fashion: you should use an instance of your Dummy class or make the dothingsWithTwoArgs static
Here are some illustrations that will get you going
First you need a method that has your TriFinction as one of its parameters
Example:
public static String sumToString(String a,String b, String c, TriFinction<String,String,String,String> f) {
return f.whatEver(a, b, c);
}
Second, in your Dummy class you need a method that matches the genric signature of your TriFinction (which means for example that it receives three parameters for O,J, and I and that it returns a R)
for example
public static String dothingsWithThreeArgs(String a, String b,String c) {
return a+ " " + b + " " + c;
}
Now you can use the method reference in your main method for example:
System.out.println(sumToString("2","3","4",Dummy::dothingsWithThreeArgs));
Here is the full example along with a second illustration from your TriFinction (and I guess you should refactor and rename it TriFunction :) )
public class ExtractWithLambda {
#FunctionalInterface
interface TriFinction<O,I,J, R> {
R whatEver(O object, I input1, J input2);
}
public static String writeEqu(TriFinction<Double,Double,Double,String> f) {
return f.whatEver(2.5, 3.4, 5.6);
}
public static String sumToString(String a,String b, String c, TriFinction<String,String,String,String> f) {
return f.whatEver(a, b, c);
}
public static void main(String[] args) {
System.out.println(writeEqu(Dummy::writeEquation));
System.out.println(sumToString("2","3","4",Dummy::dothingsWithThreeArgs));
}
}
class Dummy {
public static String dothingsWithThreeArgs(String a, String b,String c) {
return a+ " " + b + " " + c;
}
public static String writeEquation(double a, double b, double c) {
return a + "*x*x " + b + "*x " + c ;
}
}
One main thing we should know is Compilation error messages are compiler dependent. This does not mean different compilers would produce different error messages all the time. But there can be situations.
Regarding your problem I found this answer and post. That post has a detailed explanation about this error under topic not a statement.
So the main point is this. As you mentioned, this error message is specific to Eclipse compiler. The point the compiler is raising is your line is just an expression, not a statement. In order to understand it as a statement, the compiler wants you to add an assignment operator. That's the whole meaning of insert "AssignmentOperator Expression" to complete Expression. So what you all want to do is just assign that line to another defined variable, which would look like this.
someVariable = Dummy::dothingsWithTwoArgs;
Hope you can find more depth and more examples with the sources I mentioned. :))
Extracting Lambda to a method seems only suported from Eclipse 4.23 (Feb. 2022, 6 years later)
Extract lambda body to method
A new content assist has been added to extract the body of a lambda to a method.
To invoke the new feature, perform a Ctrl + 1 within the selected lambda body: