[HD Pg 376, Sec. 12.6.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 376, Sec. 12.6.0 - exercises]

Post by OCAJO1 »

Exercise 2,

I was wondering if the following simple method is sufficient to show that StringBuilder's toString() and substring() will not return an interned string, while String's same methods will?

Code: Select all

    void checkInterned (){
        
        String s = "checks";
        StringBuilder sb = new StringBuilder("checksb");
        
        if (sb.substring(0) == sb.substring(0)) 
            System.out.println("StringBuilder's substring returns interned string");
        
        if (sb.toString() == sb.toString())
            System.out.println("StringBuilder's toString returns interned string");
        
        if (s.substring(0) == s.substring(0))
            System.out.println("String's substring returns interned string");
        
        if (s.toString() == s.toString())
            System.out.println("String's toString returns interned string");
    }
For exercise 5, should I open up the code in try block, or is good as it stands?

Code: Select all

   //Excercise 5
    String changeStringBuilder (StringBuilder sb){
        
        try{
            return sb.replace(0, sb.length()-4, "X").toString();
        }catch(IndexOutOfBoundsException e){
            return "Input must contain at least 4 characters.";
        }
    } 
For exercise 6,
- please find the different calls from TestClass' main(). Is that sufficient variation to make sure the method can cover all basis?
- as for
Is this a good place to make use of a StringBuilder?
since the incoming array and its components are Strings, I don't see what would be the point of all the extra back and forth conversions code that would be needed in order to make use of StringBuilder. The only possible advantage I see in using StringBuilder here, is if there is concern for saving heap memory space with so many Strings being created. If that is the point, then I would change the parameter from String[] to StringBuilder[] to save a lot of extra conversion coding as well. Yes, No?

Code: Select all

//the method

    String stringArray (String[] sa){
        
        String sf = "";
        for (String s : sa)
            sf += s;
        return sf;
    }

//the calls from TestClass's main()

String[] stra1 = new String[]{"1", null, "hello", "", "null", null, " ", "W"};
System.out.println("\n"+ss.stringArray(stra1));
        
String[] stra2 = new String[]{null, null};
System.out.println(ss.stringArray(stra2));
        
String[] stra3 = new String[]{""};
System.out.println(ss.stringArray(stra3));
        
String[] stra4 = new String[]{"", null, "", null};
System.out.println(ss.stringArray(stra4));
Thanks
Last edited by OCAJO1 on Wed May 08, 2019 1:39 pm, edited 3 times in total.

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

Re: [HD Pg 376, Sec. 12.6.0 - exercises]

Post by admin »

1. If you want to check whether a string is same as the interned string, then you should do sb.substring(0) == sb.substring(0).intern().
2. This is fine.
3. Yes, the variations are fine. Your argument for not using stringbuilder is not good. Think harder.
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 376, Sec. 12.6.0 - exercises]

Post by OCAJO1 »

1. I originally wrote the test with .intern() and then I removed it to see what happens, and the same results occurred!
I guess instead of categorizing the method as a simple method, I should have asked if testing without .intern() was sufficient.
Question: how come removing or keeping .intern() did not cause the results to change in any of the 4 if statements ?

Code: Select all

void checkInterned (){
        
        String s = "checks";
        StringBuilder sb = new StringBuilder("checksb");
        
        if (sb.substring(0) == sb.substring(0).intern()) 
            System.out.println("StringBuilder's substring returns interned string");
        
        if (sb.toString() == sb.toString().intern())
            System.out.println("StringBuilder's toString returns interned string");
        
        if (s.substring(0) == s.substring(0).intern())
            System.out.println("String's substring returns interned string");
        
        if (s.toString() == s.toString().intern())
            System.out.println("String's toString returns interned string");
}
3. Are you by any chance referring to the fact that StringBuilders are mutable and items like nulls can be inserted or appended to the same string without causing an exception, while Strings not being mutable, can not? f not, then I'm not sure where is this question pointing?

As for exercise 10, would the following method and a call from TestClass main() do the job?

