Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 2 of 2

Thread: Need help

  1. #1
    Junior Member
    Join Date
    Jul 2024
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Need help

    I've been studying for my OCP certification and I've come across something I don't understand.
    Note: the code below is non-sense and not meant to do anything real but rather to illustrate the behavior that I'm curious about. I would never write production code like this but I can't help but be puzzled as to why it works this way.

    The following code compiles w/o issue

     char end = 'z';
     String s = "";
     Predicate<Character> predicate = c -> {
       char start = 'a';
       return start <= c && c <= end;
     };
     char c = 'Z';
     char start = 'B';

    if I move the final two lines of that block above the predicate definition it doesn't compile and it instead complains that I'm attempting to redeclare c & start inside my predicate.

     char end = 'z';
     String s = "";
     char c = 'Z';
     char start = 'B';
     Predicate<Character> predicate = c -> {
       char start = 'a';
       return start <= c && c <= end;
     };

    I assume this is something about how Java deals with lambda methods but why does having the declarations for c & start before the predicate cause issues while having them below does not?

  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,088
    Thanks
    65
    Thanked 2,712 Times in 2,662 Posts

    Default Re: Need help

    That problem was discussed here: https://www.coderanch.com/t/782694/j...plain-behavior
    If you don't understand my answer, don't ignore it, ask a question.