0

I am new to Java and I referred regarding my question on the Net but not quite Satisfied. I want to know what the "Utility Class" in Java is?

Can anybody please tell me with an Example.

Thanks, david

David Brown
  • 4,783
  • 17
  • 50
  • 75

5 Answers5

7

It's usually a class which only has static methods (possibly with a private constructor and marked abstract/final to prevent instantiation/subclassing). It only exists to make other classes easier to use - for example, providing a bunch of static methods to work with String values, performing extra actions which String itself doesn't support.

Utility classes generally don't operate on classes you have control over, as otherwise you'd usually put the behaviour directly within that class. They're not terribly neat in OO terms, but can still be jolly useful.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • @jt-gilkeson: Abstract has the advantage that new XYZ(...) will *obviously* not work. – Jon Skeet Jun 25 '15 at 20:22
  • Abstract _obviosuly_ indicates that the class is meant to be extended - using this keyword is misleading which is why the approach used by Sun, Oracle, and Google is to not mark the classes abstract. The normal approach is `final` class with `private` constructor. See `java.lang.Math` as an example. – jt-gilkeson Jun 25 '15 at 20:32
  • @jt-gilkeson: I'm personally fine with either. I've edited my answer to include final as an option. Shame Java doesn't have the equivalent of C#'s static classes... – Jon Skeet Jun 25 '15 at 20:45
1

To extends Jon Skeet's answer, java.lang.Math, java.util.Collections and java.util.Arrays are typical examples for such classes.

Landei
  • 54,104
  • 13
  • 100
  • 195
0

Its a class with all static methods and no member elements.

josliber
  • 43,891
  • 12
  • 98
  • 133
Vivek Vermani
  • 1,934
  • 18
  • 45
0

There's a utility package, java.util, that contains a bunch of stuff like dates, times, string tokenizers... Not sure if that's what you're talking about.

0

public class Utils {

public static boolean isNetworkAvailable(Context context) {
    ConnectivityManager connectivityManager = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager
            .getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

public static void unlockScreenOrientation(Activity activity) {
    activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
}

public static void lockScreenOrientation(Activity activity) {
    int currentOrientation = activity.getResources().getConfiguration().orientation;
    if (currentOrientation == Configuration.ORIENTATION_PORTRAIT)
    {
        activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }
    else
    {
        activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }
}
// Get Http Post response
@Nullable
public static String getHttpResponse(String url, List<NameValuePair> nameValuePairs) {
    HttpClient httpClient = new DefaultHttpClient();

    HttpPost httpPost = new HttpPost(url);
    UrlEncodedFormEntity entity;
    try {
        entity = new UrlEncodedFormEntity(nameValuePairs);
        httpPost.setEntity(entity);
        HttpResponse response = httpClient.execute(httpPost);

        HttpEntity resEntity = response.getEntity();
        String res =  EntityUtils.toString(resEntity);
        return res;
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

public static void CopyStream(InputStream is, OutputStream os) {
    final int buffer_size=1024;
    try
    {
        byte[] bytes=new byte[buffer_size];
        for(;;)
        {
            int count=is.read(bytes, 0, buffer_size);
            if(count==-1)
                break;
            os.write(bytes, 0, count);
        }
    }
    catch(Exception ex){}
}

public static JSONObject getJsonObjectFromXmlResponse(String xmlString) {
    JSONObject objectJson = new JSONObject();
    //JSONArray arrayJson = new JSONArray();

    XmlPullParser parser = Xml.newPullParser();
    try {
        parser.setInput(new StringReader(xmlString));
        int eventType = parser.getEventType();

        while (eventType != XmlPullParser.END_DOCUMENT) {
            String name;
            switch (eventType) {
                case XmlPullParser.START_TAG:
                    name = parser.getName();
                    if (name.equalsIgnoreCase("string")) {
                        String yourValue = parser.nextText();
                        //arrayJson = new JSONArray(yourValue);
                        objectJson = new JSONObject(yourValue);
                    }
                    break;
            }
            eventType = parser.next();
        }
    } catch (XmlPullParserException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return objectJson;
}

}