Code: Select all

    List<LocalDate> justDateList (List<LocalDateTime> ldtl){
        
        List<LocalDate> ldl = new ArrayList<>();
        
        LocalDate localdate = LocalDate.now(); 
        int month = localdate.getMonthValue();
        int day   = localdate.getDayOfMonth();
        
        for (LocalDateTime a : ldtl){
            if (a.getMonthValue() == month && a.getDayOfMonth() == day)            
                ldl.add(LocalDate.from(a));  
        }
        return ldl;
    }

//call from TestClass' main()

        //Excercise 10

        TestClass ot = new TestClass();

        List<LocalDateTime> ldlt = new ArrayList<>();
        ldlt.add(LocalDateTime.of(2019, 4, 9, 12, 34, 16));
        ldlt.add(LocalDateTime.of(2019, Month.MAY, 8, 11, 44, 16));
        ldlt.add(LocalDateTime.of(2018, 5, 8, 14, 34, 18));
        ldlt.add(LocalDateTime.of(2018, Month.JUNE, 12, 9, 4, 26));
        ldlt.add(LocalDateTime.of(2017, 5, 8, 2, 3, 7));
        
        for (LocalDate gl : ot.justDateList(ldlt))
            System.out.println(gl);

printed results were,

2019-05-08
2018-05-08
2017-05-08

By the way, in exercise 13 the method signature switch(ArrayList al, int a, int b) contains a reserved word. Should be changed to something like switchIt.

I wasn't sure if the exercise was after any E type ArrayList, so I figured to put up my solution to see if it is right.

Code: Select all

//the method

    ArrayList switchIt(ArrayList al, int a, int b){
    
        Object atemp = al.remove(a);
        Object btemp = al.remove(b-1);
        al.add(a,btemp);
        al.add(b,atemp);
        
         //or if in need of code compression
         
        //al.add(b,al.remove(a));
        //al.add(a,al.remove(b-1));
         
        return al;
    
    }

//calls from TestClass' main()

        ArrayList ars = new ArrayList(Arrays.asList(
                                     new String[]{"A", "B", "C", "D", "E"})); 
        System.out.println(oa.switchIt(ars,1,4));
                
        ArrayList ari = new ArrayList(Arrays.asList(
                                     new Integer[]{1, 2, 3, 4, 5}));
        System.out.println(oa.switchIt(ari,1,2));
         
Thanks

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

Re: [HD Pg 376, Sec. 12.6.0 - exercises]

Post by OCAJO1 »

We never finished the discussion about the exercises 1-13 (previous blog entry) and I have included the rest of the exercises in this blog entry.

I appreciate a look see at the previous blog entry and the ones in this blog to check them out and if any suggestions you might have to improve any of the methods. Thanks

Here are the exercise 14 thru 17.

Code: Select all

import java.util.*;
import java.util.function.Predicate;

//Excercise 14
interface NoParam {
    
    boolean noParamMethod();
}

interface IParam {
    
    boolean iParamMethod (Integer l);
}

//Excercise 15
interface Shape{
    
    double computeArea();
}

interface Operation{
    
    void operate(String name, double[] params);
}

class ImageInfo{
    
    String imageName; int width; int height;
    
    ImageInfo(String i, int w, int h){
        this.imageName = i; this.width = w; this.height = h;
    }

   @Override
   public String toString(){ return "("+imageName+" "+width+" "+height+")"; }
   
}    

class Image {
    
    List<ImageInfo> images = new ArrayList<>();
    
    Image(){
        images.add(new ImageInfo("Image1", 100, 200));
        images.add(new ImageInfo("Image2", 90, 100));
        images.add(new ImageInfo("Image3", 80, 60));
        images.add(new ImageInfo("Image4", 1200, 30));
        images.add(new ImageInfo("Image5", 300, 1200));
        images.add(new ImageInfo("Image6", 1900, 100));
    }
    
    //Excercise 16
    List<Object> imageControl(List<Object> li, Predicate p){
        
        List<Object> lic = new ArrayList<>();
        
        for (Object om : li){
            if (p.test(om)) lic.add(om);
        }
       
        return lic;     
    }
    
    //Excercise 17
    List<ImageInfo> imageControl(Predicate<ImageInfo> wp, Predicate<ImageInfo> hp){
        
        ArrayList<ImageInfo> imageList = new ArrayList<>();
              
        for (ImageInfo in : images){
           
            Predicate<ImageInfo> whp = wp.and(hp);
            if(whp.test(in)) imageList.add(in);                        
        }   
        return imageList;
    } 
    
}

