Properties class and Generics in Java

Last updated on Dec 27 2022
Prabhas Ramanathan

The properties object contains key and value pair both as a string. The java.util.Properties class is the subclass of Hashtable.
It can be used to get property value based on the property key. The Properties class provides methods to get data from the properties file and store data into the properties file. Moreover, it can be used to get the properties of a system.

Table of Contents

An Advantage of the properties file

Recompilation is not required if the information is changed from a properties file: If any information is changed from the properties file, you don’t need to recompile the java class. It is used to store information which is to be changed frequently.

Constructors of Properties class

Method Description
Properties() It creates an empty property list with no default values.
Properties(Properties defaults) It creates an empty property list with the specified defaults.

Methods of Properties class

The commonly used methods of Properties class are given below.

Method Description
public void load(Reader r) It loads data from the Reader object.
public void load(InputStream is) It loads data from the InputStream object
public void loadFromXML(InputStream in) It is used to load all of the properties represented by the XML document on the specified input stream into this properties table.
public String getProperty(String key) It returns value based on the key.
public String getProperty(String key, String defaultValue) It searches for the property with the specified key.
public void setProperty(String key, String value) It calls the put method of Hashtable.
public void list(PrintStream out) It is used to print the property list out to the specified output stream.
public void list(PrintWriter out)) It is used to print the property list out to the specified output stream.
public Enumeration<?> propertyNames()) It returns an enumeration of all the keys from the property list.
public Set<String> stringPropertyNames() It returns a set of keys in from property list where the key and its corresponding value are strings.
public void store(Writer w, String comment) It writes the properties in the writer object.
public void store(OutputStream os, String comment) It writes the properties in the OutputStream object.
public void storeToXML(OutputStream os, String comment) It writes the properties in the writer object for generating XML document.
public void storeToXML(Writer w, String comment, String encoding) It writes the properties in the writer object for generating XML document with the specified encoding.

Example of Properties class to get information from the properties file

To get information from the properties file, create the properties file first.

db.properties

1. user=system
2. password=oracle
Now, let’s create the java class to read the data from the properties file.

Test.java

1. import java.util.*; 
2. import java.io.*; 
3. public class Test { 
4. public static void main(String[] args)throws Exception{ 
5. FileReader reader=new FileReader("db.properties"); 
6. 
7. Properties p=new Properties(); 
8. p.load(reader); 
9. 
10. System.out.println(p.getProperty("user")); 
11. System.out.println(p.getProperty("password")); 
12. } 
13. }

Output:system
oracle

Now if you change the value of the properties file, you don’t need to recompile the java class. That means no maintenance problem.

Example of Properties class to get all the system properties

By System.getProperties() method we can get all the properties of the system. Let’s create the class that gets information from the system properties.
Test.java

1. import java.util.*; 
2. import java.io.*; 
3. public class Test { 
4. public static void main(String[] args)throws Exception{ 
5. 
6. Properties p=System.getProperties(); 
7. Set set=p.entrySet(); 
8. 
9. Iterator itr=set.iterator(); 
10. while(itr.hasNext()){ 
11. Map.Entry entry=(Map.Entry)itr.next(); 
12. System.out.println(entry.getKey()+" = "+entry.getValue()); 
13. } 
14. 
15. } 
16. }

Output:
java.runtime.name = Java(TM) SE Runtime Environment
sun.boot.library.path = C:\Program Files\Java\jdk1.7.0_01\jre\bin
java.vm.version = 21.1-b02
java.vm.vendor = Oracle Corporation
java.vendor.url = http://java.oracle.com/
path.separator = ;
java.vm.name = Java HotSpot(TM) Client VM
file.encoding.pkg = sun.io
user.country = US
user.script =
sun.java.launcher = SUN_STANDARD
………..

 

Example of Properties class to create the properties file

Now let’s write the code to create the properties file.
Test.java

1. import java.util.*; 
2. import java.io.*; 
3. public class Test { 
4. public static void main(String[] args)throws Exception{ 
5. 
6. Properties p=new Properties(); 
7. p.setProperty("name","Sonoo Jaiswal"); 
8. p.setProperty("email","sonoojaiswal@tecklearn.com"); 
9. 
10. p.store(new FileWriter("info.properties"),"Tecklearn Properties Example"); 
11. 
12. } 
13. }

Let’s see the generated properties file.

info.properties

1. #Tecklearn Properties Example
2. #Thu Oct 03 22:35:53 IST 2013
3. email=sonoojaiswal@tecklearn.com
name=Sonoo Jaiswal

