### Java System.out.println() Example Source: https://www.geeksforgeeks.org/java/java-io-input-output-in-java-with-examples Use System.out.println() to display text on the console and move the cursor to the beginning of the next line. Each subsequent output will start on a new line. ```Java import java.io.*; class Geeks { public static void main(String[] args) { // using println() all are printed in the different line System.out.println("GfG! "); System.out.println("GfG! "); System.out.println("GfG! "); } } ``` -------------------------------- ### Real-World Example: Vehicle Abstraction Source: https://www.geeksforgeeks.org/java/abstract-keyword-in-java Demonstrates how an abstract class 'Vehicle' with an abstract 'start' method can be extended by concrete classes like 'Car' to provide specific implementations. ```Java abstract class Vehicle { abstract void start(); } class Car extends Vehicle { void start() { System.out.println("Car Starts With Key"); } } public class Geeks{ public static void main(String[] args) { Car c = new Car(); c.start(); } } ``` -------------------------------- ### Java Example: Implementing and Using ResponseCache Source: https://www.geeksforgeeks.org/java/java-net-responsecache-class-in-java This example demonstrates how to create a custom ResponseCache implementation, set it as the default system-wide cache, and then use its put and get methods. It requires importing necessary classes from java.net and java.util. ```Java import java.io.IOException; import java.net.*; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; public class JavaResponseCacheExample1 { public static void main(String args[]) throws Exception { // passing the string uri String uri = "https://www.onlinegdb.com"; // Calling the constructor of the URI class URI uri1 = new URI(uri); // passing the url URL url = new URL("http://www.onlinegdb.com"); // calling the constructor of the URLConnection URLConnection urlcon = url.openConnection(); ResponseCache responseCache = new ResponseCache() { // calling the abstract methods @Override public CacheResponse get( URI uri, String rqstMethod, Map > rqstHeaders) throws IOException { return null; } @Override public CacheRequest put(URI uri, URLConnection conn) throws IOException { return null; } }; // The sets the system-wide response cache. ResponseCache.setDefault(responseCache); // The getDefault() method returns // the system-wide ResponseCache . System.out.println("Default value: " + ResponseCache.getDefault()); Map > maps = new HashMap >(); List list = new LinkedList(); list.add("REema"); // put() method sets all the applicable cookies, // present in the response headers into a cookie // cache maps.put("1", list); System.out.println( "The put() method has been called..."); // The put() method returns the // CacheRequest for recording System.out.println( "The put() method returns: " + responseCache.put(uri1, urlcon)); System.out.println( "The get() method has been called..."); // The get() method returns a CacheResponse // instance if it is available System.out.println( "The get() method returns: " + responseCache.get(uri1, uri, maps)); } } ``` -------------------------------- ### Create and Execute Threads using start() and run() Source: https://www.geeksforgeeks.org/java/java-multithreading-tutorial This example demonstrates creating two separate threads by extending the Thread class and executing them using the start() method. Each thread prints a message to the console. ```Java class MyThread1 extends Thread { public void run() { System.out.println("Thread1 is running"); } } class MyThread2 extends Thread { public void run() { System.out.println("Thread2 is running"); } } class GFG { public static void main(String[] args) { MyThread1 obj1 = new MyThread1(); MyThread2 obj2 = new MyThread2(); obj1.start(); obj2.start(); } } ``` -------------------------------- ### Java System setProperty, getProperty, and clearProperty Example Source: https://www.geeksforgeeks.org/java/java-lang-system-class-java Demonstrates how to set, get, and clear system properties using setProperty, getProperty, and clearProperty methods. Useful for managing application configurations. ```Java import java.lang.*; import static java.lang.System.clearProperty; import static java.lang.System.setProperty; import java.util.Arrays; class SystemDemo { public static void main(String args[]) { // checking specific property System.out.println(System.getProperty("user.home")); // clearing this property clearProperty("user.home"); System.out.println(System.getProperty("user.home")); // setting specific property setProperty("user.country", "US"); // checking property System.out.println(System.getProperty("user.country")); // checking property other than system property // illustrating getProperty(String key, String def) System.out.println(System.getProperty("user.password", "none of your business")); } } ``` -------------------------------- ### ProcessBuilder start() Method Source: https://www.geeksforgeeks.org/java/java-lang-processbuilder-class-java Starts a new process using the attributes of the process builder. Handles command execution, working directory, and environment setup. Throws exceptions for invalid commands or security restrictions. ```Java import java.io.*; import java.lang.*; import java.util.*; class ProcessBuilderDemo { public static void main(String[] arg) throws IOException { // creating list of commands List commands = new ArrayList(); commands.add("ls"); // command commands.add("-l"); // command commands.add( "/Users/abhishekverma"); // command in Mac OS // creating the process ProcessBuilder pb = new ProcessBuilder(commands); // starting the process Process process = pb.start(); // for reading the output from stream BufferedReader stdInput = new BufferedReader( new InputStreamReader( process.getInputStream())); String s = null; while ((s = stdInput.readLine()) != null) { System.out.println(s); } } } ``` -------------------------------- ### Establish PostgreSQL Connection in Java Source: https://www.geeksforgeeks.org/java/java-program-to-handle-checked-exception This example demonstrates establishing a connection to a PostgreSQL database using JDBC. It includes a method to get the connection and prints success or failure messages. ```Java // Importing required classes import java.io.*; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; // Class public class sql_excep { // Main driver method public static void main(String[] args) { Connection con = getConnection("javaDb", "postgres", "abrar"); } public static Connection getConnection(String dbname, String user, String pass) throws SQLException { Connection con_obj = null; String url = "jdbc:postgresql://localhost:5432/"; con_obj = DriverManager.getConnection(url + dbname, user, pass); if (con_obj != null) { System.out.println( "Connection established successfully !"); } else { System.out.println("Connection failed !!"); } return con_obj; } } ``` -------------------------------- ### Java Matcher start() Example 1 Source: https://www.geeksforgeeks.org/java/matcher-start-method-in-java-with-examples Demonstrates retrieving the start index of a matched pattern using the start() method. This example uses the regex "(G*k)" on the string "Geeks". ```Java import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = "(G*k)"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Get the String to be matched String stringToBeMatched = "Geeks"; // Create a matcher for the input String Matcher matcher = pattern .matcher(stringToBeMatched); // Get the current matcher state MatchResult result = matcher.toMatchResult(); System.out.println("Current Matcher: " + result); while (matcher.find()) { // Get the first index of match result System.out.println(matcher.start()); } } } ``` -------------------------------- ### Configuration Example Source: https://www.geeksforgeeks.org/java/introduction-to-hibernate-framework Activates the Hibernate framework by reading configuration and mapping files. Use this to load hibernate.cfg.xml. ```java Configuration cfg = new Configuration(); cfg.configure(); // Reads and validates hibernate.cfg.xml ``` -------------------------------- ### Main Test Class Setup Source: https://www.geeksforgeeks.org/java/how-to-create-thread-using-lambda-expressions-in-java Sets up the main class with arrays for games and music tracks, a RandomPlayer instance, and a Random object for selecting items. ```java public class Test { // games and tracks arrays which are being used for // picking random items static String[] games = { "COD", "Prince Of Persia", "GTA-V5", "Valorant", "FIFA 22", "Fortnite" }; static String[] tracks = { "Believer", "Cradles", "Taki Taki", "Sorry", "Let Me Love You" }; public static void main(String[] args) { RandomPlayer player = new RandomPlayer(); // Instance of // RandomPlayer to access // its functionalities // Random class for choosing random items from above // arrays Random random = new Random(); // Creating two lambda expressions for runnable // interfaces ``` -------------------------------- ### Java EnumMap entrySet() Example Source: https://www.geeksforgeeks.org/java/enummap-entryset-method-in-java Demonstrates how to use the entrySet() method to get a set view of an EnumMap. This example uses a custom enum 'rank_countries'. ```Java import java.util.*; // An enum of gfg rank is created public enum rank_countries { India, United_States, China, Japan, Canada, Russia } ; class Enum_map { public static void main(String[] args) { EnumMap mp = new EnumMap(rank_countries.class); // Values are associated in mp mp.put(rank_countries.India, 72); mp.put(rank_countries.United_States, 1083); mp.put(rank_countries.China, 4632); mp.put(rank_countries.Japan, 6797); // Map view System.out.println("Map view: " + mp); // Creating a new set of the mappings // contained in map Set > set_view = mp.entrySet(); // Set view of the mappings System.out.println("Set view of the map: " + set_view); } } ``` -------------------------------- ### Java Matcher start() Example 2 Source: https://www.geeksforgeeks.org/java/matcher-start-method-in-java-with-examples Illustrates the start() method with a different regex, "(G*G)", applied to the string "GFG". This shows how the method captures multiple match start indices. ```Java import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = "(G*G)"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Get the String to be matched String stringToBeMatched = "GFG"; // Create a matcher for the input String Matcher matcher = pattern .matcher(stringToBeMatched); // Get the current matcher state MatchResult result = matcher.toMatchResult(); System.out.println("Current Matcher: " + result); while (matcher.find()) { // Get the first index of match result System.out.println(matcher.start()); } } } ``` -------------------------------- ### Illustrating setOut(), setIn(), and setErr() Methods Source: https://www.geeksforgeeks.org/java/java-lang-system-class-java This comprehensive example shows how to use System.setOut(), System.setIn(), and System.setErr() to redirect standard input, output, and error streams to files. It requires 'input.txt' for input and creates 'system.txt' for output. ```Java import java.lang.*; import java.util.Properties; import java.io.*; class SystemDemo { public static void main(String args[]) throws IOException { FileInputStream IN = new FileInputStream("input.txt"); FileOutputStream OUT = new FileOutputStream("system.txt"); // set input stream System.setIn(IN); char c = (char) System.in.read(); System.out.print(c); // set output stream System.setOut(new PrintStream(OUT)); System.out.write("Hi Abhishek\n".getBytes()); // set error stream System.setErr(new PrintStream(OUT)); System.err.write("Exception message\n".getBytes()); } } ``` -------------------------------- ### Java Matcher end(1) Example Source: https://www.geeksforgeeks.org/java/matcher-endint-method-in-java-with-examples Demonstrates how to use the end(1) method to get the offset after the end of the first capturing group. This example finds matches for '(G*s)' in 'GeeksForGeeks'. ```Java import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = "(G*s)"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Get the String to be matched String stringToBeMatched = "GeeksForGeeks"; // Create a matcher for the input String Matcher matcher = pattern .matcher(stringToBeMatched); // Get the current matcher state MatchResult result = matcher.toMatchResult(); System.out.println("Current Matcher: " + result); while (matcher.find()) { // Get the last index of match result System.out.println(matcher.end(1)); } } } ``` -------------------------------- ### Get First Element from Integer List with Optional Handling Source: https://www.geeksforgeeks.org/java/stream-findfirst-java-examples This example shows how to use Stream.findFirst() with a list of integers and safely access the result using isPresent() and get() on the returned Optional. ```Java import java.util.*; class GFG { public static void main(String[] args) { List list = Arrays.asList(3, 5, 7, 9, 11); Optional answer = list.stream().findFirst(); if (answer.isPresent()) { System.out.println(answer.get()); } else { System.out.println("no value"); } } } ``` -------------------------------- ### Java notify() Method Example Source: https://www.geeksforgeeks.org/java/java-notify-method-in-threads-synchronization-with-examples Demonstrates how to use the notify() method to wake up a single waiting thread in Java. This example requires no specific setup beyond standard Java imports. ```Java // Java program to Illustrate notify() method in Thread // Synchronization. // Importing required classes import java.io.*; import java.util.*; // Class 1 // Thread1 // Helper class extending Thread class public class GFG { // Main driver method public static void main(String[] args) { // Creating object(thread) of class 2 Thread2 objB = new Thread2(); // Starting the thread objB.start(); synchronized (objB) { // Try block to check for exceptions try { // Display message only System.out.println( "Waiting for Thread 2 to complete..."); // wait() method for thread to be in waiting // state objB.wait(); } // Catch block to handle the exceptions catch (InterruptedException e) { // Print the exception along with line // number using printStackTrace() method e.printStackTrace(); } // Print and display the total threads on the // console System.out.println("Total is: " + objB.total); } } } // Class 2 // Thread2 // Helper class extending Thread class class Thread2 extends Thread { int total; // run() method which is called automatically when // start() is initiated for the same // @Override public void run() { synchronized (this) { // iterating over using the for loo for (int i = 0; i < 10; i++) { total += i; } // Waking up the thread in waiting state // using notify() method notify(); } } } ``` -------------------------------- ### Create a new directory using mkdirs() Source: https://www.geeksforgeeks.org/java/file-mkdirs-method-in-java-with-examples Demonstrates the basic usage of the File.mkdirs() method to create a single directory. Ensure you have write permissions for the target drive. ```Java import java.io.*; public class GFG { public static void main(String args[]) { // create an abstract pathname (File object) File f = new File("F:\\program"); // check if the directory can be created // using the abstract path name if (f.mkdirs()) { // display that the directory is created // as the function returned true System.out.println("Directory is created"); } else { // display that the directory cannot be created // as the function returned false System.out.println("Directory cannot be created"); } } } ``` -------------------------------- ### Create a Basic 'Hello World' Applet Source: https://www.geeksforgeeks.org/java/java-applet-basics This snippet shows how to create a simple 'Hello World' applet. It includes the necessary import statements, an APPLET tag comment for documentation, and the basic structure of an Applet class with a paint method. ```java // A Hello World Applet // Save file as HelloWorld.java import java.applet.Applet; import java.awt.Graphics; /* */ // HelloWorld class extends Applet public class HelloWorld extends Applet { // Overriding paint() method @Override public void paint(Graphics g) { g.drawString("Hello World", 20, 20); } } ``` -------------------------------- ### Java Matcher start(0) Example Source: https://www.geeksforgeeks.org/java/matcher-startint-method-in-java-with-examples Illustrates retrieving the start index of the entire match (group 0) using `matcher.start(0)` within a loop that finds all occurrences. This is commonly used to find the starting positions of all full matches of a pattern in a string. ```Java import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = "(G*G)"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Get the String to be matched String stringToBeMatched = "GFGFGFGFGFGFGFGFGFG"; // Create a matcher for the input String Matcher matcher = pattern .matcher(stringToBeMatched); // Get the current matcher state MatchResult result = matcher.toMatchResult(); System.out.println("Current Matcher: " + result); while (matcher.find()) { // Get the first index of match result System.out.println(matcher.start(0)); } } } ``` -------------------------------- ### Java Matcher start(1) Example Source: https://www.geeksforgeeks.org/java/matcher-startint-method-in-java-with-examples Demonstrates retrieving the start index of the first capturing group (group 1) using `matcher.start(1)` after finding a match. This is useful when your regex contains multiple capturing groups and you need the start index of a specific one. ```Java import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = "(G*s)"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Get the String to be matched String stringToBeMatched = "GeeksForGeeks"; // Create a matcher for the input String Matcher matcher = pattern .matcher(stringToBeMatched); // Get the current matcher state MatchResult result = matcher.toMatchResult(); System.out.println("Current Matcher: " + result); while (matcher.find()) { // Get the first index of match result System.out.println(matcher.start(1)); } } } ``` -------------------------------- ### Java Math ulp(), log1p() Example Source: https://www.geeksforgeeks.org/java/java-lang-math-class-java-set-2 Demonstrates the usage of Math.ulp() and Math.log1p() methods. Ensure java.lang.* is imported. ```Java import java.lang.*; public class NewClass { public static void main(String args[]) { // Use of ulp() method double x = 34.652, y = -23.34789; double u = Math.ulp(x); System.out.println("ulp of 34.652 : "+u); u = Math.ulp(y); System.out.println("ulp of -23.34789 : "+u); System.out.println(""); // Use of log() method double l = 99; double l1 = Math.log1p(l); System.out.println("Log of (1 + 99) : "+l1); l1 = Math.log(100); System.out.println("Log of 100 : "+l1); } } ``` -------------------------------- ### Java CookieManager and CookieStore Example Source: https://www.geeksforgeeks.org/java/java-net-cookiestore-class-in-java Demonstrates the usage of CookieManager and CookieStore to add, retrieve, and remove HTTP cookies. This example covers methods like add(), get(), getCookies(), getURIs(), remove(), and removeAll(). ```Java import java.io.*; import java.net.*; import java.util.*; public class GFG { public static void main(String[] args) { // CookieManager and CookieStore CookieManager cookieManager = new CookieManager(); CookieStore cookieStore = cookieManager.getCookieStore(); // creating cookies and URI HttpCookie cookieA = new HttpCookie("First", "1"); HttpCookie cookieB = new HttpCookie("Second", "2"); URI uri = URI.create("https://www.geeksforgeeks.org/"); // Method 1 - add(URI uri, HttpCookie cookie) cookieStore.add(uri, cookieA); cookieStore.add(null, cookieB); System.out.println( "Cookies successfully added\n"); // Method 2 - get(URI uri) List cookiesWithURI = cookieStore.get(uri); System.out.println( "Cookies associated with URI in CookieStore : " + cookiesWithURI + "\n"); // Method 3 - getCookies() List cookieList = cookieStore.getCookies(); System.out.println("Cookies in CookieStore : " + cookieList + "\n"); // Method 4 - getURIs() List uriList = cookieStore.getURIs(); System.out.println("URIs in CookieStore" + uriList + "\n"); // Method 5 - remove(URI uri, HttpCookie cookie) System.out.println( "Removal of Cookie : " + cookieStore.remove(uri, cookieA)); List remainingCookieList = cookieStore.getCookies(); System.out.println( "Remaining Cookies : " + cookieList + "\n"); // Method 6 - removeAll() System.out.println("Removal of all Cookies : " + cookieStore.removeAll()); List EmptyCookieList = cookieStore.getCookies(); System.out.println( "Empty CookieStore : " + cookieList); } } ``` -------------------------------- ### Initialize Object Using Constructor Source: https://www.geeksforgeeks.org/java/classes-objects-java This example shows how to define a `Product` class with a constructor and then instantiate two `Product` objects with different values. It demonstrates accessing object properties using getter methods. ```Java class Product { String name; float price; // Constructor to initialize object state public Product(String name, float price) { this.name = name; this.price = price; } // Setter methods (optional) public void setName(String name) { this.name = name; } public void setPrice(float price) { this.price = price; } // Getter methods public String getName() { return name; } public float getPrice() { return price; } } public class Main { public static void main(String[] args) { Product p1 = new Product("Visual Studio", 0.0f); Product p2 = new Product("IntelliJ IDEA", 4999.0f); System.out.println(p1.getName() + " - " + p1.getPrice()); System.out.println(p2.getName() + " - " + p2.getPrice()); } } ``` -------------------------------- ### Creating a Properties File in Java Source: https://www.geeksforgeeks.org/java/java-util-properties-class-java Demonstrates how to create a new properties file ('info.properties') and populate it with key-value pairs using the setProperty() and store() methods of the Properties class. ```Java // Java program to demonstrate Properties class to create // the properties file import java.util.*; import java.io.*; public class GFG { public static void main(String[] args) throws Exception { // create an instance of Properties Properties p = new Properties(); // add properties to it p.setProperty("name", "Ganesh Chowdhary Sadanala"); p.setProperty("email", "ganeshs.gfg@gmail.com"); // store the properties to a file p.store(new FileWriter("info.properties"), "GeeksforGeeks Properties Example"); } } ``` -------------------------------- ### Retrieve Match Positions with Index Methods in Java Source: https://www.geeksforgeeks.org/java/matcher-class-in-java Use start() and end() methods to get the start and end indices of a match and its captured groups. Ensure a match is found using find() before calling these methods. ```Java import java.util.regex.*; public class GFG { public static void main(String[] args) { Pattern pattern = Pattern.compile("(java)"); Matcher matcher = pattern.matcher("I love java"); if (matcher.find()) { System.out.println(matcher.start()); System.out.println(matcher.end()); System.out.println(matcher.start(1)); System.out.println(matcher.end(1)); } } } ``` -------------------------------- ### Create and Populate Hashtable in Java Source: https://www.geeksforgeeks.org/java/hashtable-in-java Demonstrates how to create a Hashtable with String keys and Integer values, add elements using the put() method, and print the Hashtable's contents. This example requires importing java.util.Hashtable. ```java import java.util.Hashtable; public class GFG { public static void main(String args[]) { // Create a Hashtable of String // keys and Integer values Hashtable ht = new Hashtable<>(); // Adding elements to the Hashtable ht.put("One", 1); ht.put("Two", 2); ht.put("Three", 3); // Displaying the Hashtable elements System.out.println("Hashtable Elements: " + ht); } } ``` -------------------------------- ### Basic Stack Operations (Push and Pop) Source: https://www.geeksforgeeks.org/java/stack-class-in-java Demonstrates creating a Stack, pushing integer elements onto it, and then popping them off in LIFO order until the stack is empty. This example highlights the fundamental push and pop operations. ```Java import java.util.Stack; public class Geeks { public static void main(String[] args) { // Create a new stack Stack s = new Stack<>(); // Push elements onto the stack s.push(1); s.push(2); s.push(3); s.push(4); // Pop elements from the stack while (!s.isEmpty()) { System.out.println(s.pop()); } } } ``` -------------------------------- ### Java Method hashCode() Example Source: https://www.geeksforgeeks.org/java/method-class-hashcode-method-in-java Demonstrates how to get the hash code of a specific method object obtained using getDeclaredMethod(). ```Java /* * Program Demonstrate hashcode() method of Method Class. */ import java.lang.reflect.Method; public class GFG { // create a Method name getSampleMethod public void getSampleMethod() {} // create main method public static void main(String args[]) { try { // create class object for class name GFG Class c = GFG.class; // get Method object of method name getSampleMethod Method method = c.getDeclaredMethod("getSampleMethod", null); // get hashcode of method object using hashCode() method int hashCode = method.hashCode(); // Print hashCode with method name System.out.println("hashCode of method " + method.getName() + " is " + hashCode); } catch (Exception e) { // print if any exception occurs e.printStackTrace(); } } } ``` -------------------------------- ### Create a new directory using mkdir() Source: https://www.geeksforgeeks.org/java/file-mkdir-method-in-java-with-examples This example demonstrates how to create a new directory named 'program' in the 'F:' drive using the mkdir() method. It checks the boolean return value to confirm creation. ```Java // Java program to demonstrate // the use of File.mkdirs() method import java.io.*; public class GFG { public static void main(String args[]) { // create an abstract pathname (File object) File f = new File("F:\\program"); // check if the directory can be created // using the abstract path name if (f.mkdir()) { // display that the directory is created // as the function returned true System.out.println("Directory is created"); } else { // display that the directory cannot be created // as the function returned false System.out.println("Directory cannot be created"); } } } ``` -------------------------------- ### Demonstrating run() vs start() in Java Multithreading Source: https://www.geeksforgeeks.org/java/start-function-multithreading-java This example illustrates the behavior when run() is called directly instead of start(). It shows that all executions occur on the main thread, resulting in the same thread ID being printed repeatedly, highlighting the absence of actual multithreading. ```Java class ThreadTest extends Thread { public void run() { try { // Displaying the thread that is running System.out.println ("Thread " + Thread.currentThread().getId() + " is running"); } catch (Exception e) { // Throwing an exception System.out.println ("Exception is caught"); } } } // Main Class public class Main { public static void main(String[] args) { int n = 8; for (int i=0; i m = new HashMap<>(); Set s = new HashSet<>(); // Adding elements of HashMap m.put(1, "One"); m.put(3, "Three"); m.put(5, "Five"); m.put(7, "Seven"); m.put(9, "Nine"); System.out.println(m); // Storing keys in Set s = m.keySet(); System.out.println(s); } } ``` -------------------------------- ### Java AWT Panel Example Source: https://www.geeksforgeeks.org/java/java-awt-panel Demonstrates creating and using AWT Panels to group components within a Frame. Shows how to set layout managers and background colors for panels. ```Java // Java Program to implement // AWT Panel import java.awt.*; import java.awt.event.*; // Driver Class public class PanelExample { // main function public static void main(String[] args) { Frame frame = new Frame("Java AWT Panel Example"); Panel panel1 = new Panel(); Panel panel2 = new Panel(); // Set the layout manager for panel1 panel1.setLayout(new FlowLayout()); // Add components to panel1 Button button1 = new Button("Button 1"); Button button2 = new Button("Button 2"); panel1.add(button1); panel1.add(button2); // Set background colors for panels panel1.setBackground(Color.CYAN); panel2.setBackground(Color.MAGENTA); // Add panels to the frame frame.add(panel1); frame.add(panel2); frame.setSize(400, 200); frame.setLayout(new FlowLayout()); frame.setVisible(true); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { System.exit(0); } }); } } ``` -------------------------------- ### Java Matcher lookingAt() Example 2 Source: https://www.geeksforgeeks.org/java/matcher-lookingat-method-in-java-with-examples Illustrates the lookingAt() method with a repeating pattern at the start of the string. Ensure the java.util.regex.* package is imported. ```Java import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = "GFG"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Get the String to be matched String stringToBeMatched = "GFGFGFGFGFGFGFGFGFG"; // Create a matcher for the input String Matcher matcher = pattern .matcher(stringToBeMatched); // Get the possible result // using lookingAt() method System.out.println(matcher.lookingAt()); } } ``` -------------------------------- ### Basic TextField Initialization Source: https://www.geeksforgeeks.org/java/java-awt-textfield Demonstrates creating a TextField with default settings. ```java TextField tf = new TextField(); ``` -------------------------------- ### Java Class.forName() Example Source: https://www.geeksforgeeks.org/java/java-lang-class-class-java-set-1 Demonstrates using Class.forName() to get a Class object for a specified class name, including initialization and class loader. ```java // Java program to demonstrate forName() method public class Test { public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName("Test"); ClassLoader loader = myClass.getClassLoader(); // forName method // it returns the Class object for the class // with the specified name using the given class loader Class c = Class.forName("java.lang.String",true,loader); System.out.print("Class represented by c : " + c.toString()); } } ``` -------------------------------- ### Demonstrate HashMap keySet() Method Source: https://www.geeksforgeeks.org/java/hashmap-keyset-method-in-java This snippet shows how to create a HashMap, add key-value pairs, display the map's contents, and then retrieve the set of keys using the `keySet()` method. ```Java // Java program to demonstrate the working of keySet() import java.util.HashMap; public class Geeks { public static void main(String[] args) { // Creating an empty HashMap HashMap m = new HashMap<>(); // Adding key-value pairs m.put(1, "Geeks"); m.put(2, "For"); m.put(3, "Geeks"); m.put(4, "Welcomes"); m.put(5, "You"); // Displaying the HashMap System.out.println("Initial Mappings: " + m); // Using keySet() to get the set view of keys System.out.println("The keys are: " + m.keySet()); } } ``` -------------------------------- ### Class and Interface Naming Example Source: https://www.geeksforgeeks.org/java/java-naming-conventions Classes and interfaces should be named using PascalCase, with each word starting with a capital letter. Names should be descriptive and avoid acronyms. ```Java class Student { } class Integer { } class Scanner { } interface Runnable { } interface Remote { } interface Serializable { } ``` -------------------------------- ### Adding and Accessing Elements in NavigableMap Source: https://www.geeksforgeeks.org/java/navigablemap-interface-in-java-with-example Demonstrates how to add elements to a NavigableMap using put() and access them using get(). This example uses TreeMap as the concrete implementation. ```Java import java.util.*; public class Geeks { public static void main(String[] args) { // Instantiate an object // Since NavigableMap is an interface // We use TreeMap NavigableMap map = new TreeMap(); // Add elements using put() map.put(3, "Third"); map.put(2, "Second"); map.put(1, "First"); map.put(4, "Fourth"); // Accessing the elements using get() // with key as a parameter System.out.println(map.get(1)); System.out.println(map.get(3)); System.out.println("NavigableMap: " + map.keySet()); } } ``` -------------------------------- ### Create and Populate Array of Objects in Java Source: https://www.geeksforgeeks.org/java/arrays-in-java This example demonstrates creating an array of custom 'Student' objects. It shows how to allocate memory for the array, instantiate each object using its constructor, and store references in the array. ```java class Student { public int roll_no; public String name; Student(int roll_no, String name){ this.roll_no = roll_no; this.name = name; } } public class Geeks { public static void main(String[] args){ // declares an Array of Student Student[] arr; // allocating memory for 5 objects of type Student. arr = new Student[5]; // initialize the elements of the array arr[0] = new Student(1, "aman"); arr[1] = new Student(2, "vaibhav"); arr[2] = new Student(3, "shikar"); arr[3] = new Student(4, "dharmesh"); arr[4] = new Student(5, "mohit"); // accessing the elements of the specified array for (int i = 0; i < arr.length; i++) System.out.println("Element at " + i + " : { " + arr[i].roll_no + " " + arr[i].name+" }"); } } ``` -------------------------------- ### Basic Java AWT Choice Component Setup Source: https://www.geeksforgeeks.org/java/java-awt-choice-class This snippet shows the basic setup for a Java AWT Choice component, including adding items, listeners, and integrating it into a frame. ```Java import java.awt.*; import java.awt.event.*; import java.applet.*; public class choice_example extends Applet implements ItemListener, ActionListener { Choice c; Label l; TextField tf; Button b; Panel p; Frame f; public void init() { // create a frame f = new Frame("Choice Example"); // create a panel p = new Panel(); // create a choice, add item listener, and add item c = new Choice(); c.add("C++"); c.add("Java"); c.add("Python"); // create textfield tf = new TextField(10); // create a button Button b = new Button("ok"); // add actionListener b.addActionListener(this); // add itemListener to it c.addItemListener(this); // create a label l = new Label(); Label l1 = new Label("add names"); // set the label text l.setText(c.getSelectedItem() + " selected"); // add choice to panel p.add(c); p.add(l); p.add(l1); p.add(tf); p.add(b); // add panel to the frame f.add(p); // add item listener f.addItemListener(this); // add action listener f.addActionListener(this); // show the frame f.show(); f.setSize(250, 300); } // if an item is selected public void itemStateChanged(ItemEvent e) { l.setText(c.getSelectedItem() + " selected"); } // if button is pressed public void actionPerformed(ActionEvent e) { // add item to the choice c.add(tf.getText()); } } ``` -------------------------------- ### Variable Naming Example Source: https://www.geeksforgeeks.org/java/java-naming-conventions Variable names should be short, meaningful, and mnemonic. Avoid starting with underscores or dollar signs. Single-character names are acceptable only for temporary variables. ```Java int[] marks; double answer; ``` -------------------------------- ### Java ConcurrentSkipListSet subSet() Example Source: https://www.geeksforgeeks.org/java/concurrentskiplistset-subset-method-in-java Demonstrates creating a subset of a ConcurrentSkipListSet with inclusive start and exclusive end elements. The subset reflects changes in the original set. ```Java // Java program to demonstrate subSet() // method of ConcurrentSkipListSet // Java Program Demonstrate subSet() // method of ConcurrentSkipListSet */ import java.util.NavigableSet; import java.util.concurrent.ConcurrentSkipListSet; class ConcurrentSkipListSetSubSetExample1 { public static void main(String[] args) { // Initializing the set ConcurrentSkipListSet set = new ConcurrentSkipListSet(); // Adding elements to this set for (int i = 0; i <= 10; i++) set.add(i); // Printing the elements of the set System.out.println("Contents of the set: " + set); // Creating a subsetset object NavigableSet sub_set = set.subSet(2, 8); // Printing the elements of the descending set System.out.println("Contents of the subset: " + sub_set); } } ``` -------------------------------- ### Basic HashSet Creation and Element Addition in Java Source: https://www.geeksforgeeks.org/java/hashset-in-java Demonstrates how to create a HashSet of integers, add elements (including duplicates which are ignored), and print its size and contents. This snippet requires importing the java.util.* package. ```java import java.util.*; class GFG { public static void main(String[] args) { // Instantiate an object of HashSet HashSet hs = new HashSet<>(); // Adding elements hs.add(1); hs.add(2); hs.add(1); System.out.println("HashSet Size: " + hs.size()); System.out.println("Elements in HashSet: " + hs); } } ``` -------------------------------- ### Java ConcurrentSkipListSet pollFirst() Example Source: https://www.geeksforgeeks.org/java/concurrentskiplistset-pollfirst-method-in-java Demonstrates retrieving and removing the first element from a non-empty ConcurrentSkipListSet. Ensure the set is populated before calling pollFirst() to get an element. ```Java import java.util.concurrent.*; class ConcurrentSkipListSetpollFirstExample1 { public static void main(String[] args) { // Creating a set object ConcurrentSkipListSet Lset = new ConcurrentSkipListSet(); // Adding elements to this set for (int i = 10; i <= 50; i += 10) Lset.add(i); // Printing the content of the set System.out.println("Contents of the set: " + Lset); // Retrieving and removing first element of the set System.out.println("The first element of the set: " + Lset.pollFirst()); // Printing the content of the set after pollFirst() System.out.println("Contents of the set after pollFirst: " + Lset); } } ``` -------------------------------- ### Java Object Instantiation Example Source: https://www.geeksforgeeks.org/java/classes-objects-java Defines a Product class with a constructor and demonstrates creating multiple objects with independent states. Use getter methods to access individual object properties. ```Java class Product { String name; double price; // Constructor Product(String name, double price) { this.name = name; this.price = price; } // Getter methods String getName() { return name; } double getPrice() { return price; } } public class Main { public static void main(String[] args) { // Creating objects (instances) of the Product class Product p1 = new Product("Laptop", 1200.50); Product p2 = new Product("Mouse", 25.75); // Accessing properties of each object using getter methods System.out.println("Product 1: " + p1.getName() + ", Price: " + p1.getPrice()); System.out.println("Product 2: " + p2.getName() + ", Price: " + p2.getPrice()); } } ``` -------------------------------- ### Get Size of LinkedList using AbstractCollection.size() Source: https://www.geeksforgeeks.org/java/abstractcollection-size-method-in-java-with-examples This example shows how to obtain the size of a LinkedList using the AbstractCollection.size() method. It adds elements to the LinkedList and then prints the count. ```Java import java.util.*; import java.util.AbstractCollection; public class AbstractCollectionDemo { public static void main(String args[]) { // Creating an empty Collection AbstractCollection abs = new LinkedList(); // Using add() method to add // elements in the Collection abs.add("Geeks"); abs.add("for"); abs.add("Geeks"); abs.add("10"); abs.add("20"); // Displaying the Collection System.out.println("Collection:" + abs); // Displaying the size of the Collection System.out.println("The size of the Collection is: " + abs.size()); } } ``` -------------------------------- ### Demonstrate CookieHandler Usage Source: https://www.geeksforgeeks.org/java/java-net-cookiehandler-class-in-java This example demonstrates how to set a default CookieHandler using CookieManager, open a URL connection, and retrieve cookies from the CookieStore. Ensure you have a network connection to fetch cookies. ```Java import java.net.CookieHandler; import java.net.CookieManager; import java.net.CookieStore; import java.net.HttpCookie; import java.net.URL; import java.net.URLConnection; import java.util.List; public class JavaCookieHandlerExample1 { public static void main(String args[]) throws Exception { String uri = "https://www.google.com"; // Instantiate CookieManager; CookieManager c = new CookieManager(); // First set the default cookie manager. CookieHandler.setDefault(c); URL url = new URL(uri); // All the following subsequent URLConnections // will use the same cookie manager. URLConnection connection = url.openConnection(); connection.getContent(); // Get cookies from underlying CookieStore CookieStore cookieStore = c.getCookieStore(); List cookieList = cookieStore.getCookies(); for (HttpCookie cookie : cookieList) { // Get domain set for the cookie System.out.println("The domain is: " + cookie.getDomain()); } } } ```