class TestClass implements NoParam, IParam, Shape, Operation {

    @Override
    public boolean noParamMethod(){ return true; };
    
    @Override
    public boolean iParamMethod(Integer l){ return l > 5; }
    
    @Override
    public double computeArea(){ return 10; }
    
    @Override
    public void operate(String name, double[] params){ }
        
    public static void main(String[] args){
        
        NoParam i = ()->true;
        IParam j = k->k>5;
        
        Shape v = ()->5*2;
        Operation o = (String s, double[] p)->{System.out.println(s+" "+p.length);};
        
        Image im = new Image();
        
        List<Object> olist = new ArrayList<>
                            (Arrays.asList(new Object[]{"Image1", "Image2", "Image3"}));
        List<Object> nlist = im.imageControl(olist, m->m.equals("Image2"));
        System.out.println(nlist);
        
        List<ImageInfo> goodImages = im.imageControl(in->in.width >= 100,
                                                         in -> in.height >= 100);
        System.out.println(goodImages);
        
        
        
    }

}
Looks like coming to the end of it :joy:

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

Re: [HD Pg 376, Sec. 12.6.0 - exercises]

Post by admin »

Yes, it looks fine.
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 376, Sec. 12.6.0 - exercises]

Post by OCAJO1 »

Are you sure - even the lambda's? You've never looked at my exercises (especially this many of them) and given a blanket all well before :o

By the way I'm still wondering about the questions from the past blog entry,
1. Question: how come removing or keeping .intern() did not cause the results to change in any of the 4 if statements ?
void checkInterned (){

String s = "checks";
StringBuilder sb = new StringBuilder("checksb");

if (sb.substring(0) == sb.substring(0).intern())
System.out.println("StringBuilder's substring returns interned string");

if (sb.toString() == sb.toString().intern())
System.out.println("StringBuilder's toString returns interned string");

if (s.substring(0) == s.substring(0).intern())
System.out.println("String's substring returns interned string");

if (s.toString() == s.toString().intern())
System.out.println("String's toString returns interned string");
}

2. Excursive 6 part 2 - Are you by any chance referring to the fact that StringBuilders are mutable and items like nulls can be inserted or appended to the same string without causing an exception, while Strings not being mutable, can not?
Thanks

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

Re: [HD Pg 376, Sec. 12.6.0 - exercises]

Post by admin »

Why do you think removing or keeping .intern() did not cause the results to change in any of the 4 if statements ?
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 376, Sec. 12.6.0 - exercises]

Post by OCAJO1 »

Reading what intern() does again, I think I've been giving it a lot more credit than it deserves. All it does is, causes a single copy instead of multiple copies of a string (whether be from a String or StringBuilder type) to be stored on the heap, nothing more.

enthunoob
Posts: 60
Joined: Thu Apr 15, 2021 12:21 pm
Contact:

Re: [HD Pg 376, Sec. 12.6.0 - exercises]

Post by enthunoob »

Code: Select all

	/*
	13. Create a method with the signature switch( ArrayList al, int a, int b).
	 This method should return the same list but after switching the elements 
	 at positions a and b. 
	*/
	static ArrayList switchAL(ArrayList al, int a, int b){
		Object o1 = al.get(a);
		Object o2 = al.get(b);
		al.set(a, o2);
		al.set(b, o1);
		return al;
	}
Hello, for this exercise I wrote this method. But I was wondering if there is any point in returning the ArrayList, as (the contents of) al will be adjusted anyway. I mean, it might as well return void, and it will do the same thing. Because even though the ArrayList is passed as argument, it only passes the reference to the ArrayList, not the ArrayList itself. So my question is, what would be better programming practice?

1. return al--> because it specifies to the users of the switch method that it adjusts an ArrayList.
2. return void --> because it does not fool users of switch method that a copy is returned, but the actual original ArrayList itself is adjusted.

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

Re: [HD Pg 376, Sec. 12.6.0 - exercises]

Post by admin »

True, logically, it doesn't make much sense to return the same reference.
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 88 guests