Java generics Example


Java Generics

Java Generics are a language feature that allows for definition and use of generic types and methods. It is a compilation feature introduced in java 1.5

Example

package com.vinod.test;

import java.util.ArrayList;

public class GenericsTest {
    public static void main(String[] args) {
        ArrayList vlist = new ArrayList();
        vlist.add("Pretech Learning");
        Integer vint = (Integer) vlist.get(0);
        System.out.println(vint);
    }

}
  

Output

Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
at com.vinod.test.GenericsTest.main(GenericsTest.java:9)

The compilation of above program is successful but during the run time we will get class caste exception has occured to avoid this introduced Java Generics, see if we are creating an arraylist and defining the type as String.
package com.vinod.test;

import java.util.ArrayList;

public class GenericsTest {
    public static void main(String[] args) {
        ArrayList<String> vlist = new ArrayList<String>();
        vlist.add("Pretech Learning");
        Integer vint = (Integer) vlist.get(0);
        System.out.println(vint);
    }

}
In this above case compiler will shows the error before running the program.

What is ? Extends and ? Super

First see this below class hierarchy (example) Here Number is the super class of all other classes except Object class

<? Extends E>

The first example we restricted as the Arraylist for only String. Whenever we want define the type as its sub class as well we can use <? Extends E>

Example

 ArrayList<? extends Number> numberList = new ArrayList();
                  numberList = new ArrayList();
                  numberList = new ArrayList();
Here we define as ? extents Number so we can create the type as its subclass Integer and Float.

<? Super E>

The same way we can use it for super class as well

Example

         ArrayList<? super Integer> numberList = new ArrayList();
                  numberList = new ArrayList();
                  numberList = new ArrayList();

Java Serialization / DeSerialization Example

