Meaning of `x+" "+y` and `changeUs(x, y)` - java

I've got this code and i have got the answer for it as well, but I don't understand how they come out like that, specifically what does (x+" "+y) part means as well as the changeUs(x, y), can anyone explain?
public class ChangeParam {
public static void main(String[] args) {
int x = 1;
double y = 3.4;
System.out.println(x+" "+y);
changeUs(x, y);
System.out.println(x+" "+y);
}
public static void changeUs(int x, double y) {
x = 0;
y = 0.0;
System.out.println(x +" "+y);
}
}
The answers are:
1 3.4
0 0.0
1 3.4

This is logic, because Java pass by value and not by reference.
When you call changeUs(x, y) the the x and y will change only in the method, for that you get this result.
public static void main(String[] args) {
int x = 1;
double y = 3.4;
System.out.println(x+" "+y);//<<-------- 1- This will print 1 3.4
changeUs(x, y);
System.out.println(x+" "+y);//<<-------- 3- This will print 1 3.4
}
public static void changeUs(int x, double y) {
x = 0;
y = 0.0;
System.out.println(x +" "+y);//<<-------- 2- This will print 0 0.0
}

You should read and study the Tutorial and the Java Language Specification. The semantics of operators such as + are among the first things explained. There you'll find that when either operand of + is of type String that the other operand is converted to a String via an implicit call to String.valueOf, making the whole expression a String concatenation.

