Long commands in Java - java

I am learning to code in Java
I know what namespaces, classes and methods are
with that knowledge I understand code such as the following
CharSequence v = new BackwardString("whale");
v.toString();
However sometimes you see examples of code which are longer than this
an example being
dictionary.subSet("a","ab").size();
In the ubove example dictionary is a class and subSet() is a method.
However size() is also a method but methods cannot contain other methods, so where does size() come from and why does it work?
Another common example which i have used without giving any thought to until now is
System.out.printLn();
in this case would System be a namespace, out be a class and printLn() be a method?

dictionary.subSet("a","ab").size();
It's a chaining of method calls. dictionary.subSet("a","ab") returns a String object, on which you call the size method.
System.out.println()
System is a class (java.lang.System), out is a static variable of that class whose type is PrintStream, and println is a method of PrintStream.

dictionary.subSet("a","ab").size();
The subSet method returns a String object, you are then calling .size() on this String. It is shorthand for doing the following
String a = dictionary.subSet("a","ab")
int size = a.size();
System.out.println()
System.out returns a PrintStream method, and you are invoking the println() method of that object.

This is called Method Chanining
System.out.printLn();=
System is a class
PrintStream is a class again // ref is out
println() is a function

In this example:
dictionary.subSet("a","ab").size();
method subSet returns an object with method size which gets invoked after subSet returns.
Similar thing happens with another snippet:
System.out.printLn();
Class System contains a static field out which has a method println
This is a common practice in Java programming to pipeline method calls. Sometimes an object can return itself allowing you can call multiple methods in one line.