Java – Generics

It would be nice if we could write a single sort method that could sort the elements in an Integer array, a String array, or an array of any type that supports ordering.
Java Generic methods and generic classes enable programmers to specify, with a single method declaration, a set of related methods, or with a single class declaration, a set of related types, respectively.
Generics also provide compile-time type safety that allows programmers to catch invalid types at compile time.
Using Java Generic concept, we might write a generic method for sorting an array of objects, then invoke the generic method with Integer arrays, Double arrays, String arrays and so on, to sort the array elements.

Generic Methods

You can write a single generic method declaration that can be called with arguments of different types. Based on the types of the arguments passed to the generic method, the compiler handles each method call appropriately. Following are the rules to define Generic Methods −
• All generic method declarations have a type parameter section delimited by angle brackets (< and >) that precedes the method’s return type ( < E > in the next example).
• Each type parameter section contains one or more type parameters separated by commas. A type parameter, also known as a type variable, is an identifier that specifies a generic type name.
• The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as actual type arguments.
• A generic method’s body is declared like that of any other method. Note that type parameters can represent only reference types, not primitive types (like int, double and char).

Example

Following example illustrates how we can print an array of different type using a single Generic method −

public class GenericMethodTest {
// generic method printArray
public static < E > void printArray( E[] inputArray ) {
// Display array elements
for(E element : inputArray) {
System.out.printf("%s ", element);
}
System.out.println();
}

public static void main(String args[]) {
// Create arrays of Integer, Double and Character
Integer[] intArray = { 1, 2, 3, 4, 5 };
Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 };
Character[] charArray = { 'H', 'E', 'L', 'L', 'O' };

System.out.println("Array integerArray contains:");
printArray(intArray); // pass an Integer array

System.out.println("\nArray doubleArray contains:");
printArray(doubleArray); // pass a Double array

System.out.println("\nArray characterArray contains:");
printArray(charArray); // pass a Character array
}
}

This will produce the following result −

Output

Array integerArray contains:
1 2 3 4 5

Array doubleArray contains:
1.1 2.2 3.3 4.4

Array characterArray contains:
H E L L O

Bounded Type Parameters

There may be times when you’ll want to restrict the kinds of types that are allowed to be passed to a type parameter. For example, a method that operates on numbers might only want to accept instances of Number or its subclasses. This is what bounded type parameters are for.
To declare a bounded type parameter, list the type parameter’s name, followed by the extends keyword, followed by its upper bound.

Example

Following example illustrates how extends is used in a general sense to mean either “extends” (as in classes) or “implements” (as in interfaces). This example is Generic method to return the largest of three Comparable objects −

 

public class MaximumTest {
// determines the largest of three Comparable objects

public static <T extends Comparable<T>> T maximum(T x, T y, T z) {
T max = x; // assume x is initially the largest

if(y.compareTo(max) > 0) {
max = y; // y is the largest so far
}

if(z.compareTo(max) > 0) {
max = z; // z is the largest now 
}
return max; // returns the largest object 
}

public static void main(String args[]) {
System.out.printf("Max of %d, %d and %d is %d\n\n", 
3, 4, 5, maximum( 3, 4, 5 ));

System.out.printf("Max of %.1f,%.1f and %.1f is %.1f\n\n",
6.6, 8.8, 7.7, maximum( 6.6, 8.8, 7.7 ));

System.out.printf("Max of %s, %s and %s is %s\n","pear",
"apple", "orange", maximum("pear", "apple", "orange"));
}
}

This will produce the following result −

Output

Max of 3, 4 and 5 is 5

Max of 6.6,8.8 and 7.7 is 8.8

Max of pear, apple and orange is pear

Generic Classes

A generic class declaration looks like a non-generic class declaration, except that the class name is followed by a type parameter section.
As with generic methods, the type parameter section of a generic class can have one or more type parameters separated by commas. These classes are known as parameterized classes or parameterized types because they accept one or more parameters.

Example

Following example illustrates how we can define a generic class −

public class Box<T> {
private T t;

public void add(T t) {
this.t = t;
}

public T get() {
return t;
}

public static void main(String[] args) {
Box<Integer> integerBox = new Box<Integer>();
Box<String> stringBox = new Box<String>();

integerBox.add(new Integer(10));
stringBox.add(new String("Hello World"));

System.out.printf("Integer Value :%d\n\n", integerBox.get());
System.out.printf("String Value :%s\n", stringBox.get());
}
}

This will produce the following result −
Output
Integer Value :10
String Value :Hello World

 