System.out.println() - here, println is a method which takes in a String type as argument (either a String, or a type which has been converted to a String).
So , we pass a String. But, you've two things to display (x and y), how will you do that?
In java, '+' operator acts as a concatenation operator when operands are String type, so x+" "+y will combine 'x' and 'y' with a space in between.
So, if x="HELLO" and y="WORLD" , so x+y will be HELLOWORLD.
Giving a space in between, x+" "+y will give us a cleaner and more readable answer: HELLO WORLD
where as
changeUS()
is a method (specifically a static method) which takes in two parameters (much like a math function which needs two parameters).
So, we pass two "things" to the function. Now, how do I know the function needs two parameters? To know that I must know where the function is defined. As I see, the function is defined as:
public static void changeUs(int x, double y) {
x = 0;
y = 0.0;
System.out.println(x +" "+y);}
The first line: enter code here:public static void changeUs(int x, double y)which says that changeUs takesint and double` as their parameters.
So, pass an integer and a floating point number (double is a higher precision floating point number) .
But, why did we do System.out.println but for changeUs we just called it without any of that prefixes?
This is because changeUs is a 'static' method and doesn't need an object to operate upon.

Related

How to calculate area with two variable using a function?

i m solving this question in order to calculate area with answer of double and int.it didnt work, whats wrong with code?
i try to include double radius and int radius inside, it showed cannot be applied to given types.
public static void main(String args[]){
for (int radius = 0; radius < 5 ; radius++)
PrintArea(radius);
for (double radius = 0; radius < 2.6 ; radius+= 0.5)
PrintArea(radius);
}
public static void PrintArea(int radius,double radius){
double area=3.142*radius*radius;
System.out.println(area);
}
i expect it could be calculated and shows answer in double ,but it shows error.
One thing, you should not use the same name for two parameters of a function.
So PrintArea(int radius, double radius) is incorrect and is probably one of the errors you're getting.
The other one, is that you are calling PrintArea with only one parameter, when it expects two.
Rename your parameters int r1 and double r2 instead, like so:
public static void PrintArea(int r1,double r2){
double area=3.142*radius*radius;
System.out.println(area);
}
Or use a PrintArea with only one parameter, of type double:
public static void PrintArea(double radius){
double area=3.142*radius*radius;
System.out.println(area);
}
There are certain issues with your code, your printArea function accepts two arguments, but you are sending only
one while calling the function. Your printArea function needs only one parameter radius (no need of two parameters). The other issue is
that within your printArea function, the data type of parameter is of type int. So when you call this
function with different parameter other than int, it will throw error, as you are calling the function printArea with parameters of type double in your second for loop.
There's a few things going on that can be cleaned up. First of all, why does the PrintArea function need 2 parameters? You call it with only one, and just thinking generally, we don't need two pieces of information to get the area of a circle. So I'm going to guess that you meant only one parameter.
public static void PrintArea(double radius){
double area=3.142*radius*radius;
System.out.println(area);
}
Which will work for both int and double types. Usually we also use camelCase in Java, which means that for methods like "PrintArea" which is made up of multiple words, the first word starts with a lowercase letter, and every other word after that starts with an uppercase letter.

In old C, what does this mean? double (*Window)(double)

I am trying to convert some old DSP code written in C into Java and later to C#. I do not understand what the argument "double (*Window)(double)" means and how to reference it in the Java code. The following function has me unsure what to do.
void WinFirI(float LowOmega, float UppOmega,
float *Shape, int Len, double (*Window)(double), float shift)
{ int i; double time,phase,shape;
// printf("WinFirI: %5.3f %5.3f %d\n",LowOmega,UppOmega,Len);
for(i=0; i<Len; i++)
{ time=i+(1.0-shift)-(float)Len/2; phase=2*M_PI*time/Len;
if(time==0) shape=UppOmega-LowOmega;
else shape=(sin(UppOmega*time)-sin(LowOmega*time))/time;
// printf("%2d %5.1f %5.2f %7.4f %7.4f\n",i,time,phase,shape,(*Window) (phase));
Shape[i]=shape*(*Window)(phase)/M_PI; }
}
So far I have written this:
public void WinFirI(float LowOmega, float UppOmega,
float[] Shape, int Len, double[] Window, float shift) {
double time;
double phase;
double shape;
// printf("WinFirI: %5.3f %5.3f %d\n",LowOmega,UppOmega,Len);
for(int i=0; i<Len; i++) {
time = i +(1.0-shift) - (float)Len/2;
phase = 2 * Math.PI * time / Len;
if(time==0) {
shape = UppOmega - LowOmega;
}
else {
shape=(Math.sin(UppOmega*time) - Math.sin(LowOmega*time)) / time;
}
// printf("%2d %5.1f %5.2f %7.4f %7.4f\n",i,time,phase,shape, (*Window)(phase));
//Shape[i]=shape*(*Window)(phase)/M_PI;
Shape[i] = shape * Window[phase]/Math.PI;
}
}
Pointer to function with parameter double returning double.
As an added note, implementing this function pointer behavior in Java would be done through an anonymous class/interface.
double Window(double param);
In Java would be:
interface WindowFnWrapper {
double Window(double param);
}
Then the function signature would be:
public void WinFirI(float LowOmega, float UppOmega,
float[] Shape, int Len, WindowFnWrapper WindowWrapper, float shift)
Every time you call Window() you would replace it with WindowWrapper.Window().
The declaration double (*Window)(double) declares a parameter Window, whose value is a pointer to a function. That function must be one which takes a single double as an argument, and returns a double.
In your C code, (well, actually the commented-out part), that pointer gets dereferenced, and the function called, passing phase as its argument. That is, the value of the expression (*Window) (phase) is just the result of calling the function whose address you passed in.
If you're using Java 8 or above, the nearest available equivalent is the Function generic class, from the java.util.function package. So if you write
import java.util.function.Function;
then you can declare the parameter as
Function<Double,Double> window
and use it as
window.apply(phase);
The only real difference between this and your C code is that the type parameters to Java generics can't be primitive types such as double.
Double is a reference type that works a bit like double, except that a Double can be null, whereas a double can't. In effect, this should make no difference to your code, except that you may want to add some error handling to deal with the case where window.apply(phase) evaluates to null.

Is this an effective while loop?

Here is an assignment:
"Let's say you are given a number, a, and you want to find its
square root. One way to do that is to start with a very rough guess about
the answer, x0, and then improve the guess using the following formula
x1 = (x0 + a/x0)/2
For example, if we want to find the square root of 9, and we start with x0 = 6,
then x1 = (6 + 9/6)/2 = 15/4 = 3.75, which is closer.
We can repeat the procedure, using x1 to calculate x2, and so on. In this
case, x2 = 3.075 and x3 = 3.00091. So that is converging very quickly on the
right answer(which is 3).
Write a method called squareRoot that takes a double as a parameter and
that returns an approximation of the square root of the parameter, using this
technique. You may not use Math.sqrt.
As your initial guess, you should use a/2. Your method should iterate until
it gets two consecutive estimates that differ by less than 0.0001; in other
words, until the absolute value is less than 0.0001. You can use
Math.abs to calculate the absolute value."
This is exercise meant to practice while loop. As you see I did the assignment, I think it works ? But I am not sure how did I come to solution ? In other words, what should I improve here ? Is there any other way to enter the loop differently ? How to name variables more appropriately ? And lastly, is my approach good or bad here ?
public class squareRoot {
public static void main(String args[]){
System.out.println(squareRoot(192.0));
}
public static double squareRoot(double a){
double gs = a/2; //guess
double ig = (gs + (a/gs))/2; //improving guess
double ig1 = (ig + (a/ig))/2; //one more improving guess, ig1
while (Math.abs((ig-ig1)) > 0.0001){ //with ig and ig1, I am entering the loop
ig = (ig1 + (a/ig1))/2;
ig1 = (ig + (a/ig))/2; //ig1 has to be less then ig
}
return ig1;
}
}
Your approach is nearly correct.
Let's talk about variables first. IMO, you should use full names for variables instead of acronyms. Use guess instead of gs. Use improvedGuess instead of ig etc.
Now that's out of the way we can see where your problem lies. For the while loop to finish, two consecutive guesses' difference must be less than 0.0001. However, here you are only comparing the 1st and 2nd guesses, the 3rd and 4th guesses, the 5th and 6th guesses etc. What if the 4th and 5th guesses' difference is less than 0.0001? Your loop won't stop. Instead, it returns the value of the 6th guess. Although it is more accurate, it does not fulfill the requirement.
Here's what I've come up with
public static double squareRoot(double a){
double guess = a/2;
double improvedGuess = (guess + (a/guess))/2;
while (Math.abs((guess - improvedGuess)) > 0.0001){
guess = improvedGuess;
improvedGuess = (guess + (a/guess))/2;
}
return improvedGuess;
}
Here is my Solution
private static double squareRoot(double a){
double x0= a/2;
while (true) {
double x1 = (x0 + a / x0) / 2;
if (Math.abs(x1 - x0) < 0.0001) {
break;
}
x0=x1;
}
return x0;
}

Division by zero in Java with "IsInfinite" and "POSITIVE_INFINITY" or "NEGATIVE_INFINITY"

I'm a completely noob in java and I have to make this:
Write a program that asks for the introduction of the dividend and the divisor (both real numbers) and show the result of the division in the output. If the result is infinite, the screen must show the text “The result is infinite”. Use the IsInfinite method for the corresponding wrapper class (or the comparison with the constants POSITIVE_INFINITY and NEGATIVE_INFINITY for the corresponding wrapper class).
The main problem is that I don't know how to use the IsInfinite method or the constants method (others methods worked). I have been searching on internet but I didn't find a solution.
Can you help me please?
EDIT: I did this but I don't know if it is what EXACTLY I have to do.
import java.util.Scanner;
public class Exercise {
public static void main(String[] args) {
Scanner key=new Scanner(System.in);
System.out.println("Dividend:");
double dividend=key.nextDouble();
System.out.println("Divisor:");
double divisor=key.nextDouble();
double x = dividend/divisor;
if (x == Double.POSITIVE_INFINITY | x == Double.NEGATIVE_INFINITY) {
System.out.println("The result is infinite");
} else {
System.out.println("The quotient is: " + dividend/divisor);
}
}
}
The code you have given worked for me.
However, you might want to change these lines:
double x = dividend/divisor;
if (x == Double.POSITIVE_INFINITY | x == Double.NEGATIVE_INFINITY) {
to this:
Double x = dividend / divisor;
if (x.isInfinite()) {
Notice the capital D in Double. This is the wrapper class of the primitive double. This class contains the isInfinite method.

Casting from Java primitive int to double

If I call
methodName(5, 1/2);
and it has the signature
public static int methodName(int x, double y){
}
does the methodName receive y with a value of 0 or 0.5?
int y = 1/2;
At this point, y is 0. If you try to cast it to a double afterwards it will be 0.0. It doesn't remember how it got its value, just what its value is.
EDIT: I think the compiler will actually replace 1/2 with 0 at compile time. Making the code literally identical to int y = 0
int y = 1/2;
In this code, y will be 0;
If you want to get it as 0.5
Have a try with the following code:
double y = 1.0 * 1 /2; //y is 0.5
It will evaluate to 0.
There's not a whole lot you can do with the above code.
There should be no specific reason to store y as an int.
Try this instead:
double y = 1/2.0;
int y = 1/2
Since you're using 1 (int) and 2 (int) to make the division, it's an integer division, thus y = 0 (and remainder (%) is 1).
I think you are confused with parameters (the parenthesis). In java every method has a set of parameters (they might not hold values ex: exampleMethod()).
A parameter is a variable that is passed into the method, so when in your code you call:
methodName() initialize it with methodName(x,y);
the x and y inside the method are just pointers for the values you pass through the parameters. I would suggest that you name your variables differently to avoid this confusion. For example:
int x;
int y;
methodName(int argX, double argY)
{
}
Also to answer your question, an int cuts off its stored value at the decimal point, so 5.9 would round to 5 rather than 6, so if you needed a floating point variable for y, either declare it as a float or a double, either will work, but most methods in the java library are written to take doubles as parameters rather than floats

Categories

Resources