The . selection is done as follows:
(dictionary.subSet("a","ab")).size();
Set s = dictionary.subSet("a","ab");
s.size();
The method subSet delivers (likely) a Set,
and Set has a method size.
This is called "chaining".
To get a feeling of it:
BigDecimal n = BigDecimal.valueOf("123456780.12");
n = n.multiply(n).add(n).divide(BigDecimal.TWO).subtract(n);
BigDecimal does large numbers with precise fixed point arithmetic.
It cannot use operators, and the above is a normal style.
Selectors (that might be chained:
. member
[ index ]
( function arguments )

Related

How to pass parameter in Supplier function with method reference operator(::)

Sorry, it seems to be very basic in functional programming but I am not getting this idea. Actually I have a method in my code which consumes a method and another param as a parameter.
private <R> CompletableFuture<R> retryRequest(Supplier<CompletableFuture<R>> supplier, int maxRetries)
I want to call this function and pass another method(anOtherMethod) which taking one integer parameter:
CompletableFuture<Boolean> retry = this.retryRequest(this:: anOtherMethod, 2);
Not getting this how I can call this retryRequest and give anOtherMethod(123)?
I know it can work like this:
CompletableFuture<Boolean> retry = this.retryRequest(()-> anOtherMethod(123), 2);
You cannot instantiate a lambda with a specific captured value like 123 in the pure method reference variant.. You need to write the explicit lambda version with arrow, if you want to pass captured values other than the instance to execute the method on. Read more on capturing values in lambdas in this answer: Enhanced 'for' loop and lambda expressions
The only exception is an object, which itself becomes the first parameter.
Assume a signature that expects a Consumer of a String:
public void something(Consumer<String> job) {
...
The above signature will enable you to write the following calls:
String myString = " Hey Jack ";
something(myString::trim);
something(s -> s.trim());
Both do the same, and this is maybe unintuitive, because one takes an argument (the instance reference myString) and one seem not to (but it actually does, too). This works, because the compiler tries two possible resolutions for a lambda method reference (the above version with ::). On one hand, the compiler can apply signatures, as if the called method did not have any parameters, and none need passing. This is the case for myString.trim. But the compiler will also check, whether there is a static method String.trim(myString) (which luckiely there is not). If you wanted to call a static method without any parameters, then you'd have to call the class identifier with the function reference like so:
something(String::trim); // this version of trim does not exist.
This is sometimes even a problem, because if a class offers a static version of a method and an instance-related one, you get ambiguity:
public void somethingElse(Function<Integer, String> transformation) {...}
// This will not compile:
somethingElse(Integer::toString);
The above example will not compile, because the toString method exists twice, once as static Integer.toString(someInt) and once as instance related someInteger.toString().

Is it necessary to store a value from a method which is returning a value in java?

Let suppose I have a method
public int dummy(){
return 1;
}
and if I call this method by
dummy();
not
int a = dummy();
will it make any difference? why?
No, it wouldn't make any difference. We call a ton of methods from the JDK ignoring their outputs - List's .remove(int index) removes the element at a given index, and returns what element was removed. It is normal to ignore it and move ahead.
It will still compile, but (assuming that the method is just called in isolation) it'll be pointless, since you can never use the value returned. (At a deeper level, and depending on implementation, it's possible the JVM may optimise away the method call entirely.)
If however you do int a = dummy();, then you can later reference that variable, eg. System.out.println(a); will print out its value.
If your method had another side effect other than returning a value, such as:
public int dummy(){
System.out.println("hello");
return 1;
}
...then calling it without assigning its result to a variable wouldn't be pointless, since the side effect would still occur (printing "hello" in this case). While some argue this is poor design, this sometimes occurs in practice in the Java libraries - you could call createnewFile() on a File object for instance and ignore its returned boolean value (which will tell you whether the file was created or not.)
These two are both true statements, but the difference is, when you use
dummy()
this will call the function in the program, but since you are returning a value, it is pointless ( considering you will keep the value )
When you use
int a = dummy()
You will create an integer named a in order to store the output ( return value ) of the function, which you can reuse any time.

why need of "println(char[] x)" when there is already "println(Object x)" - java

I was reading about println function and I came across that there is println(char[ ] x) as well as println(Object x)
https://docs.oracle.com/javase/7/docs/api/java/io/PrintStream.html#println(char[])
My question is that: As arrays in java are object so what is the need to specifically overload println() with char[] whereas rest arrays like int[] etc. uses the println(Object x) overloaded function.
println(Object x)
if you use it to print a char array (the char array is an object), it won't print the content but the objectClass#hashcode style. You can test it yourself to see the exact output.
Because they are implemented differently.
println(Object)
will (after checking for null, etc), call the parameter's toString() method and display the result of it.
The toString() method of an array is not useful: it will give you the array type and the hashcode of the array. So the overloaded form gives a more useful implementation in the case of a char[] parameter.
Note that, with most object types, the toString() method can be overridden (so overloading the println(...) method for every possible type is not necessary (or possible...). However, the toString() method cannot be overridden for arrays, so there is benefit to overloading println in this case.
Because it prints the char array as a string and otherwise prints in object form, and seeing the contents may be more convinient. You can try casting it to object first and see the difference.
Because print/ln(char[]) handles the actual printing of characters, toString() of the array object itself still provides the usual type+hash output, regardless of being an array of characters
char c[]={'a','b','c'};
Object o=c;
System.out.println(c);
System.out.println(c.toString());
System.out.println(o); // *
System.out.println(o.toString());
The * thing is interesting (and this is why I post at all, since the rest is already there in other answers) because it demonstrates that Java has single dispatch: the actual method to be invoked is decided in compilation time, based on the declared type of the argument(s). So it does not matter that o is a character array in runtime, in compilation time it seems to be an Object, and thus print/ln(Object) is going to be invoked for it.

Why do we need parameter(s) in a method(if it involves giving parameter), I mean what does a parameter do?

When we say
public static void task(int number)
{
(you can give any example)
}
what is the function of parameter there ? I understand that when we give task.subtring(0,5) here the parameters are telling us the place value of the character. How does it work in "int"..
If you are confused about the general idea of parameters, they are a message you pass to a method. Think of a method or a function for that matter as a labeled block of code the you can execute somewhere else using that label. Now, parameters are a way of giving a different input to that block of code. They are variables that get used inside that block of code and that you can set from outside of it by passing in a different value when you use that label. For example, I can pass an int (integer number) to a method that multiplies it by 2 and returns the result:
int multiplyBy2(int number){
return number*2;}
Now, I can pass different numbers into that method and get different outputs. What could be confusing about that method you've shown is that it doesn't return a value and can't access class fields, so it might seem useless. However, that method can be doing a lot of other stuff with that integer. A few examples: the method can be printing some string to the screen that changes based on the integer, it could be writing to a file, it could be modifying static fields, and many other possible tasks.
In the example you posted you would pass in the value of a single int; maybe to get a single character, maybe to read a specific line from a file; anything that needs that single int. In the example you understand there are two int parameters.
Your question is for the idea of parameters at all, aren't you? Parameters make methods more dynamic. for example you want to add a number to an existing int in an object. you will do it in this way (it is only a part of a class):
int all;
....
public void add(int i){
all += i;
}

Java dynamic function calling

I have a String array that contains names of method in the yyyyyy class
In the xxxxxx class I'm making a yyyyyy instance (say obj). Now I can call obj.function_name(), except I want to read function_name from the String array in a loop. Is this possible?
You can, using reflection. It is done by calling Yyyy.class.getMethod("methodName").invoke(someArgs)
You'd have to handle a bunch of exceptions, and your method must be public. Note that java coding conventions prefer methodName to method_name.
Using reflection, however, should be a last resort. You should be using more object-oriented techniques.
If you constantly need similar features, perhaps you can look at some dynamic language running on the java platform, like Groovy
It's possible using reflection, although you should probably question your design somewhat if you need that sort of behavior. Class.getMethod takes a String for the method name and returns a Method object, which you can then call .invoke on to call the method
These Javadoc pages should be helpful:
Class.getMethod
Method.invoke
Sample code (assuming the yyyyyy methods take one int argument, just to show argument passing):
yyyyyy obj = new yyyyyy();
String[] methodNames = {"foo", "bar", "baz"};
for(String methodName : methodNames) {
Method method = Class.forName("yyyyyy").getMethod(methodName, new Class[] {int.class});
method.invoke(obj, 4); // 4 is the argument to pass to the method
}

Categories

Resources