So, this brings us to the end of blog. This Tecklearn ‘Properties class and Generics in Java’ blog helps you with commonly asked questions if you are looking out for a job in Java Programming. If you wish to learn Java and build a career Java Programming domain, then check out our interactive, Java and JEE Training, that comes with 24*7 support to guide you throughout your learning period. Please find the link for course details:

Java and JEE Training

Java and JEE Training

About the Course

Java and JEE Certification Training is designed by professionals as per the industrial requirements and demands. This training encompasses comprehensive knowledge on basic and advanced concepts of core Java & J2EE along with popular frameworks like Hibernate, Spring & SOA. In this course, you will gain expertise in concepts like Java Array, Java OOPs, Java Function, Java Loops, Java Collections, Java Thread, Java Servlet, and Web Services using industry use-cases and this will help you to become a certified Java expert.

Why Should you take Java and JEE Training?

• Java developers are in great demand in the job market. With average pay going between $90,000/- to $120,000/- depending on your experience and the employers.
• Used by more than 10 Million developers worldwide to develop applications for 15 Billion devices.
• Java is one of the most popular programming languages in the software world. Rated #1 in TIOBE Popular programming languages index (15th Consecutive Year)

What you will Learn in this Course?

Introduction to Java

• Java Fundamentals
• Introduction to Java Basics
• Features of Java
• Various components of Java language
• Benefits of Java over other programming languages
• Key Benefits of Java

Installation and IDE’s for Java Programming Language

• Installation of Java
• Setting up of Eclipse IDE
• Components of Java Program
• Editors and IDEs used for Java Programming
• Writing a Simple Java Program

Data Handling and Functions

• Data types, Operations, Compilation process, Class files, Loops, Conditions
• Using Loop Constructs
• Arrays- Single Dimensional and Multi-Dimensional
• Functions
• Functions with Arguments

OOPS in Java: Concept of Object Orientation

• Object Oriented Programming in Java
• Implement classes and objects in Java
• Create Class Constructors
• Overload Constructors
• Inheritance
• Inherit Classes and create sub-classes
• Implement abstract classes and methods
• Use static keyword
• Implement Interfaces and use it

Polymorphism, Packages and String Handling

• Concept of Static and Run time Polymorphism
• Function Overloading
• String Handling –String Class
• Java Packages

Exception Handling and Multi-Threading

• Exception handling
• Various Types of Exception Handling
• Introduction to multi-threading in Java
• Extending the thread class
• Synchronizing the thread

File Handling in Java

• Input Output Streams
• Java.io Package
• File Handling in Java

Java Collections

• Wrapper Classes and Inner Classes: Integer, Character, Boolean, Float etc
• Applet Programs: How to write UI programs with Applet, Java.lang, Java.io, Java.util
• Collections: ArrayList, Vector, HashSet, TreeSet, HashMap, HashTable

Java Database Connectivity (JDBC)

• Introduction to SQL: Connect, Insert, Update, Delete, Select
• Introduction to JDBC and Architecture of JDBC
• Insert/Update/Delete/Select Operations using JDBC
• Batch Processing Transaction
• Management: Commit and Rollback

Java Enterprise Edition – Servlets

• Introduction to J2EE
• Client Server architecture
• URL, Port Number, Request, Response
• Need for servlets
• Servlet fundamentals
• Setting up a web project in Eclipse
• Configuring and running the web app with servlets
• GET and POST request in web application with demo
• Servlet lifecycle
• Servlets Continued
• Session tracking and filter
• Forward and include Servlet request dispatchers

Java Server Pages (JSP)

• Fundamentals of Java Server Page
• Writing a code using JSP
• The architecture of JSP
• JSP Continued
• JSP elements: Scriptlets, expressions, declaration
• JSP standard actions
• JSP directives
• Introduction to JavaBeans
• ServletConfig and ServletContext
• Servlet Chaining
• Cookies Management
• Session Management

Hibernate

• Introduction to Hibernate
• Introduction to ORM
• ORM features
• Hibernate as an ORM framework
• Hibernate features
• Setting up a project with Hibernate framework
• Basic APIs needed to do CRUD operations with Hibernate
• Hibernate Architecture

POJO (Plain Old Java Object)

• POJO (Plain Old Java Object)
• Persistent Objects
• Lifecycle of Persistent Object

Spring

• Introduction to Spring
• Spring Fundamentals
• Advanced Spring

Got a question for us? Please mention it in the comments section and we will get back to you.

 

0 responses on "Properties class and Generics in Java"

Leave a Message

Your email address will not be published. Required fields are marked *