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
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 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
public static void main(String[] args) {
Double ans1 = add(5, 9);
Number ans2 = add(new Integer(3), new Double(2.4));
double ans3 = add(10, 3.2);
System.out.println(answer1 + " " + answer2 + " " + answer3);
}
Given the main method above, how would I create a static method (as opposed a set of overloaded methods) which in turn would could successfully call the methods within the main?
Thanks in advance!
write a single static method (not a set of overloaded methods) which
can be called successfully by all the methods in main.
It is very basic, you can simply do that by creating a new static add() method (a single method contains the code for all calls to different overloaded add methods) as below:
public static void main(String[] args) {
add();
}
public static void add() {
Double ans1 = add(5, 9);
Number ans2 = add(new Integer(3), new Double(2.4));
double ans3 = add(10, 3.2);
System.out.println(answer1 + " " + answer2 + " " + answer3);
}
OK. I think I understand what your teacher wants, despite the wrong terminology he's using. He wants you to write a unique static add() method. And the code should compile and run after this unique add() method is being added to the code.
Since the method is called with arguments that are of type int, Integer, Double and double, the argument types must be a parent class of all these types (after boxing/unboxing). For example Number, or Object.
Since the returned value is assigned to a variable of type Double, Number and double, the return type must be a common class or subclass subclass of all this (after boxing/unboxing).
A candidate would thus be, for example:
private static double add(Object i, Object i1) {
return 0;
}
Of course, the ansX variables need to be renamed to answerX, too, otherwise the code will never compile.
I guess we can also safely assume that add() should add the arguments. I leave that as an exercise for your.
In order for the add method to be called successfully by the main method, you need to figure out what types to use for the return value and the parameters.
Here's a template:
private static ??? add(??? a, ??? b) {
return a + b;
}
As you can see, main calls add with all kinds of arguments, and it stores the result in different types of variables as well.
If you analyze the main method, you will see that the add method must be able to accept the following types of parameters:
(int, int)
(Integer, Double)
(int, double)
It can be deduced that an int, a double, an Integer and a Double can be implicitly converted to the parameters' type. If you do a little bit of thinking, you will know that double is one of the types that satisfy this requirement. This means that the parameters can be of tyoe double!
And it must be able to return a value that's compatible with the following types:
Double
double
Number
It can be deduced that the return type must be able to be implictly converted to Double, double, or Number. double also satisfy this requirement. This means that the method returns a double as well!
Here's the completed method:
private static double add(double a, double b) {
return a + b;
}
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
Im new to Java, is there a method in Java that tells you the type of an Object?
For example in Python if you type
type(34) it would return int
type('abc') would return string
I've been looking everywhere but I can't find a way of doing it. Any help?
Thanks a lot.
The instanceof operator is the handiest way to do runtime type checking:
if (someObject instanceof String) {
// It's a string
}
Alternately, on any instance, you can use getClass, which gives you the Class instance for the type of the object.
Class c = someObject.getClass();
The Class instance will have a getName method you can call to get a string version of the name (and lots of other handy methods).
You can get a Class object from a type name using .class, e.g.:
Class stringClass = String.class;
As Peter Lawrey points out in the comments, all of these assume you're dealing with an object reference, not a primitive. There's no way to do a runtime type check on a primitive, but that's okay, because unlike with object references (where your compile-time declaration may be Object), you always know what your primitive types are because of the declaration. It's only object types where this really comes up.
If you find yourself doing a lot of explicit type checks in your Java code, that can indicate structure/design issues. For the most part, you shouldn't need to check type at runtime. (There are, of course, exceptions.)
Basically we can achieve our goal by using the method overriding
class GetType {
void printType(byte x) {
System.out.println(x + " is an byte");
}
void printType(int x) {
System.out.println(x + " is an int");
}
void printType(float x) {
System.out.println(x + " is an float");
}
void printType(double x) {
System.out.println(x + " is an double");
}
void printType(char x) {
System.out.println(x + " is an char");
}
}
public static void main(String args[]) {
double doubleVar = 1.5;
int intVar = 7;
float floatVar = 1f;
GetType objType = new GetType();
objType.printType(doubleVar);
objType.printType(intVar);
objType.printType(floatVar);
}