This question already has answers here:
Any risk using a single dollar sign `$` as a java class name?
(5 answers)
Closed 9 years ago.
Is it possible to use functions in Java? I'm not used to OOP and I like having global functions that can be used in any classes. Is this possible in Java? Right now, I have a class named $ that contains all my functions (as static methods). Is there a Java convention for using classes like this? (I borrowed the $ from JQuery)
You can write static class methods with no state, which is effectively a pure function. You can do a "static import" so you don't have to reference the enclosing class. However all your methods/functions must be defined in a class. So, yes, you can do those things, but the syntax isn't perfect.
Java encapsulates everything in classes. You must have all functions within a class. You can either have one big class with many functions and program your Java program more or less like you are writing C or have static functions/class method.
For instance you can have a class Gloabls where you put all your functions:
class Globals {
public static int AddNumbers(int a, int b) { return a+b; }
}
class MyClass {
public MyClass { int four = Globals.AddNumbers(1,3); }
public static void main(String[] args) { new MyClass(); }
}
Related
This question already has answers here:
Non-class functions in Java
(4 answers)
Closed 2 years ago.
When declaring methods in Java, do they need to be a part of a class? I am familiar with the idea of a Utility Class:
"Utility Class, also known as Helper class, is a class, which contains just static methods, it is stateless and cannot be instantiated. It contains a bunch of related methods, so they can be reused across the application."
However, can one just create a method separate from any class altogether? (I'd assume scope becomes public by default and declaring anything else for scope might result in an error).
If this is not possible, perhaps that would explain the need for Utility Classes, but I wasn't sure as I hadn't thought about this before - I assumed naturally you could make functions separate from any specific class, but I had been looking through various code samples and couldn't find a specific example where this was occurring.
Part of the reason I am asking this is I was reviewing this article (and mentioned in point 2):
https://www.geeksforgeeks.org/lambda-expressions-java-8/
In it, it states: Lambda expressions are added in Java 8 and provide below functionalities.
1) Enable to treat functionality as a method argument, or code as data.
2) A function that can be created without belonging to any class.
3) A lambda expression can be passed around as if it was an object and executed on demand.
Java is a sort of purely class-based programming language. So, Yes, it and everything needs to be a part of a class.
You are right, you can make a Utility class making methods public static in this way methods can be called without instantiating the class.
Answer to question in the comment:
Why would someone write Object.method() instead of just method()?
Object class is a standard class in java.lang package. You should not create your class named Object otherwise you will need to specify java.lang.Object everywhere you use java.lang.Object.
Now you probably meant
Why would someone write MyUtilClass.method() instead of just method()?
Suppose you have a class MyUtilClass as follows
public class MyUtilClass {
public static int utilMethodA() {
return 1;
}
public static boolean utilMethodB() {
int value = utilMethodA();
if(value == 1)
return true;
else
return false;
}
}
And suppose you have another class MyClass as
public class MyClass {
public void classMethod() {
int value = MyUtilClass.utilMethodA();
}
}
Here if you see in MyUtilClass, utilMethodB() uses utilMethodA() without writing MyUtilClass.utilMethodA() (however, we could write it that way also). Here we did not need to write it as MyUtilClass.utilMethodA() because compiler can find the utilMethodA() without fully specifying it's class because it is present inside it's own class.
Now, In Myclass's myMethod(), we must specify MyUtilClass.utilMethodA() (without it, it won't work), because the compiler has no way of figuring out that you meant to call utilMethodA() of MyUtilClass. There could be hundreds of classes with a method named utilMethodA(), the compiler has no way of finding out which one of the hundred methods you want to call.
Note:-
Also, you can do static import of MyUtilClass.myMethod() like
import static my.package.name.MyUtilClass.myMethodA()
and then use utilMethodA() inside MyClass without prefixing MyUtilClass (but you already informed compile by static import that you will be using utilMethodA() of MyUtilClass right?)
Looks cool to you? No!
This is rather a bad way because
It makes code looks unobvious. In a large class, it may seem that
method utilMethodA() is a local method defined somewhere in
MyClass.
Also, it can generate ambiguity to the compiler if more than one static import of utilMethodA() is done. As compiler has no way of figuring out which of the two you intend to use.
(Edit) Regarding Lambda Expression
Lambda expression is pretty cool stuff added in Java 8. They are basically a kind of function. They provide you the power to define a function right where they need to be used. For example in this link that you provided, see the example shown below syntax of lambda, there the statement
ArrayList<Integer> arrL = new ArrayList<Integer>();
arrL.add(1);
arrL.add(2);
arrL.add(3);
arrL.add(4);
arrL.forEach(n -> { if (n%2 == 0) System.out.println(n); });
Basically, what we are doing here is, we are defining a function, if n is multiple of 2, we print n. We are doing it forEach element of arrL. Did you see, we defined the function to be executed on each element right inside a function call forEach(). That's the beauty of lambda expression.
Now, coming to your question,
So the primary benefit of lambda (besides syntax) is to make it easier to implement functional interfaces (compared to what alternative)?
Yes, sort of. Easy in terms of not creating a separate class implementing the interface and then implementing the abstract method and then calling that implemented method.
This becomes lots of work, especially if you need to call that method only once for example,
Consider the Functional Interface FuncInterface defined as in the link in your question:
interface FuncInterface {
// An abstract function
void abstractFun(int x);
// A non-abstract (or default) function
default void normalFun() {
System.out.println("Hello");
}
}
Now, you want two kind of implementation to your functional interface:
One that provides twice of the passed int x.
Another one that provides square of passed int x.
So, you make two implementations of it:
First FuncInterfaceTwiceImpl
public class FuncInferFaceTwiceImpl implements FuncInterface {
#Override
public void abstractFun(int x) {
System.out.println(2 * x);
}
}
Second, FuncInterfaceSquareImpl as
public class FuncInterfaceSquareImpl implements FuncInterface {
#Override
public void abstractFun(int x) {
System.out.println(x * x);
}
}
Now, you call them as
public class MyClass {
public static void main(String[] args) {
FuncInterface interfaceTwiceObject = new FuncInferFaceTwiceImpl();
interfaceTwiceObject.abstractFun(5);
FuncInterface interfaceSquareObject = new FuncInterfaceSquareImpl();
interfaceSquareObject.abstractFun(5);
}
}
It prints
10
25
Now, what you had to do?
You had to create two separate Classes (in separate new files or
could have made private classes in the same file that of MyClass),
each implementing the abstract method.
Then you instantiated objects of each class and called them
respectively in the main function.
What if this is the only place where you had to call this twice and square thing? You had to make two classes just to use them only once. This effort is too much!!
What if you want to call it without creating new classes and implementing methods in a class?
What if I tell you only provide me the method body, I will do the work for you without you to bother about implementing interface and overriding methods?
Here comes the Lambda magic. Instead of making any impl classes just
head straight towards the main method
Instantiate two objects of FuncInterface providing only method body in Lambda expression.
Call abstract method from objects just like below
public class MyClass {
public static void main(String[] args) {
FuncInterface interfaceTwiceObject = (n) -> System.out.println(2*n);
interfaceTwiceObject.abstractFun(5);
FuncInterface interfaceSquareObject = (n) -> System.out.println(n*n);
interfaceSquareObject.abstractFun(5);
}
}
And boom, the output is
10
25
Just one more time where Lambda saved your day!!
Yes all methods in Java have to be part of a class. You cannot create a method (static or otherwise) which is not associated with a class.
EDIT
Before I answer your question, I will point out that lambda expressions were introduced in Java 8 through the concept of SAM types. In addition, a bit of syntactic sugar was also introduced to facilitate the creation of these types.
When you hear the term "Lambda expression" in Java, you should always remember that they are expressions. Your confusion stems from thinking that lambda expressions evaluate to a pure function not associated with a class or object; well this is simply not the case in Java and I will show you why.
Lambda expressions are not functions
I can now see where your confusion comes from because that article you are reading made a false claim when they say that lambda expression is:
A function that can be created without belonging to any class.
This is simply not true. A lambda expression in Java is not a function. Take the example they give for instance.
interface FuncInterface
{
// An abstract function
void abstractFun(int x);
// A non-abstract (or default) function
default void normalFun()
{
System.out.println("Hello");
}
}
class Test
{
public static void main(String args[])
{
// lambda expression to implement above
// functional interface. This interface
// by default implements abstractFun()
FuncInterface fobj = (int x)->System.out.println(2*x);
// This calls above lambda expression and prints 10.
fobj.abstractFun(5);
}
}
Proof
Now take the comment they have in the main method:
lambda expression to implement above functional interface
From the start they admit that the next line of code implements a functional interface. However functions in Java do not implement interfaces, only classes or other interfaces can do that!
Now, they even go ahead and "call" this function:
This calls above lambda expression and prints 10.
except instead of directly invoking the function (as anyone would if this was really a function), they use the property accessor notation (.) to access the actual method they wanted to call, which means what we have here is not a function, but actually an instance of an anonymous class.
Furthermore, since this object actually contains another method (normalFun), one might ask the question, which one do I use when I want to pass this "function" to another method? This is not a question that is commonly (if ever) asked in the context of lambda functions because there is only one thing to do with a lambda function and that is to call it.
In closing
Java has lambda expressions, not lambda functions.
What makes it a lambda expression is simply the syntactic sugar introduced in Java 8 that uses the () -> { } notation. Unfortunately, many fans of functional programming began associating the term "Lambda function" with objects created using this syntax, and this has led to the confusion you have expressed in your question.
To rehash what I answered previously, all functions in Java are part of a class, and you cannot have a function which is not associated with an object, nor can you create a function outside a class.
HTH
This question already has answers here:
Calling static method from another java class
(3 answers)
Closed 3 years ago.
I am new to Java and still trying to understand the basics. I can write code within a class and method but really struggling with working across classes. To help I am trying to write a very simple programme that can add or subtract two numbers. This program will have three classes:
Class 1
package christmas;
public class addintegers
{
public static int add2numbers(int a, int b)
{
return (a+b);
}
}
and the second class
package christmas;
public class subtractintegers {
public static int sub2numbers(int a, int b)
{
return (a-b);
}
}
what I now want to do is to write a third class that contains a main method that can read two numbers and an operator (+ or -) from the keyboard and then depending on the operand call the addintegers or subtractintegers classes.
This seems basic and it is not homework, I am simply trying to understand through a basic example how to build more complex code to work across mumtiple classes.
I know how to read from the keyboard, the help I need is how to call the different classes from a main method that is in a class of its own.
Thank you in advance - I am sure this is easy for many but hard for me to understand.
To call the christmas.addintegers.add2numbers method from another class, you just do christmas.addintegers.add2numbers(foo, bar) (where foo and bar are some already initialized integers.)
This question already has answers here:
Why is the Java main method static?
(37 answers)
Closed 8 years ago.
I'm new to programming in Java (even though I'm used to code in C, html and some other languages (vaguely)).
I'm trying to create a simple Hello World program, and I'm unsure of why, and what the "static" tag does. I tried to do some research, and I came up with that the static tag makes the method work as an instance in a moment, instead of having to "launch" it (didn't quite understand it). I'm wondering where, and why to use it.
On the other hand, while I'm compiling, I found out how to make it execute, but some friends of mine have told me that I need to include a manifest, and run it as a .jar, (I'm using:
$ javac Potato.java
$ java Potato
)
As a note, I would like to tell you that I'm trying to avoid using 3rd-party softward to learn programming (using the standard Notepad++ and bash).
Thank you ;)
Edit: Sorry, this was my first question.
class Potato {
static String textA = "Hello There";
public static void main(String[] args){
System.out.println(textA);
}
}
I got this code, and I did some mixing by creating the variable textA inside and outside of the main method.
The static modifier used on a method allows you to call such method on its class instead of a specific instance.
If you want to know why main is always static, have a look here: Why is the Java main method static?
Normal method
Definition:
public Class ExampleClass{
public void exampleMethod(){
System.out.println("exampleMethod()");
}
}
Use:
ExampleClass exampleClassInstance = new ExampleClass();
exampleClassInstance.exampleMethod();
Static method
Definition:
public Class ExampleClass{
public static void exampleMethod(){
System.out.println("exampleMethod()");
}
}
Use:
ExampleClass.exampleMethod();
The same applies to fields. If you have a static field, it will belong to the class and not to single instances.
Example:
public Class ExampleClass{
public static int a = 1;
}
...
System.out.println(ExampleClass.a);
This question already has answers here:
What is the actual memory place for static variables?
(7 answers)
Closed 9 years ago.
Why static variables are directly called without any use of object in java?Are they stored in some different memory location?And why only static methods can called with the name of the class directly without creating its object ?for example
class First
{
public static void ss()
{
System.out.println("This genius will give answer");
}
}
class Second
{
public static void main(String ar[])
{
First.ss();
}
}
Yes static resources belong to the class and not the objects. And are stored in a separate location kind of global location. You can read more here.
As docs says
Every instance of the class shares a class variable, which is in one fixed location in memory.
The Java programming language supports static methods as well as static variables. Static methods, which have the static modifier in their declarations, should be invoked with the class name, without the need for creating an instance of the class, as in
ClassName.methodName(args)
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Why do C# and Java bother with the “new” operator?
Why does java have the new keyword? To create an object of type A, I have to type A a = new A().
Java doesn't have stack allocation, so why couldn't that just be simplified to A a = A()?
Because C++ did it so, I presume. Java was supposed to look superficially like C++, but with a greatly simplified and streamlined language.
In any case, you got a problem there:
class Foo {
private static void A() {
System.out.println("method");
}
public static void main(String[] args) {
A();
}
}
class A {
public A() {
System.out.println("ctor");
}
}
What should happen here? ctor or method?
One obvious drawback to your syntax suggestion is found here:
class A {}
class B extends A {
public A A() { return new B() }
public A foo() { return A(); } //ERK
}
What should the above code in the method foo do? Does it invoke the method named A(), or the constructor of A.
Of course you can now have something like what you want using static imports:
public class A {
public static A A() { return new A(); }
}
This can be brought into scope by import static my.stuff.A.*
That you know you are calling a constructor and not a method.
It is arbitrary. Python constructors work more or less like Java constructors, and are just A(), no new required.
In Java, classes, methods, and variables have different namespaces, which means in any scope you could have one of each with the same name. It'd be ambiguous to say A a = A();, because there could be a method named A(). Sure, Java could look for a method and use a class constructor if it couldn't find a method...but then, it wouldn't be obvious (from looking just at the code) what it does, and the Java people are big on "purity". Plus, if you happened to add a public A A() to your class, that line of code takes on a whole different meaning.
It is arbitrary but one could think of many reasons.
One reason would have to do with the mixing of automatic (stack based) and heap-allocation objects and references for them. You know how in C++ you have to be careful about not taking a pointer to an automatic variable? That's one less headache to worry about.
A second reason is likely that Java is generally designed to have low-cost object allocation and low-cost GC for recent objects (thanks to the use of generational garbage collectors). There is therefore no significant benefit to supporting both types of object allocations.