[HD Pg 152, Sec. 6.4.0 - exercises]

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
OCAJO1
Posts: 221
Joined: Mon Nov 26, 2018 2:43 pm
Contact:

[HD Pg 152, Sec. 6.4.0 - exercises]

Post by OCAJO1 »

I was looking at the 1st question of Chapter 6's exercise,

"1. Write a method that accepts a number as input and prints whether the number is odd or even using an if/else statement as well as a ternary expression."

and wrote the following code to accommodate any number, with and without a floating point.

I tried using parameter type Number (as well as Object) to avoid method overload, but the compiler did not like the fact that in the first if, num was Number/Object type and 2 was int. Then I tried final Number n = 2; if (num%n == 0) and the compiler complained about both being Number type!

Questions:

1. Why would the compiler complain about bad operand types, if both num and n are Number types?
2. Is there a parameter type that can handle all types of numbers or overloading is the only way?

Thanks

p.s. I think the intent of the exercise 4 of the same page would have been a lot more clear if the first if statement were if (a == b){ instead of if (a == b) and a little further down, the code were else if (flag == false){ instead of else if (flag == false).

Code: Select all

public class Chapter6 {
    
    public void whichNumber(long num){
        
        if (num%2 == 0)
              System.out.println(num+" is an even number.");
        else
              System.out.println(num+" is an odd number.");
        
        System.out.println(num%2 == 0? num+" is an even number." : num+" is an odd number.");
    }
    
    public void whichNumber(double num){
        
        if (num%2 == 0)
              System.out.println(num+" is an even number.");
        else
              System.out.println(num+" is an odd number.");
        
        System.out.println(num%2 == 0? num+" is an even number." : num+" is an odd number.");
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        
       Chapter6 t = new Chapter6();
       t.whichNumber(5.0f);
       t.whichNumber(244);
       t.whichNumber(6.5);
       t.whichNumber(2147483649L);

    }
    
}
Last edited by OCAJO1 on Tue Feb 05, 2019 2:06 pm, edited 1 time in total.

admin
Site Admin
Posts: 10036
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: [HD Pg 374, Sec. 2.8.0 - exercises]

Post by admin »

1. The answer to your question has a lot to do with the rules of method selection. This is explained (along with the answer to your question) in section 8.2.3 pg 189.
Remember that processData(Long ) cannot accept an Integer because Integer is not a subtype of Long.
2. You can use double as the parameter type for your method. It will accept all numbers.

3. Why do you think the changes you suggest would be better? I am curious to know because as an exercise the code seems fine to me if the intention is to make the code more readable. Doesn't really matter what the code does.
If you like our products and services, please help us by posting your review here.

OCAJO1
Posts: 221
Joined: Mon Nov 26, 2018 2:43 pm
Contact:

Re: [HD Pg 152, Sec. 6.4.0 - exercises]

Post by OCAJO1 »

1. I'll double check page 189.

2. This is a bit outside of the scope of this chapter, but the whole reason I went with overloading was because the double parameter was causing the integer numbers to presented with decimal points in the print statements (variable num).

3. Looking at the final indented code, it just looked to me that since the intent of question was to realize the proper indentations, those modifications would have made the expected final outcome more dependent on one's understanding of the flow than the flow and syntax. Of course the way it is, it is a bit more challenging since brackets had to be introduced in those two places.

Code: Select all

        int a = 0, b = 0, c = 0, d = 0;
        boolean flag = false;
        
        if (a == b) {
            if (c == 10) {
                if (d > a) {
                } else {
                }
                if (flag)
                    System.out.println("The first true flag check.");
                else 
                    System.out.println("The first false flag check.");
                
            } else if (flag == false) {
                System.out.println("The second flag check.");
            } else if (a + b < d) {
                System.out.println("");
            } else
                System.out.println("");
        } else
            d = b;

OCAJO1
Posts: 221
Joined: Mon Nov 26, 2018 2:43 pm
Contact:

Re: [HD Pg 152, Sec. 6.4.0 - exercises]

Post by OCAJO1 »

Chapter 7's

exercise 4,

Given the two declarations, is one better than the other? If not, when/where would the first one be useful?

int[] _1D1 = new int[]{1, 2, 3};
int[][] _2D1 = new int[][]{ _1D1 };
int[][] _2D2 = new int[][]{ _1D1, _1D1 };
int[][][] _3D = new int[][][]{ _2D1, _2D2 };

int[][][] _3D1 = new int[][][]{{{1,2,3}}, {{1,2,3}, {1,2,3}}};

exercise 7,

If this were an actual exam question, since it allows printing of all the elements of the chars array, would the answer be, it is a good idea? Or, because each element's exact location (i.e. chars[0][0] = a), cannot be printed, it is not a good idea?

exercise 8,

Is answering the second half of the question (Can you print in reverse using enhanced for loop) this way (2nd & 3rd enhanced for loops), cheating/wrong answer - as far as the intention of the question is concerned?

Code: Select all

        String[] word = {"hello", "goodbye", "well", "AA", "bad", "BBB", "last"};
        String[] rWord = new String[word.length];
        
        boolean alt = false;
        for (String s : word){
            if (!alt)
                System.out.print(s+" ");
            alt = !alt;
        }
        System.out.println();
        
        i = word.length - 1;
        for (String s : word){
            rWord[i] = s;
            i--;
        }
        for (String rs : rWord){
            System.out.print(rs+" ");
        }
Thanks

admin
Site Admin
Posts: 10036
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: [HD Pg 152, Sec. 6.4.0 - exercises]

Post by admin »

OCAJO1 wrote:
Thu Feb 07, 2019 1:19 pm
Chapter 7's

exercise 4,

Given the two declarations, is one better than the other? If not, when/where would the first one be useful?

int[] _1D1 = new int[]{1, 2, 3};
int[][] _2D1 = new int[][]{ _1D1 };
int[][] _2D2 = new int[][]{ _1D1, _1D1 };
int[][][] _3D = new int[][][]{ _2D1, _2D2 };

int[][][] _3D1 = new int[][][]{{{1,2,3}}, {{1,2,3}, {1,2,3}}};

exercise 7,

If this were an actual exam question, since it allows printing of all the elements of the chars array, would the answer be, it is a good idea? Or, because each element's exact location (i.e. chars[0][0] = a), cannot be printed, it is not a good idea?


exercise 8,

Is answering the second half of the question (Can you print in reverse using enhanced for loop) this way (2nd & 3rd enhanced for loops), cheating/wrong answer - as far as the intention of the question is concerned?

Code: Select all

        String[] word = {"hello", "goodbye", "well", "AA", "bad", "BBB", "last"};
        String[] rWord = new String[word.length];
        
        boolean alt = false;
        for (String s : word){
            if (!alt)
                System.out.print(s+" ");
            alt = !alt;
        }
        System.out.println();
        
        i = word.length - 1;
        for (String s : word){
            rWord[i] = s;
            i--;
        }
        for (String rs : rWord){
            System.out.print(rs+" ");
        }
Thanks
4. Neither is better or worse than the other. It is a personal choice. Code readability is the only concern here. You should use which ever approach makes the code easy to read.

7. The second code iterates through the arrays correctly but doesn't update the members of the array. So, it is broken too.

8. The question is meant to highlight what you can and cannot do (easily or otherwise) with an enhanced for loop. The solution is not really important. The ability to decide whether to use enhanced for loop or the regular for loop for a particular problem is important.
If you like our products and services, please help us by posting your review here.

OCAJO1
Posts: 221
Joined: Mon Nov 26, 2018 2:43 pm
Contact:

Re: [HD page 277 sec 8.8.0 - exercises]

Post by OCAJO1 »

Quick questions about exercise 7 in section 8.

Given the code:

Code: Select all

import student.*;
import static student.Student.*;


public class Course {
    
  
    static void enroll(Student x){ //all  the fields in the Student are public
        
        x.studentId = 2;
        name = "Bob";
        x.address = "222 Wrong Street"; 
        
        System.out.println(x.studentId);
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
               
               
    }
    
}
1. How come the print statement in enroll() prints zero? (the last value for studentId in Student class was 2000)
2. Short of using subclass, is there a way, using the enroll() method, to assign new values to the fields. I'm thinking maybe your answer to question 1 may answer this one too.
3. Depending on your answer to 1 & 2 - what would be the best way to assign and print the contents of enroll() from the local main() without having to (lets say) involve the class student?

Thanks
Last edited by OCAJO1 on Mon Feb 25, 2019 9:10 pm, edited 1 time in total.

admin
Site Admin
Posts: 10036
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: [HD Pg 152, Sec. 6.4.0 - exercises]

Post by admin »

1. check your code thoroughly.
2. I am not sure what you mean. Your statement makes no sense. What do you mean by contents of enroll() ?
If you like our products and services, please help us by posting your review here.

OCAJO1
Posts: 221
Joined: Mon Nov 26, 2018 2:43 pm
Contact:

Re: [HD Pg 152, Sec. 6.4.0 - exercises]

Post by OCAJO1 »

I just updated my question.
Last edited by OCAJO1 on Tue Feb 26, 2019 12:43 pm, edited 2 times in total.

admin
Site Admin
Posts: 10036
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: [HD Pg 152, Sec. 6.4.0 - exercises]

Post by admin »

I don't see 2000 wrtten anywhere so why do you expect 2000 to be printed?? Again, check your code thoroughly line by line. Where are you calling enroll.

Still no idea about your other questions.
If you like our products and services, please help us by posting your review here.

OCAJO1
Posts: 221
Joined: Mon Nov 26, 2018 2:43 pm
Contact:

Re: [HD Pg 152, Sec. 6.4.0 - exercises]

Post by OCAJO1 »

I think that is my problem right there. I tried to call enroll() from the main(), but the compiler keeps looking for type Student as parameter.

I'm thinking that I need a bit of detailed hint as to what am I doing wrong here. I think what I've stumbled on here represents more fundamental misunderstanding than what's in question 7!

admin
Site Admin
Posts: 10036
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: [HD Pg 152, Sec. 6.4.0 - exercises]

Post by admin »

It is a fairly simple exercise. Here is what you can do:

package someOtherPackage;
class Course{
public static void enroll(Student s){
System.out.println(s.id); // try changing access modifier of Student class fields and see if you are able to compile.
}
}

That's pretty much it.

Now, if you want to run this code, obviously, you need a main method to start, something like this :

public static void main(String[] args){
Student s = new Student(); //you can use other constructors also
enrolls(s);
}

Remember that there is no single correct answer. The goal is to modify the code and see how things works.

If you have trouble understanding the above, you may want to attend a Java training class or get help from personal tutor.
If you like our products and services, please help us by posting your review here.

OCAJO1
Posts: 221
Joined: Mon Nov 26, 2018 2:43 pm
Contact:

Re: [HD Pg 152, Sec. 6.4.0 - exercises]

Post by OCAJO1 »

Gee this is rather embarrassing. I have a (let's say) not so clever friend who studies Java with me off and on and yesterday I gave my user and password (which of course I will change today) for an urgent question, since I was not available. Looking at what was asked at this stage of the book, maybe a class is very well in order :roll:

OCAJO1
Posts: 221
Joined: Mon Nov 26, 2018 2:43 pm
Contact:

Re: [HD Pg 298, Sec. 10.5 - exercises]

Post by OCAJO1 »

Would you please clarify,
4. Pass null to the countVowels method and observe the output.
whether the null is expected to be passed from the command line (how?)or in main(), passing someCharArray[0] = '\u0000'; from a different try/catch block than the one in Exercise 2?

Thanks

p.s. this is Exercise 2:

2. Invoke the countVowels method from main in a loop and print its return value for each
command line argument. Observe what happens in the following situations: there is no
command line argument, there are multiple arguments, there are multiple arguments but
the rst argument contains an 'x'. (Use String's toCharArray method to get an array of
characters from the string.)

admin
Site Admin
Posts: 10036
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: [HD Pg 152, Sec. 6.4.0 - exercises]

Post by admin »

call countVowels(null); from main.
If you like our products and services, please help us by posting your review here.

OCAJO1
Posts: 221
Joined: Mon Nov 26, 2018 2:43 pm
Contact:

Re: [HD Pg 298, Sec. 10.5.0 - exercises]

Post by OCAJO1 »

Oh, so the point was to cause a NullPointerException at the enhanced for loop (for loop) by passing a null to the method. Here I was passing someCharArray[0] to avoid it :roll:
Last edited by OCAJO1 on Thu Mar 21, 2019 1:49 pm, edited 1 time in total.

OCAJO1
Posts: 221
Joined: Mon Nov 26, 2018 2:43 pm
Contact:

Re: [HD Pg 298, Sec. 10.5.0 - exercises]

Post by OCAJO1 »

I've included my solution to chapter 10's exercise. I believe I've satisfied all 6 questions. However, I appreciate a look see to verify, and any suggestions you might have to streamline any portion.

Thanks

List of command line arguments used to test: "wegedfuop" " xh" "x g" "oiwderioze" "oierjhnwr" " " "45ul65il49ol" " " " h3xx"

Code: Select all

package Ch10Ex;

public class Ch10Ex {
    
    int countVowels (char[] value) throws Exception {
        
        int vowelCt = 0;
        char ex6chk;

        if (value.length == 0)
            
            System.out.println("The array is empty.");
        
        else{

            try{

                ex6chk = value[0];  //Null Test

            }catch(ArrayIndexOutOfBoundsException iae){

                return 0;
            }            
        }
            
        for (char c : value){

                switch (c){

                    case 'a' : vowelCt += 1; break;
                    case 'e' : vowelCt += 1; break;
                    case 'o' : vowelCt += 1; break;
                    case 'i' : vowelCt += 1; break;
                    case 'u' : vowelCt += 1; break;
                    case 'x' : throw new Exception(); //Question 3

                    //below is unchecked verison which doesn't require a
                    //declaration in the throws clause.
                    //case 'x' : throw new IllegalArgumentException
                    //                     ("Array conatins'x'.");
                }
                
        }
        
                    try{        
                ex6chk = value[9];   //Less than 10 characters test 

            }catch(ArrayIndexOutOfBoundsException aiobe){

                //further enhancement to the original requirement.
                //see calling method.
                vowelCt = -vowelCt;
            }

        return vowelCt;
    }

    /**
     * @param args the command line arguments
     * @throws java.lang.Exception
     */
    public static void main(String[] args) throws Exception{
        
        Ch10Ex o = new Ch10Ex();
        
        int z;
        
        //test arrays for question 1
        char[] vc1 = {};
        char[] vc2 = {' '};
        char[] vc3 = {'e', 'g', 'i', '9', 's', 'o', 'd', 'e', '4', 'g'};
        
        z = o.countVowels(vc1);
        System.out.println("There are "+z+" vowels in the 1st array.");
    
        z = o.countVowels(vc2);
        System.out.println("There are "+z+" vowels in the 2nd array.");
        
        z = o.countVowels(vc3);
        System.out.println("There are "+z+" vowels in the 3rd array.");
      
        //Question 2
        for (int i = 0; i< args.length; i++) {
   
            char[] charInput = args[i].toCharArray();

            System.out.print("\nArray number "+i+": ");
            
            if (args[i].equals(" "))
                    System.out.print("This array only has blank characters.");
            
            for (char c: charInput)
                System.out.print(c+" ");

            try{
                int u;

                u = o.countVowels(charInput);

                if (u < 0) {
                    System.out.println("\nThe number of vowels is reset to "
                                       +"-1, since there are less than 10 "
                                       +"characters in the array. However"
                                       +" there are "+-u+" vowels in the"
                                       +" array.");
                    u = -1;
                }
                else
                    System.out.println("\nThere are "+u+" vowels in the "
                                       +"array.");
            }catch(Exception e){

                System.out.println("\nArgument number "+i+
                                   " contains character 'x'.");    
            }
      
        
        /*Question  4:
        -passing a null without a try/catch NPE, will cause JVM to throw one.
        */
        }
        
       //Question 5
        int n = 0;
        try{
            n = o.countVowels(null);
            
        //this catch clause satisfies both number 4 and 6 questions.
        }catch(IllegalArgumentException | NullPointerException ienpe){
                
           System.out.println("\nThe array is NULL, the number of vowels is "+
                              "set to "+n+".");
        }
    }
    
}

admin
Site Admin
Posts: 10036
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: [HD Pg 152, Sec. 6.4.0 - exercises]

Post by admin »

This part isn't too good:

ex6chk = value[0]; //Null Test

If you want to check for null, then check for null.

Same for ex6chk = value[9]; //Less than 10 characters test
If you like our products and services, please help us by posting your review here.

OCAJO1
Posts: 221
Joined: Mon Nov 26, 2018 2:43 pm
Contact:

Re: [HD Pg 298, Sec. 10.5.0 - exercises]

Post by OCAJO1 »

I thought the last part of question 6,
6. Modify countVowels method to return -1, if the input array is null and 0, if the input array
length is less than 10. Do not use an if statement.
meant to do the checking with code that would cause exception. Or does it simply mean use other conditional tools such as a switch?

admin
Site Admin
Posts: 10036
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: [HD Pg 152, Sec. 6.4.0 - exercises]

Post by admin »

oh, fine then.
If you like our products and services, please help us by posting your review here.

wdphipps
Posts: 21
Joined: Mon Sep 23, 2019 4:55 pm
Contact:

Re: [HD Pg 152, Sec. 6.4.0 - exercises]

Post by wdphipps »

The link in the Study Guide (1ZO-815) goes from 4.7 Exercises (Describing and Using Objects and Classes) to this thread. It seems that this is incorrect. Is there any way this can be updated?

admin
Site Admin
Posts: 10036
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: [HD Pg 152, Sec. 6.4.0 - exercises]

Post by admin »

wdphipps wrote:
Mon Oct 21, 2019 6:16 pm
The link in the Study Guide (1ZO-815) goes from 4.7 Exercises (Describing and Using Objects and Classes) to this thread. It seems that this is incorrect. Is there any way this can be updated?
Fixed.
thank you for your feedback!
If you like our products and services, please help us by posting your review here.

Post Reply

Who is online

Users browsing this forum: No registered users and 42 guests