Two declared constructors in inner class

I have a public class with a private class inside it:

public class A {

   private class B
   {
   }

   private final B b = new B();

   public static void main(String[] args) {
       Class<?> bClass = A.class.getDeclaredClasses()[0];
       Constructor<?>[] declaredConstructors = bClass.getDeclaredConstructors();
       System.out.println(declaredConstructors.length);  //result = 2
   }
}

The problem is, that the declared constructors in class B equals two.

Although in other cases, the number of constructors in class B equals one:

public class A {

   private class B
   {
       public B()
       {
       }
   }

   private final B b = new B();

   public static void main(String[] args) {
       Class<?> bClass = A.class.getDeclaredClasses()[0];
       Constructor<?>[] declaredConstructors = bClass.getDeclaredConstructors();
       System.out.println(declaredConstructors.length);  //result = 1
   }
}

and

public class A {

   private class B
   {
   }

   public static void main(String[] args) {
       Class<?> bClass = A.class.getDeclaredClasses()[0];
       Constructor<?>[] declaredConstructors = bClass.getDeclaredConstructors();
       System.out.println(declaredConstructors.length);  //result = 1
   }
}

The question is why in the first case 2 constructors?
Thanks!

Solution:

As already shortly mentioned by chrylis what you are seeing here is a synthetic constructor.

Basically, whenever you access private attributes of a nested class from the nesting class the compiler needs to create a synthetic method for this access.

In your first example the default constructor is private so when you call it a synthetic method is created (thus “2” constructors exist).

In your second example the constructor is declared as public and no such issue exists.

In your third example once again it is private but also never accessed so there is no need to create a synthetic method.

