I have this code :
public static void main(String[] args){
boolean greeting = true; //or false
if(greeting)
hello();
}
public static void hello(){
System.out.println("Hello")
}
I want to call hello method without using (if,switch) if the value of greeting is set to true
is it possible to re-write this program without using if statement or switch ? if so how?
You can use an enum
enum Greeting {
GREETING(() -> System.out.println("hello")),
NO_GREETING(() -> {});
private final Runnable greeting;
private Greeting(Runnable r) {
greeting = r;
}
public void greet() {
greeting.run();
}
}
and then have
public static void main(String[] args) {
Greeting gr = Greeting.GREETING; // or Greeting.NO_GREETING
// or if you insist on the boolean
// Greeting gr = (greeting) ? Greeting.GREETING : Greeting.NO_GREETING;
gr.greet();
}
That would also be extendable to have things like
CORDIAL_GREETING(() -> System.out.println("hi wow so nice to see you"))
in the enum.
The ternary operator in the comment is of course not really different from an if/else.
checkout this :
public static void main(String[] args)
{
boolean b = true;
Predicate<Boolean> p = s -> {hello();return true;};
boolean notUsefulVariable = b && p.test(true); //will be called
b = false;
notUsefulVariable = b && p.test(true); //will not called
}
public static void hello(){
System.out.println("Hello");
}
or you could use while
b = true;
while(b)
{
hello();
break;
}
Simple answer:
public static void main(String[] args){
boolean greeting = true; //or false
while(greeting) {
hello();
break;
}
}
It may not be very elegant, but that wasn't the question, and it's the simplest solution (at least, that I can think of).
If modification of greet() is allowed, one can do it with very little changes to the original code:
public static void main(String[] args) {
boolean greet = true;
boolean dummy = greet && greet();
}
public static boolean greet() {
System.out.println("Hello");
return true;
}
There are a number of ways to branch into a block of code without an if statement. I'll start with simple, and move to the complex.
You can use a switch statement. It is basically a compound ifstatement, with more conditions.
You can use the ternary operator ?. This replaces the condition with one of two values, and can be used like an if statement.
You can use conditional jumping. Basically you store the body of the block of code for each result of the condition as the value in a Map, with the key being the value of the evaluated condition. Then you evaluate the condition, and run the code. For example
myMap.get(age > 3).execute();
Where myMap is a Map with
Map(true) = block of code to `execute()` if true.
Map(false) = block of code to `execute()` if false.
There's lots of ways to go about it. These are just some common ones.
--- Edited with example, as Przemysław Moskal asked for one :) ---
I see your confusion about ternary and returning null, but the poster isn't going to print null in either case of their conditional, they are going to print a String.
public class Hello {
private static Map<Boolean, String> response;
public static void main(String[] args) {
// setup the response map
response = new HashMap<>();
response.put(Boolean.TRUE, "Hello");
response.put(Boolean.FALSE, "");
boolean value = true;
System.out.println(response.get(value));
}
}
or another approach
public class Hello {
private static Map<Boolean, Runnable> response;
public static void main(String[] args) {
// setup the response map
response = new HashMap<>();
response.put(Boolean.TRUE, new Runnable() {
public void run() {
System.out.println("Hello");
}
});
response.put(Boolean.FALSE, new Runnable() {
public void run() {
}
})
boolean value = true;
response.get(value).run();
}
}
or anther example
System.out.println((condition) ? "Hello" : "");
However, it is quite possible for a ternary operation to return null.
(condition) ? null : "hi";
is a valid expression, provided that the null or the hi are both valid in the context of where you write that expression.
I think it's only a Compiler trick question.
Based on the question : greeting is set to true or false, not changeable vairable.
If we set : boolean greeting = true;, the Compiler ignores if command and delete it.
public static void main(String[] args){
boolean greeting = true;
// if(greeting) ---ignores with Compiler
hello();
}
However, if we set : boolean greeting = false;, the Compiler ignores all the if command as Dead Code and delete all the if.
public static void main(String[] args){
boolean greeting = false;
// if(greeting) ---ignores with Compiler as Dead Code
// hello(); ---ignores with Compiler as Dead Code
}
Therefor: if greeting set to true: there is no need to if. And if greeting set to false: there is no need to if and hello() method. So there is not any if in the final code to change it to other things.
As my first attempt to answer this question was not well received, I tried to make another one.
After a little discussion under one of the answers to this question, I was looking for a way to use ternary operator (condition ? value1 : value2) to call method whose return value is void and I think it's rather impossible, because value1 and value2 can't be result of calling such method as hello() returns nothing. If there is a need to use ternary operator, I guess this is the only possible way to make use of this operator, with making the least additional operations possible:
public class MyClass {
public static void main(String[] args){
boolean greeting = true; //or false
checkIfGreetingIsTrue(greeting);
}
public static void hello(){
System.out.println("Hello");
}
public static Void checkIfGreetingIsTrue(boolean greeting) {
return greeting ? callHelloInMyBody() : null;
}
public static Void callHelloInMyBody() {
hello();
return null;
}
}
Related
I have code like
public class Functionz {
public static boolean test() {
return true;
}
public static void main(String[] args) {
Function[] funcs = new Function[] {test}; // and others
for (Function func : funcs) {
func();
}
}
}
and my error is: cannot find symbol: test in the line with the function array declaration.
Hope this isn't a stupid question, very new to java, not new to object oriented languages like python and C++.
A Function in Java does takes one parameter as input and one as output.
You might declare parameter's type this way : Function<Integer, String> is a function that transforms an Integer into a String
Your method test() does not take any input value and outputs a boolean so it's a Supplier.
import java.util.function.Supplier;
public class Main {
public static boolean test() {
System.out.println("lorem ipsum");
return true;
}
public static void main(String[] args) {
Supplier[] funcs = new Supplier[] {Main::test}; // and others
for (Supplier func : funcs) {
func.get();
}
}
}
Your code would compile if test requires one (and only one parameter) like
import java.util.function.Function;
public class Main {
public static boolean test(String str) {
System.out.println(str);
return true;
}
public static void main(String[] args) {
Function[] funcs = new Function[] {(Object anyObject) -> test(anyObject.toString())}; // and others
for (Function func : funcs) {
func.apply("lorem ipsum");
}
}
}
Here's the list of those types
Please note that Function doesn't type its parameters in construction because you can't create arrays with generic type in Java (you might for specific usecases) => Use a List will help you here
I wonder if there is a way (a gradle script or any script or any other way without an IDE) to remove methods annotated with certain annotations. Example:
class x {
public static void main(String[] args) {
int x = getValue();
System.out.println(x);
}
#RemoveEnabled(id = "getValueMethod1", return = "10")
int getValue() {
return 20;
}
}
Now when I run the script or gradle target, it should remove the getValue() method, and the output code should become:
class x {
public static void main(String[] args) {
int x = 10;
System.out.println(x);
}
}
Is there an existing script or way to achieve this? It might be achievable with grep and String parsing etc., but I'm looking for a cleaner solution which is able to get all methods by an annotation id, and remove them with formatting. I tried searching on Google, Stack Overflow etc., but couldn't find a solution.
I wrote a module to process similiar task.
https://github.com/KnIfER/Metaline
#StripMethods(keys={"ToRemove","AlsoRemove"})
public class YourCLZ{
void ToRemove(){} // will be removed
void AlsoRemove(){} // will be removed
#StripMethods(strip=true)
void AnotherTest(){} // will also be removed
}
in your case
#StripMethods(keys="getValue")
class yourx {
public static void main(String[] args) {
int x = getValue();
System.out.println(x);
}
int getValue() {
return 20;
}
}
will become:
class yourx {
public static void main(String[] args) {
System.out.println(x);
}
}
you will get a compilation error since for now my module simply remove any methods or method body statements that contain the key you specified.
How to create a method that accepts a boolean criteria and a lambda with arguments as a parameter in Java 8?
For Example I have lot of this code.
if(something is true) {
foo("a", "b", 2)
}
if(something else is true) {
bar("hello", 1)
}
Want to create a method that accepts boolean and a lambda so I can factor out all the if checks so I can do something like this?
checkAndCAll(isValid, (a, b, c) -> { if(isValid) foo(a, b, c); })
checkAndCAll(isValid2, (a, b) -> { if(isValid2) bar(a, b, c); })
If there is something even cleaner please suggest
Can be even simpler, the paramaters can passed directly to the lambda:
public static void main(String[] args) {
//how to use
checkAndCAll(true, () -> someMethod("param1,", "param2"));
checkAndCAll(false, () -> anotherMethod("param1", 123));
}
public static void checkAndCAll(boolean b, Runnable action) {
if (b) action.run();
}
public static void someMethod(Object param1, Object param2) {
//some method to execute
}
public static void anotherMethod(String param1, Integer param2) {
//some method to execute
}
But I think it's not very useful. The traditional 'if' requires comparable amount of code and in addition is more readable. In fact it only duplicates Java's 'if' statement semantics.
Don't think the way you want to implement is good at all, but anyway - is this what you asked about?
public static void main(String[] args) {
//how to use
checkAndCAll(true, new Object[]{"param1", "param2"}, p -> someMethod(p));
checkAndCAll(true, new Object[]{"param1", 2 , new AtomicInteger(124)}, p -> anotherMethod(p));
}
public static void checkAndCAll(boolean b, Object[] params, Consumer<Object[]> consumer) {
if (b) consumer.accept(params);
}
public static void someMethod(Object[] args) {
//some method to execute
System.out.println(args);
}
public static void anotherMethod(Object[] args) {
//some method to execute
System.out.println(args);
}
This code is asserting that a created class' method which returns a certain value returns the right number. I have to insert my own code where [???] is currently.
class A { int m() { return 1; } }
public class Exercise {
public static void main(String [] arg) {
A a = [???];
assert a.m() == 2;
}
}
How do I change the return value of the m method of the class A so it returns 2, not 1?
I suppose you need something like this:
A a = new A() {
#Override
int m() {return 2;}
};
I am making a bukkit plugin, and I am using an API called MCStats, to create the graph, you add Plotters like so...
mobs.addPlotter(new Metrics.Plotter("Player") {
#Override
public int getValue() {
return 0;
}
});
But I want to get the values from a HashMap, and idealy something like this...
for(String mob: mobNames) {
mobs.addPlotter(new Metrics.Plotter(mob) {
#Override
public int getValue() {
return Stats.getValue(mob);
}
});
}
But obviously, it can't access the mob variable, if I set it to final, it still wont be able to change in the loop. How can I work around this problem?
You can, in fact, use final in an enhanced for loop:
for(final String mob: mobNames) {
mobs.addPlotter(new Metrics.Plotter(mob) {
#Override
public int getValue() {
return Stats.getValue(mob);
}
});
}
You can use the final keyword for mob and it still be changed in the loop.
Try to run this code below:
public class Test2 {
public static void main(String args[]) {
String[] data = new String[] {"1", "2"};
List<MyClass> test = new ArrayList<MyClass>();
for (final String word: data) {
test.add(new MyClass() {
#Override
public void testMethod() {
System.out.println(word);
}
});
}
for (MyClass myClass: test) {
myClass.testMethod();
}
}
static class MyClass {
public void testMethod() {
}
}
}
The output will be "1" and "2".