Java program to serialize and deserialize objects
package mycollectiontest;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class SerializationExample {

public static void main(String[] args) {
Customer customer = new Customer("Vinod", "Bangalore");

FileOutputStream fos;
try {
// Serialization
fos = new FileOutputStream(new File("customer.ser"));
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(customer);
oos.flush();
oos.close();

// Deserialization
FileInputStream fis = new FileInputStream("customer.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
Customer decustomer = (Customer) ois.readObject();
ois.close();
System.out.println("Customer after serialization: " + decustomer);
} catch (IOException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

class Customer implements Serializable {
/**
   *
   */
private static final long serialVersionUID = -1943599317632365868L;
private String name;
private String address;

public Customer(String name, String address) {
super();
this.name = name;
this.address = address;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

@Override
public String toString() {
return "Customer [name=" + name + ", address=" + address + "]";
}

}
Output
Customer after serialization: Customer [name=Vinod, address=Bangalore]

 

 

Apache Wicket Hello world example


1. Create a Apache a wicket project


Clik here to get help for create Apache Wicket Project

2. Create Application classes

Apache wicket is working via conventions and there is no configuration needed, but we have to put the class file and html file in right package.

Page java file

This file needs to extend webpage and add the components
package com.mycompany;

import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.WebPage;

public class HomePage extends WebPage {
    private static final long serialVersionUID = 1L;

    public HomePage(final PageParameters parameters) {
        super(parameters);
        add(new Label("message", "Hello world by Java release...."));
    }
}
  

Web application file

This file needs to extend Web application and override getHomePage method

In getHomePage method we have to add our page java file class name
package com.mycompany;

import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.protocol.http.WebApplication;

/**
 * Application object for your web application. If you want to run this
 * application without deploying, run the Start class.
 *
 * @see com.mycompany.Start#main(String[])
 */

public class WicketApplication extends WebApplication {
    /**
     * @see org.apache.wicket.Application#getHomePage()
     */

    @Override
    public Class<? extends WebPage> getHomePage() {
        return HomePage.class;
    }

    /**
     * @see org.apache.wicket.Application#init()
     */

    @Override
    public void init() {
        super.init();

        // add your configuration here
    }
}

Run Start.java and hit the url 

Output

Apache Wicket How to start ?



Apache Wicket

Apache Wicket is a open source lightweight component-based web application framework for the Java programming language conceptually similar to JavaServer Faces and Tapestry.

Softwares Used

  • Eclipse Juno
  • Apache tomcat 6.0
  • Java 7
  • Maven with Wicket quickstart 

1. Create a Maven Project in eclipse.

File->New->Other->Maven->Maven Project

2. Select Wicket quickstart artifact

Or Use the below command to generate the archetype
mvn archetype:generate -DarchetypeGroupId=org.apache.wicket -DarchetypeArtifactId=wicket-archetype-quickstart -DarchetypeVersion=7.2.0 -DgroupId=com.mycompany -DartifactId=myproject -DarchetypeRepository=https://repository.apache.org/ -DinteractiveMode=false

3. Maven Project created with below structure.



4. Deploy this project in Tomcat

Right click on the project->Run As->Tomcat Server  Or Run the Start.java (Which is using Jetty server)

5.  output 


 






References

http://wicket.apache.org/

How to remove babylon toolbar

How to remove Babylon toolbar from browser

Please find the below steps to remove babylon toolbar from browser
image

1. Uninstall all babylon programs

image

2. Delete all babylon related registry files

Start->Run->regedit> then find babylon and delete
image

3. Delete all babylon files (Including babylon.xml)

image
image

4. Remove babylon extensions

Tools->Add-ones
image

4. Rename search engine tab value

Open Mozilla and type about:config and search babylon.We can see all babylon related files and we have to modify all search engine values (eg to http://google.com)
image
image

5. Open Mozilla and check

image

6. Disable add ons from Internet Explorer

image

7. Change default page from internet options

image

8. Open IE and check

image

Java Singleton Pattern Example

🔁 Singleton Pattern in Java 8 — Step-by-Step Guide

The Singleton Pattern ensures that only one instance of a class exists in the JVM and provides a global access point to it.
It’s a classic creational design pattern used when you need exactly one shared object managing global state or resources.


🎯 When & Why to Use a Singleton

Use the Singleton Pattern when:

  • You want to share one object (e.g., configuration manager, cache, logger, connection pool).

  • You need to coordinate actions globally (e.g., central event dispatcher).

  • You must prevent multiple instances that could cause inconsistency or resource conflicts.

✅ Benefits

  • Guarantees a single shared instance

  • Provides controlled access via a static method

  • Saves memory by avoiding duplicate objects

  • Enables lazy initialization

  • Thread-safe options available in Java 8


⚙️ Key Principles

  1. Private constructor prevents external instantiation.

  2. Static instance variable holds the single instance.

  3. Public static method (like getInstance()) provides access.

  4. Optionally, synchronize or use static holder for thread safety.

  5. Class can be made final to prevent subclassing.


🧩 1️⃣ Double-Checked Locking Singleton (Thread-Safe in Java 8)

💡 Why it works

In Java 8, the volatile keyword guarantees visibility and prevents instruction reordering, making the Double-Checked Locking (DCL) approach both lazy and thread-safe.

package com.vinod.patterns; /** * Thread-safe Singleton using Double-Checked Locking. * Works correctly in Java 8 due to 'volatile' semantics. */ public final class VinodSingleton { // Volatile ensures proper visibility across threads private static volatile VinodSingleton instance; // Private constructor prevents instantiation private VinodSingleton() { System.out.println("Singleton instance created!"); } // Global access method public static VinodSingleton getInstance() { if (instance == null) { // First check (no lock) synchronized (VinodSingleton.class) { if (instance == null) { // Second check (with lock) instance = new VinodSingleton(); } } } return instance; } }

🧠 How it works (Step-by-Step)

StepActionDescription
1Class loadsNo instance created yet
2First getInstance() callChecks if instance == null
3Enters synchronized blockOnly first thread proceeds
4Creates new instanceStored in instance
5Later callsSkip synchronization (fast path)

Thread-safe, lazy initialization, and efficient after first access.


🧩 2️⃣ Static Inner Class Singleton (Recommended Java 8 Approach)

💡 Why use it

This approach leverages Java’s class loading mechanism — the inner class isn’t loaded until it’s referenced, making it both lazy and thread-safe without explicit synchronization.

package com.vinod.patterns; /** * Singleton using Inner Static Holder Pattern. * Lazy, thread-safe, and efficient in Java 8. */ public final class VinodHolderSingleton { // Private constructor private VinodHolderSingleton() { System.out.println("Holder-based Singleton instance created!"); } // Inner static class - loaded only when referenced private static class Holder { private static final VinodHolderSingleton INSTANCE = new VinodHolderSingleton(); } // Public access point public static VinodHolderSingleton getInstance() { return Holder.INSTANCE; } }

🧠 Step-by-Step Explanation

  1. VinodHolderSingleton class loads → inner Holder class not loaded yet.

  2. First call to getInstance() triggers loading of Holder.

  3. JVM initializes Holder.INSTANCE exactly once (thread-safe).

  4. Any future call just returns the same instance.

No synchronization overhead and 100 % thread-safe — ideal in Java 8.


🧩 3️⃣ Enum Singleton (Simplest & Reflection-Safe)

💡 Why use it

Since Java 5, the Enum Singleton is the most secure method. It’s serialization-safe, reflection-proof, and inherently thread-safe.

package com.vinod.patterns; /** * Simplest Singleton using Enum. * Safe against serialization and reflection. */ public enum VinodEnumSingleton { INSTANCE; public void showMessage() { System.out.println("Enum Singleton Instance Working!"); } }

Usage:

VinodEnumSingleton.INSTANCE.showMessage();

✅ Automatically prevents:

  • Multiple instances via reflection

  • Duplication via serialization


🧪 Test Program

package com.vinod.patterns; public class SingletonTest { public static void main(String[] args) { System.out.println("Testing Singleton Implementations...\n"); VinodSingleton s1 = VinodSingleton.getInstance(); VinodSingleton s2 = VinodSingleton.getInstance(); VinodHolderSingleton h1 = VinodHolderSingleton.getInstance(); VinodHolderSingleton h2 = VinodHolderSingleton.getInstance(); VinodEnumSingleton e1 = VinodEnumSingleton.INSTANCE; VinodEnumSingleton e2 = VinodEnumSingleton.INSTANCE; System.out.println("\nAre all Singletons identical?"); System.out.println("VinodSingleton: " + (s1 == s2)); System.out.println("VinodHolderSingleton: " + (h1 == h2)); System.out.println("VinodEnumSingleton: " + (e1 == e2)); } }

Sample Output

Testing Singleton Implementations... Singleton instance created! Holder-based Singleton instance created! Enum Singleton Instance Working! Are all Singletons identical? VinodSingleton: true VinodHolderSingleton: true VinodEnumSingleton: true

🧭 Comparison Table

PatternThread-SafeLazy InitReflection-SafeSerialization-SafeRecommended?
Double-Checked Locking👍 Yes
Static Holder⚠️ (use private guard)⚠️ (add readResolve)✅ Best
Enum🚀 Ideal

🧠 Key Takeaways

  • Use Static Inner Class or Enum Singleton for Java 8 — they’re thread-safe and lazy by default.

  • Always prevent external creation via:

    • private constructor

    • final class

    • Reflection guards (optional)

  • Don’t overuse Singleton — prefer dependency injection for testable, scalable systems.

  • For multi-threaded or distributed systems, ensure proper synchronization and avoid static mutable state.


💬 Real-World Example

Use CaseDescription
Logging UtilityOne logger used across all modules.
Configuration ReaderSingle global config object loaded once.
Cache ManagerShared cache across threads.
Connection Pool ManagerCentralized connection provider.

Tapestry Grid Example


Grid

A Grid component represents tablular data, it can be create very easily in tapestry. The Grid component is almost same as BeanEditor component, they are both based on the same underlying concept and sharing some codes.
Grid component class  is org.apache.tapestry5.corelib.components.Grid

Grid Example

Here is one simple example to edit a bean with BeanEditForm and using Grid to see the output.

a. Using BeanEditForm to create/update data
b. Using Grid to view the data
Create template
<html t:type="layout"title="TestArtifact Page"

xmlns:t="http://tapestry.apache.org/schema/tapestry_5_1_0.xsd"

xmlns:p="tapestry:parameter">

<body>

Vinod: Bean Editor example

<t:beaneditform t:id="person"/>
<t:grid source="personbeans"/>
</body>

</html>
Create person object
package vinod.test.model;
public class Person {
private String name;
private String address;
private String country;

public Person(String name, String address, String country) {
super();
this.name = name;
this.address = address;
this.country = country;
}

public Person() {
}

public String getName() {
return this.name;
}

public void setName(String name) {
this.name = name;
}

public String getAddress() {
return this.address;
}

public void setAddress(String address) {
this.address = address;
}

public String getCountry() {
return this.country;
}

public void setCountry(String country) {
this.country = country;
}

}
Create backend java file for template
package vinod.test.pages;

import java.util.ArrayList;
import java.util.List;

import vinod.test.model.Person;

public class BeanEditForm {
Person person = new Person();
List<Person> personbeans = new ArrayList<Person>();

public List<Person> getPersonbeans() {
return this.personbeans;
}

public void setPersonbeans(List<Person> personbeans) {
this.personbeans = personbeans;
}

public Person getPerson() {
return this.person;
}

public void setPerson(Person person) {
this.person = person;
}

Object onSuccess() {
System.out.println("Submit button was pressed!");
personbeans.add(person);

return BeanEditForm.class;
}
}
Output

Reference:

Confusion Matrix + Precision/Recall (Super Simple, With Examples)

  Confusion Matrix + Precision/Recall (Super Simple, With Examples) 1) Binary Classification Setup Binary classification means the model p...

Featured Posts