I was wandering how to make custom classes that can be used through out all of java eclipse. For example if you make any basic program you can call pre determined classes, like you can just type Math.abs(x); instead of having to go out of your way and typing
if (x<0) x = x * -1;
else x = x;
I would like to design my own custom classes for basic functions that I use a lot that i can use I in any program regardless of if they are in the same project or not.
custom classes that can be used through out all of java eclipse...
you can do that with any class as soon as you import that and define the right visibility for its data....
class MyRandom{
public static int MultiplybyTwo(int number){
return number * 2;
}
public static int DividebyTwo(int number){
return number / 2;
}
}
import MyRandom;
class Test{
public static void main(string[] args){
int x = MyRandom.MultiplyByThow(9);
System.out.println("the result is: " + x);
}
}
on the other hand, this makes no sense:
else x=x;
Related
i made a small program for summing two numbers
if i used a void type method it will be like this
import java.util.Scanner;
public class NewClass {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.println("enter x");
int x = input.nextInt();
System.out.println("enter y");
int y = input.nextInt();
getSum(x,y);
}
public static void getSum(int x, int y)
{
int sum = x + y;
System.out.println("sum = " + sum);
} }
here if i used a method that returns a value i will get same output!
import java.util.Scanner;
public class NewClass {
public static void main(String[] args)
{
Scanner input = new Scanner (System.in);
System.out.println("enter x");
int x = input.nextInt();
System.out.println("enter y");
int y = input.nextInt();
int r = getSum(x,y);
System.out.println("sum = " + r);
}
public static int getSum(int x, int y)
{
int sum = x + y;
return sum;
}}
so i'm confused what is the benefit of returning a value if i can finish my program with a void type method?
The point is not to get the result but the way we get the result
consider
public static void getSum(int x, int y)
{
int sum = x + y;
System.out.println("sum = " + sum);
}
will print the output to the screen after calculation
but when we use return
as you have done it later
public static int getSum(int x, int y)
{
int sum = x + y;
return sum;
}
this function will respond back the sum. that sum can be stored in a variable
can be used afterwards
like in recursion
In small programs, you won't get the difference but while writing the big programs you have to make several functions which are being called several times and you may need the output of one function into other.
In that case, you will require return so that the output of one function can be used into other.
Hope this helps!!
I think the answer is that, if you're calling getSum() method with a return type in any other class.. you would get a returned value which can be used for further processing. .
Where as in void that's not possible... Hope this helps... Reply if any doubts..
I can understand why you have this question.
First of all, you should know that in real development, we do not use console logs.
System.out.Println();
This is used only for debugging and that too in very rare cases.
The whole point of a function is to take some input and convert to something else.
So,
public static int getSum(int x, int y) {
return x+y;
}
public static void main(String[] args) {
System.out.Println(getSum(5,10));
}
This is the better solution.
Best Regards,
Rakesh
When you use the keyword void it means that method doesn't return anything at all. If you declare a return type different to void at the method statement instead, that method must return obligatorily a valid value to the declared return type using the keyword return followed by a variable/value to send back to the class that called the method.
Defining methods here you have the java documentation for a method declaration
Answering your question, in small programs that work with primitive values it doesn't really matter but in complex program when you usually need to return specifics object types, i.e an ArrayList or actually an instance of a class you created you can't simply put it into a System.out.println and send it to the console, mostly you'll want to get something from a method and that something usually can be a more complex object than an integer or a string, the way to get that something is through the return type defined by the method's statement.
A common use of return types is when your method is static and it can't interact with the non-static instance variables of the class, this type of static methods usually get values from their arguments, do a certain kind of progress and then return a result that the method's caller can use.
Returning a value enables you to use that value in whichever way you want, including printing it or assigning it to variable for further processing. If on the other hand you print the value in the method and not return anything, i.e. making the method of type void, then that's all you can do with that method.
This question already has answers here:
JAVA cannot make a static reference to non-static field
(4 answers)
Closed 4 years ago.
Ok, so I am revisiting java after many years and I was just trying out some random program when I found out that I was having an error in the following snippet. Can someone give me any heads on how to solve this? I know that static methods will not be able to access non static variables but I created an instance for it right? Also I am not getting any heads on reading some other questions so try to help me.
import java.io.*;
public class phone
{
int x=6;
int getx()//I also tried using this function but everything in vain
{
return x;
}
}
public class Testing_inheritance extends phone
{
public static void main (String args[])throws IOException
{
phone xy=new phone();
int y=phone.x;
y+=10;
System.out.println("The value of x is " +y);
}
}
You probably intended to access the instance variable of the instance you created :
phone xy = new phone();
int y = xy.x;
Since x is not a static variable it can't be accessed without specifying an instance of the phone class.
Of course this will also fail, unless you change the access level of x to public (which is possible but not advisable - you should use getter and setter methods instead of directly manipulating instance variables from outside the class).
x is not static. You need to access it through an object reference.
Do
int y = xy.getx(); //could do xy.x, but better to access through method
Also, it's better to stick with Java naming conventions
Almost there, I made small but very important changes, I hope you get this otherwise just ask ;-)
Phone.java
public class Phone //<--- class with capital letter always
{
int x=6;
int getx()//I also tried using this function but everything in vain
{
return x;
}
}
Testing_inheritance.java
import java.io.*;
public class Testing_inheritance extends Phone
{
public static void main (String args[])throws IOException
{
Phone xy=new Phone();
int y= xy.getx(); //<--- principle of encapsulation
y+=10;
System.out.println("The value of x is " +y);
}
}
OR private inner class :
import java.io.IOException;
public class Phone {
int x = 6;
int getx()// I also tried using this function but everything in vain
{
return x;
}
private static class Testing_inheritance extends Phone {
public static void main(String args[]) throws IOException {
Phone xy = new Phone();
int y = xy.getx();
y += 10;
System.out.println("The value of x is " + y);
}
}
}
So, I have to create 68 different summing methods using the datatypes, int, float, double and short. The class is called, OverloadingSums. Here is an example of one the methods.
public double sum(double x, float y, int z)
{
return x+y+z;
}
Now I'm being asked to create a class called ZeroSum, essentially copying OverloadingSum and returning everything to zero. Here is an example.
public double sum(double x, float y, int z)
{
return 0;
}
Then I'm being asked to create another class called RealSum, which will extend the ZeroSum class. I'm a little confused about the wording of this assignment, not sure if the stackoverflow community could help but I'm just extremly confused.
Here is the assignment requirements:
Now that we have thoroughly explored overloading we are going to
explore overriding. Create a class called ZeroSum.java. Take all of
the methods from OverloadingSum.java and change them to return all
zeros in ZeroSum.java. Next, create a class called RealSum.java. This
class, RealSum, will extend the ZeroSum class. Having all zeros for
our sums isn't very useful. We will need to override the parent, or
super class methods to produce real results. Create the necessary
methods to override all of those in the ZeroSum.java. When you are
done run your classes against DrivingSum.java.
This is what I have in my main method:
public class DrivingSum {
public static void main(String[] args) {
int x = 10;
int y = 20;
// x + y = 30....yay?
ZeroSum zero= new ZeroSum();
RealSum real= new RealSum();
System.out.println("Calling ZeroSum " + zero.sum(x,y) );
System.out.println("Calling ZeroSum " + real.sum(x,y) );
}
}
So, from how I'm understanding this I wrote the following code:
public class ZeroSum extends RealSum{
public double sum(double x, float y, int z)
{
return super.sum(x,y,z);
}
This will grab the method from RealSum, instead of using the sum method located in the ZeroSum class. So when I run the main method, zero.sum(x,y) gives me 30.
The confusion comes from the fact that the assignment asks me to set everything in ZeroSum returning to zero. If I extend ZeroSum to RealSum, it doesn't really make a difference. Am I doing this correctly? or Am I just overthinking this way too much?
The goal of this assignment is to explore overriding concept, where function executed depends on type of object it called upon on run time, so you will have something like this :
public class ZeroSum {
public double sum(double x, float y)
{
return 0;
}
}
public class RealSum extends ZeroSum{
public double sum(double x, float y)
{
return x+y;
}
}
public class DrivingSum {
public static void main(String[] args) {
int x = 10;
int y = 20;
// x + y = 30....yay?
ZeroSum zero= new ZeroSum();
ZeroSum real= new RealSum();
System.out.println("Calling ZeroSum " + zero.sum(x,y) ); //here the sum will return zero
System.out.println("Calling ZeroSum " + real.sum(x,y) ); //here the sum will return 30
}
I believe he's trying to make a point in which whatever you write in the parent class is transferred (this is called inheritage) to the child. You can override this by writing a method in the child class using the same name and arguments as the parent class' method.
I also believe you read the assignment a bit wrong, it said:
This class, RealSum, will extend the ZeroSum class.
I interpret this as RealSum is the child to ZeroSum, not the other way around as such:
public class RealSum extends ZeroSum{
//code code code
}
This means everything in ZeroSum is set to 0 and RealSum set new values, not using the super. I'm not betting my hand this is correct but try to read the assignment again after a break and some fresh air :)
Hope this helps!
I tried to run a simple matlab code in java (I'm new to Java).
In matlab, I created this function :
Function [y] = square[x]
y = sqrt(x)
end
I named the class: square
But when I run the function in Eclipse, I couldn't make it work.
Here is the code in Eclipse:
import square.*;
import com.mathworks.*;
import com.mathworks.toolbox.javabuilder.*;
public class square {
/**
* #param args
*/
public static void main(String[] args) {
square x = new square();
Double z = x.square(8);
}
}
The error is: The method square(int) is undefined for the type square
Any idea? Thanks so much!
You can use the Math.Pow() function in Java to square a number. If you wanted to write your own function, you could do:
class Mymaths
{
public static double Square(double exponent, double number)
{
return Math.pow(number,exponent);
}
}
Then you could use that inside your main method:
public static void main(String[] args)
{
Mymaths.Square(2.0,8.0); //should return 64
}
Sorry if I misunderstood, but that's what I read.
The problem you have is that you do not have defined the method square. That is exactly what the compiler complains about.
Define it like this to return a Double object:
private Double square(int x) {
// do whatever you like here
}
However I think it will be better if you use the primitive double type for simple tests (just be aware for the precision).
Another option is to use one of the methods defined in the Math utility class.
Are there any extensions for the Java programming language that make it possible to create nested functions?
There are many situations where I need to create methods that are only used once in the context of another method or for-loop. I've been unable to accomplish this in Java so far, even though it can be done easily in JavaScript.
For example, this can't be done in standard Java:
for(int i = 1; i < 100; i++){
times(2); // Multiply i by 2 and print i
times(i); // Square i and then print the result
public void times(int num){
i *= num;
System.out.println(i);
}
}
Java 8 introduces lambdas.
java.util.function.BiConsumer<Integer, Integer> times = (i, num) -> {
i *= num;
System.out.println(i);
};
for (int i = 1; i < 100; i++) {
times.accept(i, 2); //multiply i by 2 and print i
times.accept(i, i); //square i and then print the result
}
The () -> syntax works on any interface that defines exactly one method. So you can use it with Runnable but it doesn't work with List.
BiConsumer is one of many functional interfaces provided by java.util.function.
It's worth noting that under the hood, this defines an anonymous class and instantiates it. times is a reference to the instance.
The answer below is talking about the closest you can get to having nested functions in Java before Java 8. It's not necessarily the way I'd handle the same tasks which might be handled with nested functions in JavaScript. Often a private helper method will do just as well - possibly even a private helper type, which you create an instance of within the method, but which is available to all methods.
In Java 8 of course, there are lambda expressions which are a much simpler solution.
The closest you can easily come is with an anonymous inner class. That's as close as Java comes to closures at the moment, although hopefully there'll be more support in Java 8.
Anonymous inner classes have various limitations - they're obviously rather wordy compared with your JavaScript example (or anything using lambdas) and their access to the enclosing environment is limited to final variables.
So to (horribly) pervert your example:
interface Foo {
void bar(int x);
}
public class Test {
public static void main(String[] args) {
// Hack to give us a mutable variable we can
// change from the closure.
final int[] mutableWrapper = { 0 };
Foo times = new Foo() {
#Override public void bar(int num) {
mutableWrapper[0] *= num;
System.out.println(mutableWrapper[0]);
}
};
for (int i = 1; i < 100; i++) {
mutableWrapper[0] = i;
times.bar(2);
i = mutableWrapper[0];
times.bar(i);
i = mutableWrapper[0];
}
}
}
Output:
2
4
10
100
Is that the output you get from the JavaScript code?
I think that the closest you can get to having nested functions in Java 7 is not by using an anonymous inner class (Jon Skeet's answer), but by using the otherwise very rarely used local classes. This way, not even the interface of the nested class is visible outside its intended scope and it's a little less wordy too.
Jon Skeet's example implemented with a local class would look as follows:
public class Test {
public static void main(String[] args) {
// Hack to give us a mutable variable we can
// change from the closure.
final int[] mutableWrapper = { 0 };
class Foo {
public void bar(int num) {
mutableWrapper[0] *= num;
System.out.println(mutableWrapper[0]);
}
};
Foo times = new Foo();
for (int i = 1; i < 100; i++) {
mutableWrapper[0] = i;
times.bar(2);
i = mutableWrapper[0];
times.bar(i);
i = mutableWrapper[0];
}
}
}
Output:
2
4
10
100
Such methods are sometimes called closures. Have a look at Groovy – perhaps you will prefer it to Java. In Java 8 there will probably be closures as well (see JSR335 and deferred list).
For non-argument method you can create Runnable object
private static void methodInsideMethod(){
Runnable runnable = new Runnable(){
#Override
public void run(){
System.out.println("Execute something");
}
};
for(int i = 0; i < 10; i++){
runnable.run();
}
}
Consider making an anonymous local class and using its initializer block to do the work:
public class LocalFunctionExample {
public static void main(final String[] args) {
for (final int i[] = new int[] { 1 }; i[0] < 100; i[0]++) {
new Object() {
{
times(2); //multiply i by 2 and print i
times(i[0]); //square i and then print the result
}
public void times(final int num) {
i[0] *= num;
System.out.println(i[0]);
}
};
}
}
}
Output:
2
4
10
100
(The "final wrapper trick" is not automatically required with this technique, but was needed here to handle the mutation requirement.)
This works out to be almost as concise as the lambda version, but you get to use whatever method signatures you want, they get to have real parameter names, and the methods are called directly by their names - no need to .apply() or whatnot. (This kind of thing sometimes makes IDE tooling work a little better too.)
I don't know if anyone else has figured this out, but apparently you can do magic with the var keyword that comes with Java 10 and above. This saves you from having to declare an interface if you don't have one that will work for you.
public class MyClass {
public static void main(String args[]) {
var magic = new Object(){
public void magic(){
System.out.println("Hello World!");
}
};
magic.magic();
}
}
I have tested it and it works. I haven't found a Java compiler that lets you do a simple share yet.
I hate to use the forbidden word but you could use a goto statement to create an an effective subroutine inside the method. It is ugly and dangerous but much easier than what was shown in previous answers. Although the private method with a call inside of the first method is much better, and serves you needs just fine. I don't know why you would want to use a nested method for something as simple as this.