The document discusses various Java standard libraries and frameworks essential for developers, including Mockito for unit testing, Apache Commons for reusable components, and Jackson for JSON parsing. It also covers the concept of templates in C++, explaining how they enable generic programming through function and class templates. Additionally, it highlights the advantages of generics in Java, such as type safety and code reusability, with examples of generic classes, methods, and interfaces.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0 ratings0% found this document useful (0 votes)
23 views22 pages
Unit 4
The document discusses various Java standard libraries and frameworks essential for developers, including Mockito for unit testing, Apache Commons for reusable components, and Jackson for JSON parsing. It also covers the concept of templates in C++, explaining how they enable generic programming through function and class templates. Additionally, it highlights the advantages of generics in Java, such as type safety and code reusability, with examples of generic classes, methods, and interfaces.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 22
Unit 4
Standard Libraries: Templates; Generic Programming
using generic function and 6 class; Packages; Interfaces. Iterators; Containers. Java Libraries Every developer is more or less aware of the benefits of using libraries- eliminating redundancy and thus saving time. For every programming language, there are frameworks and libraries that are fundamental to learning and mastering it. 1. Java Standard Libraries It is always best, to begin with, the frameworks and libraries provided by the programming language itself. This is also true for development tools. The Java standard libraries provided by Java are often overlooked but have some of the most robust and functional libraries. To name a few: • Java.util • Java.lang • Java.math • Java.net • Java.io /Java.nio Java standard library helps students and new Java developers to build a strong base which further helps them to solidify their concepts and learn different third-party libraries efficiently. 2. Mockito [Unit Testing Library] Somewhat inferable from the name, Mockito is an open-source mocking framework. Java developers are often expected to be skilled at conducting unit tests. Mockito helps developers to write tests with clean and simple API. It enables developers to test double objects or dummy objects for behavior-driven and test-driven behavior. According to StackOverflow, Mockito was voted as the best mocking framework for Java. 3. JUnit [Unit Testing Library] Another unit testing framework, JUnit lets Java programmers create test cases and run unit tests. Unit testing tools are crucial for fixing bugs, which is why mastering unit testing tools becomes imperative. JUnit creates new samples of the test class every time developer runs a test. One important thing to note is that creating test cases independent of each other is important with JUnit since JUnit runs tests randomly, without following a set sequence. 4. Apache Commons [General-Purpose Library] The official site of Apache Commons states Apache Commons as an Apache project aimed at all aspects of reusable Java components, i.e. Java libraries. It is a general-purpose library compromising of various libraries. To name a few- • Commons IO • Commons Numbers • Commons Text • Commons CSV • Commons BSF • Commons Crypto The above-mentioned list of Apache Commons libraries is non-exhaustive. A Java developer can make use of the plethora of library resources available on Apache Commons without having to refer to another source. 5. Google Guava [General-Purpose Library] An alternative for Apache Commons, Google Guava is an open-source containing core Java libraries. Guava offers additional advanced features and functions to Java, some of these include new generic classes like multiset and bitmaps, strings, I/O, caches, graph libraries, etc. Guava has consistently been one of the most popular Java libraries. It is usually classified under three heads, namely- • Basic utilities to implement common methods and behavior • Google collections library • Miscellaneous utilities providing productivity features 6. Jackson [JSON Parsing Library] Jackson is perhaps the most used JSON parsing library known for its high performance, lightweight, and accuracy. It lets developers serialize and map Java objects to JSON and vice versa. Jackson has various tools and uses various approaches for working with JSON, such as using data binding annotations on POJO classes, additional data format modules, etc. It also supports different data types like standard collections datatype, Java 8 Module, Hibernates, etc., and can process data encrypted in BSV, XML, CBOR, BSON, TOML, etc. 7. HttpClient [HTTP Library] HttpClient is used to request and retrieve HTTP resources over the network. Java HttpClient supports HTTP/1.1 and HTTP/2. It supports both synchronous and asynchronous programming models. HttpClient is built through a builder and is fixed once set. The Java developer can use it to make multiple requests and gain configuration information and resources for each one of the requests. 8. Log4j 2 [Logging Library] Log4j is the most popular logging library for Java. Log4j 2 is an upgrade of Log4j and addresses issues faced in the Log4j framework. It also has a plugin architect that lets developers define and configure custom components. Logging events are imperative and logging libraries help developers to manage these log events. Log4j 2 has more advanced features than Log4j, some of them are: • Improved filters and speed • Extensibility and reliability • Custom log levels • Supports JSON, XML, and YAML • Support for multiple APIs • Performance of asynchronous loggers • Clean configuration syntax Templates Templates in C++ allow us to write generic code that works with multiple data types without rewriting the same logic. Templates enable generic programming by allowing functions and classes to work with any data type. 1. Function Templates A function template allows a function to operate on different data types without being rewritten for each type. Example: Generic Function for Addition #include <iostream> using namespace std; template <typename T> // Template declaration T add(T a, T b) { return a + b; } int main() { cout << "Sum of integers: " << add(5, 10) << endl; cout << "Sum of doubles: " << add(5.5, 2.5) << endl; return 0; } • The function add<T>() works for both int and double. 2. Class Templates A class template allows a class to handle multiple data types. Example: Generic Box Class #include <iostream> using namespace std; template <typename T> // Template declaration class Box { T value; public: Box(T v) : value(v) {} // Constructor void show() { cout << "Box contains: " << value << endl; } }; •Box<int> stores an integer, and int main() { Box<string> stores a string. Box<int> intBox(100); intBox.show(); Box<string> strBox("Hello"); strBox.show(); return 0; } 3. Multiple Type Parameters in Templates We can use multiple template parameters for different types. Example: Pair Class with Two Data Types #include <iostream> using namespace std; template <typename T1, typename T2> class Pair { T1 first; T2 second; public: Pair(T1 a, T2 b) : first(a), second(b) {} •Pair<string, int> holds a string and an void show() { cout << "Pair: " << first << ", " << second << endl; } integer. }; •Pair<double, char> holds a double and int main() { a character. Pair<string, int> p1("Age", 25); p1.show(); Pair<double, char> p2(3.14, 'A'); p2.show(); return 0; } 4. Template Specialization Sometimes, we need a specialized version of a template for a specific type. Example: Specialization for char* Type #include <iostream> using namespace std; template <typename T> class Printer { public: void print(T data) { cout << "Data: " << data << endl; } }; // Specialized version for `char*` template <> •Printer<int> uses the generic template. class Printer<char*> { •Printer<char*> uses a specialized version. public: void print(char* data) { cout << "String: " << data << endl; } }; int main() { Printer<int> intPrinter; intPrinter.print(10); Printer<char*> stringPrinter; stringPrinter.print("Hello"); return 0; 5. Template with Default Type We can assign a default data type for a template. Example: Default Type for Class #include <iostream> using namespace std; template <typename T = int> // Default type is `int` class Number { T value; public: Number(T v) : value(v) {} •Number<> uses int as the default type. void show() { cout << "Value: " << value << endl; } •Number<double> overrides it with }; double. int main() { Number<> num1(50); // Uses `int` as default num1.show(); Number<double> num2(3.14); num2.show(); return 0; } 6. Template in Inheritance Templates can be used in inheritance. Example: Base and Derived Classes with Templates #include <iostream> using namespace std; template <typename T> class Base { public: void show() { cout << "Base class with type: " << typeid(T).name() << endl; } }; template <typename T> class Derived : public Base<T> { }; int main() { •Derived<int> inherits from Base<int>. Derived<int> d; d.show(); return 0; } 7. Template with Static Members Templates can have static members, shared among all instances of the same type. Example: Counter with Static Variable #include <iostream> using namespace std; template <typename T> class Counter { public: static int count; Counter() { count++; } void showCount() { cout << "Count: " << count << endl; } }; template <typename T> •Counter<int> and Counter<double> maintain int Counter<T>::count = 0; separate counts. int main() { Counter<int> c1, c2; c1.showCount(); // Count: 2 Counter<double> c3; c3.showCount(); // Count: 1 return 0; } Difference Between Templates (C++) and Generics (Java) Generic Programming using generic function and 6 class Generic programming is a style of programming that allows code to be written in a general way so that it can work with different data types. In object-oriented programming (OOP), this is commonly achieved using generic functions and generic classes.
Why Use Generics in Java?
Type Safety → Detects type errors at compile time Code Reusability → One class or method works with different data types Eliminates Type Casting → Avoids unnecessary casting Compile-time Checking → Reduces runtime errors A generic class allows us to create a class that works with any data type. Example: Generic Box Class class Box<T> { // <T> makes it a generic class private T value; public Box(T value) { this.value = value; } public void show() { System.out.println("Box contains: " + value); } } public class Main { public static void main(String[] args) { Box<Integer> intBox = new Box<>(100); intBox.show(); Box<String> strBox = new Box<>("Hello"); strBox.show(); } } A generic method allows a method to accept any type of data. Example: Generic Print Method class Printer { public <T> void print(T data) { // Generic method System.out.println("Printing: " + data); } } public class Main { public static void main(String[] args) { Printer p = new Printer(); p.print(10); // Prints Integer p.print("Hello"); // Prints String p.print(3.14); // Prints Double } } An interface can also be generic. Example: Generic Interface interface Container<T> { void show(T item); } class DataContainer<T> implements Container<T> { public void show(T item) { System.out.println("Container holds: " + item); } } public class Main { public static void main(String[] args) { DataContainer<Integer> intContainer = new DataContainer<>(); intContainer.show(500); DataContainer<String> strContainer = new DataContainer<>(); strContainer.show("Java Generics"); } } We can use multiple type parameters. Example: Generic Pair Class class Pair<K, V> { // Two generic types private K key; private V value; public Pair(K key, V value) { this.key = key; this.value = value; } public void show() { System.out.println("Pair: " + key + " -> " + value); } } public class Main { public static void main(String[] args) { Pair<String, Integer> age = new Pair<>("Alice", 25); age.show(); Pair<Integer, Double> marks = new Pair<>(101, 95.5); marks.show(); } } Java Collections (ArrayList, HashMap, etc.) use generics for type safety. Example: Using Generics in Collections import java.util.*; public class Main { public static void main(String[] args) { // List with Generics List<String> names = new ArrayList<>(); names.add("John"); names.add("Alice"); // No need for casting String firstName = names.get(0); System.out.println("First name: " + firstName); // Map with Generics Map<Integer, String> students = new HashMap<>(); students.put(1, "Emma"); students.put(2, "Liam"); System.out.println("Student ID 1: " + students.get(1)); } } Wildcard (?) allows us to use unknown types in methods. Example: Using Wildcards in a Method import java.util.*; class Printer { public static void printList(List<?> list) { // Wildcard ? allows any type for (Object item : list) { System.out.println(item); } } } public class Main { public static void main(String[] args) { List<Integer> numbers = Arrays.asList(10, 20, 30); List<String> words = Arrays.asList("Hello", "World"); Printer.printList(numbers); Printer.printList(words); } }