Hi i am trying to solve the problem I am facing
public class exam {
public static void main(String[] args) {
test1 a = new test1();
}
int zahl(int x, int y) {
int e;
if(x>y) {
e=x-y;
}else {
e=y-x;
}
if(e==0) {
return 0;
}
int z=0;
int i=1;
while(i<=e) {
z=z+i;
i++;
}
return z;
}
}
what I want to do is to call the zahl method to the test1 class
public class test1{
private exam b;
public void init() {
b = new exam();
}
void test() {
int result = b.zahl(2, 2);
assertEquals(1, result);
}
}
this is what I have tried, but it returns nothing, even though it's supposed to show me error.
You should probably be declaring your functions with the public tag i.e. public void test() if you intend to access them from other functions outside of that package. The usual Class naming convention in Java is with capital first letter, which makes your code more readable for you and others.
For your question, I don't think you are actually invoking the test() method of the test1 class. If you want that method to get called every time, you could place it inside the default Constructor.
This question already has answers here:
How to write a Unit Test?
(5 answers)
Closed 4 years ago.
I have a problem with Mockito. I have two different class. My purpose is test “setChanges” function. this is my first class :
class M {
private String a;
private String b;
private boolean c = false;
public String getA() {
return a;
}
public void setA( String _a ) {
a = _a;
}
public String getC() {
return c;
}
public void setC( final boolean imp ) {
c = imp;
}
}
this is the main class which has “setChanges” function:
class MyMainClass {
private String getMyA() {
return "Data";
}
private static void setChanges(final M m) {
if (getMyA().equals(m.getA())){
m.setC(true);
}
}
}
How can I test "setChanges"? Which means that if getA() returns "Data", How can I check getC() that should be "true"?
Thanks, It works with this code :
#Test
public void testsetChanges(){
MyMainClass mmc = new MyMainClass ();
M m = new M();
m.setA("Data");
Method method = MyMainClass.class.getDeclaredMethod(
"setChanges",
M.class
);
method.setAccessible(true);
method.invoke(method, m );
assertTrue(m.getC());
}
Pass in an instance of M which satisfies (or doesn't satisfy) getMyA and validate that M#getC returns true (or false, depending on what you're testing). No mocks required.
This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 6 years ago.
In Java, is it possible for a calling method to get the value of a local variable inside the called method without returning it?
See below in C, where I can use pointers to change the value of the local variable of the fun function.
#include <stdio.h>
int main(void) {
int* a;
a = malloc(sizeof(int));
*a = 10;
printf("before calling, value == %d\n",*a);
fun(a);
printf("after calling, value == %d",*a);
return 0;
}
int fun(int* myInt)
{
*myInt = 100;
}
Can I do something similar in Java. I did try, but wasn't able to.
public class InMemory {
public static void main(String[] args) {
int a = 10;
System.out.println("before calling ..."+a);
fun(a);
System.out.println("after calling ..."+a);
}
static void fun(int newa)
{
newa = 100;
}
}
int and Integer are not mutable. You could pass in a reference to a collection and modify the contents of it, or use a mutable implementation of an integer such as AtomicInteger if you're that keen on it.
public class InMemory {
public static void main(String[] args) {
AtomicInteger a = new AtomicInteger(10);
System.out.println("before calling ..." + a);
fun(a);
System.out.println("after calling ..." + a);
}
static void fun(AtomicInteger newa) {
newa.set(100);
}
}
You can use method as setter for your global variable to get the local variable of that function.
public class InMemory {
static int g=10; // global in class
public static void main(String[] args) {
System.out.println("before calling ..."+g);
fun();
System.out.println("after calling ..."+g);
}
static void fun()
{
int l = 100; // local in fun
g = l; // assign value to global
}
}
public interface MyFunc<T> {
boolean func(T v1, T v2);
}
public class HighTemp {
private int hTemp;
HighTemp(){
}
public HighTemp(int ht) {
this.hTemp = ht;
}
boolean sameTemp(HighTemp ht2){
return hTemp == ht2.hTemp;
}
boolean lessThanTemp(HighTemp ht2){
return hTemp < ht2.hTemp;
}
}
class InstMethWithObjRef {
static <T> int counter(T[] vals, MyFunc<T> f, T v){
int count = 0;
for (int i = 0; i < vals.length; i++) {
if(f.func(vals[i], v)) count++;
}
return count;
}
public static void main(String[] args) {
int count;
//Create an array of HighTemp objects.
HighTemp[] weekDayHighs = {new HighTemp(89), new HighTemp(82),
new HighTemp(90), new HighTemp(89),
new HighTemp(89), new HighTemp(91),
new HighTemp(84), new HighTemp(83)};
count = counter(weekDayHighs, HighTemp::lessThanTemp,new HighTemp(89));
System.out.println(count);
}
}
Please explain how
boolean sameTemp() is compatible with func() in Functional interface.
sameTemp() method got implemented on func() in Functional Interface.
count = counter(weekDayHighs, HighTemp::sameTemp, new HighTemp(89)); is working
Please Explain All points separately.
Equivalent lambda expression of HighTemp::lessThanTemp is
(highTemp1, highTemp2) -> {
return highTemp1.lessThanTemp(highTemp2);
}
This is one of the features of Java8 named Reference to an Instance Method of an Arbitrary Object of a Particular Type
Consider following example,
interface FIface<T> {
int testMethod(T a, T b);
}
class Test2 {
private String str;
Test2(String str) {
this.str = str;
}
int ok(Test2 test2) {
System.out.println("Currnet String : "+ this.str);//Refer to t1
System.out.println("Test String : "+test2.str);//Refer to t2
return 0;
}
}
public class Test {
public static <T> int checkCall(T t1, T t2, FIface<T> fiFace) {
//Here Test2 :: ok is equivalent to t1.ok(t2)
return fiFace.testMethod(t1, t2);
}
public static void main(String[] args) {
checkCall(new Test2("a"), new Test2("b"), Test2 :: ok);
}
}
OUTPUT
Currnet String : a
Test String : b
Note here that Test2 :: ok is valid for the call even ok method is not static.
When you call the method checkCall for the functional interface you still have two arguments which are t1 and t2 and for that valid lambda expression can have parameters as (Test t1, Test t2) so your method Test2 :: ok here becomes valid for the call. Internally it works this way t1.ok(t2).
So, fiFace.testMethod(t1, t2); will will invoke method as t1.ok(t2)
For starters I'm not a professional programmer. I too had a great difficulty in understanding the so called "Reference to an Instance Method of an Arbitrary Object of a Particular Type" I think this might be helpful for somebody who comes here from a google search.
I understood it a little bit with the help of lambda expressions.
In your code HighTemp::lessThanTemp as a Lambda expression would look like (x,y)->{x.lessThanTemp(y);} Replacing the method reference with this lambda expression would produce the same result. The above Lambda expression or the method reference both tell the interface method what to do.
When you use the method reference it tells the interface method to use the referred method from the given class, to carryout its function. Therefore if you convert HighTemp::lessThanTemp to English words it would sound something like "implement the lessThanTemp method form the class HighTemp as the implementation of the interface function". As you might've noticed in that case the return types and the argument types should be compatible. Otherwise you cannot implement an interface.
I would provide you another simple example code. More examples helps to understand this concept.
interface myint{
int returnit(Test t ,int y);
}
class Test{
int x=0;
public Test(int x){
this.x=x;
}
public int addNumbers(int y){
return x+y;
}
public int subtractNumbers(int y){
return x-y;
}
}
public class myclass{
private static void myMethod(Test t,myint inf,int y){
int x=inf.returnit(t, y);
System.out.println(x+"");
}
public static void main(String[] args){
myMethod(new Test(4),Test::addNumbers,7);
myMethod(new Test(4),Test::subtractNumbers,7);
}
}
Output would be:
11
-3
This is the simplest way I could imagine it. See how return types and argument types gets matched using the above sentence pattern. Spend some time on it.
This is the Interface
package learninglambdaexp;
#FunctionalInterface
public interface TempInterface {
public boolean validTemp(Temperature temp);
}
This is the class
package learninglambdaexp;
public class Temperature {
private int temp;
public Temperature(int temp) {
this.temp = temp;
}
public boolean isEvenTemp() {
return temp % 2 == 0;
}
public boolean isOddTemp(){
return !isEvenTemp();
}
}
This is the Class with the Main Method
package learninglambdaexp;
import java.util.ArrayList;
import java.util.List;
public class AnotherMainClass {
public static void main(String[] args) {
List<Temperature> tempCollection = new ArrayList<>();
tempCollection.add(new Temperature(100));
tempCollection.add(new Temperature(20));
tempCollection.add(new Temperature(30));
tempCollection.add(new Temperature(40));
tempCollection.add(new Temperature(50));
tempCollection.add(new Temperature(60));
tempCollection.add(new Temperature(70));
int k1 = countVariation(tempCollection, Temperature::isEvenTemp);
//int k2 = countVariation(Temperature::lowTemp);
System.out.println(k1);
// System.out.println(k2);
}
private static int countVariation(List<Temperature> tempCollection, TempInterface ti) {
int count = 0;
for (Temperature eachTemp : tempCollection) {
if (ti.validTemp(eachTemp)) { // (eachTemp) -> {return eachTemp.isEvenTemp();};
count++;
}
}
return count;
}
}
With one argument its easier to understand
Please, correct me if I am wrong, but the way I think about this type of method references (Reference to an Instance Method of an Arbitrary Object of a Particular Type) is that when we pass a method reference, in this case to the counter method, the instance of anonymous class which implements MyFunc interface is created. Then, inside this anonymous class, we override func method which is passed two parameters. And then inside the func method, lessThanTemp method is called like this:
v1.lessThanTemp(v2);
So for me this concept looks something like this:
public class Demo {
public static void main(String[] args) {
AnonymousClass an = new AnonymousClass();
System.out.println(an.apply(new SomeClass(3), 4));
}
}
interface SomeInterface {
int apply(SomeClass obj, int n);
}
class SomeClass {
private int n;
SomeClass(int n) {
this.n = n;
}
int add(int n) {
return this.n + n;
}
}
class AnonymousClass implements SomeInterface {
#Override
public int apply(SomeClass o, int n) {
return o.add(n);
}
}
Could you point me to the JLS section where it is specified that inherited methods will not act on subclasses re-defined variables?
I.e. the output of the following code is "value is 3" and not "value is 5".
public class PlayGround {
int value = 3;
public int getValue() {
return value;
}
public static void main(String[] args) {
PlayGround.PlayGroundSon pg = new PlayGround().new PlayGroundSon();
System.out.println("value is "+pg.getValue());
}
class PlayGroundSon extends PlayGround{
int value = 5;
}
}
You have not "re-defined" value. You have created a completely separate field in PlayGroundSon that happens to have the same name.
You can only override methods. If you want the program to print 5 you will have to override the getValue() method. I have also changed the name of the variable in PlayGroundSon to emphasize that it is not the same as value in PlayGround.
public class PlayGround {
int value = 3;
public int getValue() {
return value;
}
public static void main(String[] args) {
PlayGround.PlayGroundSon pg = new PlayGround().new PlayGroundSon();
System.out.println("value is "+pg.getValue());
}
class PlayGroundSon extends PlayGround{
int sonValue = 5;
#Override
public int getValue() {
return sonValue;
}
}
}