If you are interested in more detail, read into Chapter 13.1.7 of the Java Language Specification (https://docs.oracle.com/javase/specs/jls/se7/html/jls-13.html) where it is explained a bit further.

Also if you are interested in the implications of synthetic method this post might be interesting to you, discussing the implications of them in regards to security (and performance): What's the penalty for Synthetic methods?

Also, if you want to read more into the inner workings of this concept, I can recommend the following article: https://www.javaworld.com/article/2073578/java-s-synthetic-methods.html (which (to my knowledge) should still be up to date)

Stack overflow error in return statement

Getting a stack overflow error when i submit to canvas but it runs fine in Visual Studio Code, anyone know what the issue is?

Here is the error:

Exception in thread "main" java.lang.StackOverflowError
    at Phi.gcd(Phi.java:14

Here is the assignment:

Euler’s totient function, otherwise known as φ(n), measures the number
of positive integers relatively prime to n that are less than n. Two
numbers are relatively prime if their gcd is 1. For example: φ(9) = 6
because 1, 2, 4, 5, 7, and 8 are relatively prime to 9. More
information about Euler’s totient function can be found at this Wiki
page.

n Relatively Prime    φ(n)
2 1   1
3 1,2 2
4 1,3 2
5 1,2,3,4 4
6 1,5 2
7 1,2,3,4,5,6 6
8 1,3,5,7 4
9 1,2,4,5,7,8 6
10    1,3,7,9 4

Write a function int phi(int n) that takes an integer n as an input
and returns φ(n), and a main() that prompts a user for an integer i,
calls the function φ(i), and prints the result. The upper limit for
the input i is 250000.

The closed form formula for computing φ(n) is: where p1, p2, …, pm
are prime numbers that divide the number n.

The output of your program should look and function like the examples
shown below.

Enter a positive integer n: 8
Phi(n): 4

And here is my code:

import java.util.Scanner;

public class Phi {

    static int gcd(int a, int b)
    {
        if (a == 0 || b == 0)
            return 0;

        if (a == b)
            return a;

        if (a > b)
            return gcd(a-b, b);
        return gcd(a, b-a);
    }

    static int phi(int n) {
        int count=0;
        for(int i = 1; i < n; ++i) {
            if(gcd(n, i) == 1) {
                count++;
            }
        }
        return count;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter a positive integer n: ");;
        int n = in.nextInt();
        System.out.printf("Phi(%d): %d\n", n, phi(n));
    }

}

Solution:

This is because your recursive GCD method converges to the value of GCD very slowly. For example, if you pass 250000 and 1, your method would use 250000 stack frames, more than most JVMs would allocate for you.

One solution is to rewrite Euclid’s GCD algorithm with iterations. Another solution is to use a faster algorithm:

int gcd(int a, int b) {
    return (b != 0) ? gcd(b, a % b) : a;
}

What type of token is exactly "var" in Java 10 and why is it not a reserved word?

In the last issue of Heinz Kabutz’s newsletter, #255 Java 10: Inferred Local Variables, it is shown that var is not a reserved word in Java 10, because you can also use var as an identifier:

public class Java10 {
    var var = 42; // <-- this works
}

However, you cannot use i.e. assert as an identifier, as in var assert = 2, because assert is a reserved word.

As it’s told in the linked newsletter, the fact that var is not a reserved word is good news, because this allows code from previous versions of Java that uses var as an identifier to compile without problems in Java 10.

So, what’s var then? It’s neither an explicit type nor a reserved word of the language, so it’s allowed to be an identifier, however it does have a special meaning when used to declare a local variable in Java 10. How do we exactly call it in the context of a local variable declaration?

Besides, apart from supporting backwards compatibility (by allowing older code that contains var as an identifier to compile), what other advantages does it have for var not to be a reserved word?

Solution:

According to JEP-286: Local-Variable Type Inference, var is

not a keyword; instead it is a reserved type name or a context-sensitive keyword.

Because it’s not a “reserved keyword”, it is possible to still use it in variable names (and package names), but not in class or interface names.

I would think the biggest reason for not making var a reserved keyword is backwards compatibility with old source code.

Different implementations of compare method for Long, Integer and Short?

Why are the implementations of the static method compare for Long, Integer and Short in Java’s library different?

For Long:

public static int compare(long x, long y) {
    return (x < y) ? -1 : ((x == y) ? 0 : 1);
}

For Integer:

public static int compare(int x, int y) {
    return (x < y) ? -1 : ((x == y) ? 0 : 1);
}

For Short:

public static int compare(short x, short y) {
    return x - y;
}

Solution:

If you try:

System.out.println(Long.MIN_VALUE - Long.MAX_VALUE);

or

System.out.println(Integer.MIN_VALUE - Integer.MAX_VALUE);

You will get 1 because of overflow(update: should be underflow here, as mentioned in another answer), which is incorrect.

However, with

System.out.println(Short.MIN_VALUE - Short.MAX_VALUE);

you will get correct value -65535, because short will be converted to int before - operation, which prevents the overflow.

Can I text wrap a Java method name on multiple lines?

I know your first reaction will be “why on earth would you do this, your method names are clearly ridiculous” but it’s because I’m using Spring Boot JPA where you can use the method name to construct the query for you by reflection (it’s amazing). But when querying based on a few different columns and the entity variables have longish names the method name ends up being quite long and hard to read, so I was wondering if there is a way of splitting it across multiple lines?

At the moment I have something like (simplified for this question):

public List<Employee> findByFirstNameAndLastNameAndAgeBetweenAndBirthdayBefore(String firstName, String lastName, Integer minAge, Integer maxAge, Date maxBirthday);

And I would like it in my code to be more like:

    public List<Employee> findBy
                         FirstName
                         AndLastName
                         AndAgeBetween
                         AndBirthdayBefore
                         (String firstName, String lastName, Integer minAge, Integer maxAge, Date maxBirthday);

Is this at all possible?

Solution:

Well, that is an invalid method declaration, Java doesn’t allow you to extend method name to next line but even if it does it is still not a good practice.

I guess you trying to do this because of long method names, and even Spring Data JPA documentation suggests that if your method names are growing large you consider writing the query by using @Query annotation or use Query DSL.

How to get the Year of a Temporal in Java

My problem is to find a useful method from the Temporal interface. In specific, I want to have the year from an Object, which is implementing the Temporal interface. All methods of the interface just add or sub from the objects, however, I just want to get the year of the Temporal itself.

Solution:

The Temporal interface inherits the TemporalAccessor::get method, so for example you can do this:

Temporal t = LocalDate.now();
System.out.println(t.get(ChronoField.YEAR));

Output:

2018

EDIT

As @Ole V.V. pointed out is good to validate if the Temporal implementation supports the desired field using Temporal::isSupported:

if(t.isSupported(ChronoField.YEAR)){
   // ...
}

This will prevent getting exceptions if the Temporal implementation doesn’t support the desired field. For example, Instant is a Temporal implementation that doesn’t support the Year.

Java / Kotlin equivalent of Swift [String : [String : Any]]

What is the equivalent of [String : [String : Any]] from Swift in Kotlin or Java language?

I need to retrieve from database a structure that looks like this:

Key:
    Key : Value
    Key : Value
    Key : Value
Key :
    Key : Value
    Key : Value
    Key : Value

Solution:

It can be represented by a Map<String, Map<String, Any>>. The Kotlin code for creating such a type:

val map: Map<String, Map<String, Any>> = mapOf(
    "Key1" to mapOf("KeyA" to "Value", "KeyB" to "Value"),
    "Key2" to mapOf("KeyC" to "Value", "KeyD" to "Value")
)

In Java, as of JDK 9, it can be expressed like this:

Map<String, Map<String, Object>> map = Map.of(
    "Key1", Map.of("KeyA", "Value", "KeyB", "Value"),
    "Key2", Map.of("KeyC", "Value", "KeyD", "Value")
);

Note that Any from the Kotlin snippet became Object in Java.

Should I convert an Integer to an int?

I have read threads where the convertion of an Integer to an int is a must,BUT I encountered this thing. My code was :

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

String numberOne = "12";

String numberTwo = "45";

Integer myint1 = Integer.valueOf(numberOne);

Integer myint2 = Integer.valueOf(numberTwo);

int sum = myint1.intValue() + myint2.intValue(); //line6

System.out.print(sum);

It gave me a warning of unnecessary unboxing at line6 and recommended me this instead:

int sum = myint1 + myint2; //newline6

Both prints gave me the same result. Isn’t it a must to convert Integer to int at line 6?

Solution:

The compiler will do the same unboxing automatically for you (since JDK 5), so

int sum = myint1.intValue() + myint2.intValue();

is a bit redundant and

int sum = myint1 + myint2;

will have the same behavior.

That said, you can parse the Strings directly into ints, and avoid both the boxing and the unboxing:

int myint1 = Integer.parseInt(numberOne);
int myint2 = Integer.parseInt(numberTwo);
int sum = myint1 + myint2;

how to change the colour of a cardview when selected?clicked

im trying out card view instead of a button i love the amount of info you can add to them. but im trying to make it so if they press the card it changes colour. i want it to change back once they release. so that it works in a similar way to my buttons.

i can get it so that it changes on click but it stay like that untill the activity is destroyed,

this is the code i use for changing the colour at the moment.

public void setSingleEvent(GridLayout maingrid) {
    for (int i = 0; i < maingrid.getChildCount(); i++) {
        final CardView cardView = (CardView) maingrid.getChildAt(i);
        final int finalI = i;
        cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(mcontext, "Button: " + finalI, Toast.LENGTH_SHORT).show();
                cardView.setCardBackgroundColor(mcontext.getResources().getColor(R.color.buttonPressed));
                if (finalI == 0) {
                    mcontext.startActivity(new Intent(mcontext, Genre_Streaming.class));
                }
            }
        });

Solution:

You can try using OnTouchListener with ACTION_DOWN and ACTION_UP to handle Press/Release events instead of OnClickListener.

Modified Code:

public void setSingleEvent(GridLayout maingrid) {
    for (int i = 0; i < maingrid.getChildCount(); i++) {
        final CardView cardView = (CardView) maingrid.getChildAt(i);
        final int finalI = i;

        cardView.setOnTouchListener(new OnTouchListener () {
          public boolean onTouch(View view, MotionEvent event) {
            if (event.getAction() == android.view.MotionEvent.ACTION_DOWN) {
              Toast.makeText(mcontext, "Button: " + finalI, Toast.LENGTH_SHORT).show();
              cardView.setCardBackgroundColor(mcontext.getResources().getColor(R.color.buttonPressed));
              if (finalI == 0) {
                  mcontext.startActivity(new Intent(mcontext, Genre_Streaming.class));
              }
            } else if (event.getAction() == android.view.MotionEvent.ACTION_UP) {
              /* Reset Color */
              cardView.setCardBackgroundColor(mcontext.getResources().getColor(R.color.red));
            }
            return true;
          }
        }
}

Link: http://developer.android.com/reference/android/view/MotionEvent.html#ACTION_UP

How to join a list elements by ',' using streams with ' as prefix and suffix too

I have an insert statement like below

private final COLUMNS = "NAME,TYPE,STATUS,CATEGORY";

String values = list
    .stream()
    .collect(Collectors.joining(","));

String insertStatement = String.format("INSERT INTO ifc.documents (%s) VALUES (%s) ",COLUMNS,values); 

I can easily put COLUMNS as no quotes required but for values, my SQL fails and complain about missing quotes for the code above.

So, I tried

 String values = list.stream()
.collect(Collectors.joining("','"));

But it fails with this one as well.So I did a workaround and added another statement prefixing and suffixing a single quote and it started working.

 values = "'"+values+"'";

To be more specific, if i have say “rest”, “test” and “best” in list

then expected output is

'rest','test','best'

Anyone knows a better solution for this?

Solution:

You can actually use Collectors.joining(CharSequence delimiter,CharSequence prefix,CharSequence suffix) and you can look here for the API.

String values = list.stream().collect(Collectors.joining("','", "'", "'"));