Sunday, 24 August 2025

ENUM

Enum

Enums were introduced in Java 5 (JDK 1.5) as a way to define a collection of named constants in a type-safe manner. Unlike enums in older languages (like C or C++), Java enums are far more powerful since they are implemented using class concepts and can contain constructors, methods, and variables.

What is an Enum?

  • Enum is a special data type used to define a group of named constants.
  • Each enum constant is implicitly:

    • public, static, and final.
  • Enums make the code readable, maintainable, and less error-prone compared to using int or String constants.
Example :

enum Month {
    JAN, FEB, MAR, DEC;
}

Internal Implementation of Enum

  • Internally, an enum is implemented as a class.
  • Every enum constant is a reference variable that points to its own enum object.
  • You can think of enums as a fixed set of static final objects.

Enum Declaration and Usage :

enum Month{
    JAN, FEB, MAR, DEC; // semicolon at the end is optional if no extra members
}

class Test {
    public static void main(String[] args) {
        Month mon = Month.FEB;
        System.out.println(mon);
    }
}
Output:

FEB
๐Ÿ‘‰ Note: Since enum constants are implicitly static, we can access them using EnumName.CONSTANT.

Enum with Switch Statement :

Before Java 5, switch allowed only byte, short, char, int (and their wrappers). From Java 5 onwards, enum types can also be used in a switch.

Example:

enum PaymentStatus {
    PENDING, PROCESSING, SUCCESS, FAILED;
}

class Test {
    public static void main(String[] args) {
        PaymentStatus status = PaymentStatus.PROCESSING;

        switch (status) {
            case PENDING:
                System.out.println("Payment is pending. Please wait...");
                break;
            case PROCESSING:
                System.out.println("Payment is being processed. Do not refresh the page.");
                break;
            case SUCCESS:
                System.out.println("Payment successful! Thank you for your purchase.");
                break;
            case FAILED:
                System.out.println("Payment failed. Please try again.");
                break;
            default:
                System.out.println("Unknown payment status.");
        }
    }
}
Output :

Payment is being processed. Do not refresh the page.
๐Ÿ‘‰ Every case label must be a valid enum constant, otherwise you’ll get a compile-time error.

Enum and Inheritance

  • Every enum in Java is implicitly a child of java.lang.Enum.
  • Hence, enums cannot extend other classes.
  • Enums are implicitly final, so they cannot be extended.
  • But enums can implement interfaces.

Useful Enum Methods

  1. values() returns all constants as an array.
  2. ordinal() returns the index (zero-based position) of the constant.
  3. valueOf(String name) returns the enum constant with the specified name 

values():

  • Returns an array containing all the constants of the enum, in the order they were declared.
  • Automatically added by the compiler for every enum type.
  • Return type: EnumType[]
๐Ÿ“Œ Syntax :
    
  public static EnumType[] values()

ordinal():

  • Returns the position (zero-based index) of the enum constant in its declaration.
  • Return type: int
  • Use case: Helpful when you need the position/order of the enum constant (e.g., for iteration or sorting).

valueOf(String name)

  • Returns the enum constant with the specified name.
  • The name must exactly match the declared constant (case-sensitive).
  • Return type: EnumType
  • Use case: Useful for converting a string into the corresponding enum constant.
๐Ÿ“Œ Syntax :
    
  public static EnumType valueOf(String name)

๐Ÿ“ŒEample :

  enum Day {
    MONDAY, TUESDAY, WEDNESDAY;
}

class Test {
    public static void main(String[] args) {
        // Using the compiler-generated method
        Day d1 = Day.valueOf("MONDAY");

        // Using Enum.valueOf (generic)
        Day d2 = Enum.valueOf(Day.class, "TUESDAY");

        System.out.println(d1); 
        System.out.println(d2); 
    }
}

Output :

MONDAY
TUESDAY

⚠️ Important Note:

  • If the string doesn’t match exactly, it throws IllegalArgumentException.
  • "monday" (lowercase) would fail because enum names are case-sensitive.

๐Ÿ“Œ Important Notes

  • The name must match the enum constant exactly (case-sensitive).
  • If the string doesn’t match any constant, it throws IllegalArgumentException.
  • null input throws NullPointerException.

✅ So yes, valueOf(String name) is always available for enums in Java, either via the compiler-generated method or the generic Enum.valueOf() method.

๐Ÿ“ŒNote : 

  • ordinal() is defined in the java.lang.Enum class.
  • valueOf(String) is also defined in the Enum class. 
  • values() is not defined in Enum; instead, it is a synthetic method automatically generated by the compiler for each enum type. That’s why you won’t find it in the JDK source of Enum.


enum Day {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}

class Test {
    public static void main(String[] args) {
        Day[] days = Day.values();
        for (Day d : days) {
            System.out.println(d + " ---> " + d.ordinal());
        }
    }
}
Output :

MONDAY ---> 0
TUESDAY ---> 1
WEDNESDAY ---> 2
THURSDAY ---> 3
FRIDAY ---> 4
SATURDAY ---> 5
SUNDAY ---> 6

✅ Key Differences :

Featureordinal()valueOf(String name)values()
PurposeReturns index (position) of constantReturns enum constant by its nameReturns an array of all enum constants
Return TypeintEnum type itselfEnum array (EnumType[])
InputNo input (called on enum constant)Takes String argumentNo input (called on enum type)
Example UsageDay.MONDAY.ordinal()0Day.valueOf("MONDAY")Day.MONDAYDay.values()[MONDAY, TUESDAY, …]
RiskChanges if enum order is modifiedThrows IllegalArgumentException if not foundNone (safe, but array order depends on enum order)

Enum with Constructors and Fields

Each enum constant is actually an object, and constructors are executed at class loading time.

enum UserRole {
    ADMIN(5), MODERATOR(3), CUSTOMER(1), GUEST;

    private int accessLevel;

    // parameterized constructor
    UserRole(int accessLevel) {
        this.accessLevel = accessLevel;
    }

    // default constructor (for GUEST)
    UserRole() {
        this.accessLevel = 0;
    }

    public int getAccessLevel() {
        return accessLevel;
    }
}

class Test {
    public static void main(String[] args) {
        for (UserRole role : UserRole.values()) {
            System.out.println(role + " has access level " + role.getAccessLevel());
        }
    }
}
Output :

ADMIN has access level 5
MODERATOR has access level 3
CUSTOMER has access level 1
GUEST has access level 0
Note :๐Ÿ‘‰ You cannot create enum objects manually (new UserRole() is not allowed). They are created internally at load time.
         ๐Ÿ‘‰ This way, each UserRole constant represents a real application role with an access level (like permissions in a system).

Enum with Methods

Enums can override methods just like classes.

Example:

enum NotificationType {
    EMAIL {
        @Override
        public void send() {
            System.out.println("Sending Email Notification...");
        }
    },
    SMS {
        @Override
        public void send() {
            System.out.println("Sending SMS Notification...");
        }
    },
    PUSH; // uses default implementation
    // default behavior
    public void send() {
        System.out.println("Sending Push Notification...");
    }
}

class Test {
    public static void main(String[] args) {
        for (NotificationType type : NotificationType.values()) {
            type.send();
        }
    }
}
Output :

Sending Email Notification...
Sending SMS Notification...
Sending Push Notification...

Static Import with Enum

You can use static imports to avoid qualifying enum constants.

package pack1;
public enum Fish {
    STAR, GUPPY;
}
package pack2;
import static pack1.Fish.*;

class A {
    public static void main(String[] args) {
        System.out.println(STAR);
        System.out.println(GUPPY);
    }
}

Valid imports:

  1. import static pack1.Fish.*;

  2. import static pack1.Fish.STAR;

Invalid imports:

  1. import pack1.*;

  2. import pack1.Fish;

๐Ÿ“Key Points (Latest Java Versions ✅)

  • Enums are type-safe constants.
  • They can have fields, methods, and constructors.
  • They cannot extend other classes, but can implement interfaces.
  • Enums are thread-safe since all constants are created at class loading.
  • From Java 5 onwards, enums can be used in switch.
  • Useful methods: values(), ordinal(), name(), compareTo().
  • They work seamlessly with Collections, Generics, and Streams (Java 8+).


Saturday, 15 August 2020

No of Occurrence in Array

package com.tutorial4u;

import java.util.HashMap;

/************************************************************

 No of Occurrence in Array

************************************************************/

public class NoOfOccurrenceInArray {

      public static void main(String[] args) {

            int [] numbers = new int[] {10,12,13,14,12,11,10,20,21,14,22};

            int count =0;

            HashMap<Integer, Integer> map = new HashMap<>();

            for(Integer i : numbers) {

                  if(map.containsKey(i)) {

                        count = map.get(i);

                        map.put(i, count+1);

                  }else {

                        map.put(i, 1);

                  }

            }

            System.out.println(map);

      }

}

 

 Output :

{20=1, 21=1, 22=1, 10=2, 11=1, 12=2, 13=1, 14=2}

Wednesday, 29 July 2020

JSON Tutorial

JSON (JavaScript Object Notation)


1.What is JSON?

When working with modern applications—whether web, mobile, or enterprise—data exchange between different systems is a core requirement. To achieve this, developers need a format that is both human-friendly and machine-readable. This is where JSON comes into play.

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It has become the de-facto standard for client-server communication in RESTful APIs, microservices, and even configuration files.

Why JSON is so popular:

  • Easy to read and write – its structure is straightforward and resembles objects in many programming languages.
  • Language-independent – JSON is not tied to JavaScript; almost every modern language (Java, Python, PHP, C#, etc.) supports JSON parsing.
  • Flexible data representation – JSON can represent different kinds of values, such as:

    Objects (key/value pairs)
    • Arrays (ordered lists)
    • Numbers
    • Strings
    • Booleans (true / false)
    • Null values
  • Because of this simplicity, JSON has almost completely replaced XML in most APIs.
๐Ÿ‘‰ In this tutorial, we’ll explore how to create, manipulate, and parse JSON using one of the most widely used Java libraries: the JSON-Java library, also known as org.json.

2.JSON Syntax Rules

  • Data is in key/value pairs"key": "value".
  • Keys are always strings (inside double quotes).
  • Values can be:

    • String → "Hello"
    • Number → 25
    • Boolean → true / false
    • Null → null
    • Array → [1,2,3]
    • Object → { "key": "value" }
Example:

{
  "name": "Ashish",
  "age": 25,
  "isStudent": false,
  "skills": ["Java", "Spring Boot", "SQL"],
  "address": {
    "city": "Delhi",
    "pincode": 110001
  }
}

3.JSONObject

A JSONObject in Java represents a collection of key-value pairs, very similar to a Map<String, Object>.

✅ Key points about JSONObject:

  • Keys must be unique and non-null strings.
  • Values can be:

    • String → "Hello"
    • Number → 100
    • Boolean → true / false
    • JSONArray → [ ... ]
    • Another JSONObject → { ... }
    • or JSONObject.NULL (if you want a null value).
  • The data is wrapped in curly braces { }, with keys and values separated by : and each pair separated by a comma.

3.1 Creating a JSONObject Manually

We can create a new JSONObject and add properties using the put() method:

import org.json.JSONObject;

public class JsonExample {
    public static void main(String[] args) {
        JSONObject user = new JSONObject();
        user.put("id", 101);
        user.put("name", "Alice");
        user.put("isPremium", true);
        
        System.out.println(user.toString());
    }
} 

Output:

{"id":101,"name":"Alice","isPremium":true}

3.2 Creating JSONObject from JSON String

If you already have a JSON string, just pass it into the constructor:

String jsonString = "{\"course\":\"Java\",\"level\":\"Beginner\"}";
JSONObject course = new JSONObject(jsonString);

System.out.println(course.getString("course"));  // Java
System.out.println(course.getString("level"));   // Beginner

3.3 Nested JSONObject

You can also store JSON objects inside another JSON object:

JSONObject address = new JSONObject();
address.put("city", "Mumbai");
address.put("pincode", 400001);

JSONObject student = new JSONObject();
student.put("name", "Ravi");
student.put("rollNo", 12);
student.put("address", address);

System.out.println(student.toString(2));  

Output :

{
  "name": "Ravi",
  "rollNo": 12,
  "address": {
    "city": "Mumbai",
    "pincode": 400001
  }
}

4.JSON Array

A JSONArray is an ordered list of values, very similar to a Java List.

Key points about JSONArray:

  • Values can be Strings, Numbers, Booleans, JSONObjects, or even other JSONArrays.
  • It is enclosed in square brackets [ ].
  • Each value is separated by a comma.

4.1 Creating JSONArray Manually

import org.json.JSONArray;
import org.json.JSONObject;

public class JsonArrayExample {
    public static void main(String[] args) {
        JSONArray fruits = new JSONArray();
        fruits.put("Apple");
        fruits.put("Banana");
        fruits.put("Mango");

        System.out.println(fruits.toString());
    }
}

Output:

["Apple","Banana","Mango"]

4.2 JSONArray with JSONObjects

You can add JSON objects into an array as well:

JSONObject book1 = new JSONObject();
book1.put("title", "Clean Code");
book1.put("author", "Robert Martin");

JSONObject book2 = new JSONObject();
book2.put("title", "Effective Java");+
book2.put("author", "Joshua Bloch");

JSONArray library = new JSONArray();
library.put(book1);
library.put(book2);

System.out.println(library.toString(2));

Output :

[
  {
    "title": "Clean Code",
    "author": "Robert Martin"
  },
  {
    "title": "Effective Java",
    "author": "Joshua Bloch"
  }
]

4.3 Creating JSONArray from Collection

List<String> cities = Arrays.asList("Delhi", "London", "New York");
JSONArray cityArray = new JSONArray(cities);

System.out.println(cityArray.toString());

Output:

["Delhi","London","New York"]

5.HTTP

The HTTP class in the org.json package helps us work with HTTP headers. It provides simple methods to convert between:

  • an HTTP header stringJSONObject
  • a JSONObject → HTTP header string

Main Methods of HTTP Class:

  • toJSONObject(String sourceHttpHeader)

    • Takes a plain HTTP header string.
    • Converts it into a structured JSONObject.

  • toString(JSONObject jo)

    • Takes a JSONObject.
    • Converts it into an HTTP header string.

5.1 Converting JSONObject to an HTTP Header

The HTTP class in the org.json package lets us convert a JSONObject into an HTTP header string.To make a valid HTTP request header, our JSONObject must contain three required keys:

  • "Method" – the HTTP method (GET, POST, PUT, DELETE, etc.)
  • "Request-URI" – the resource URL we want to call
  • "HTTP-Version" – the HTTP version (usually HTTP/1.1)
Example:
import org.json.JSONObject;
import org.json.HTTP;

public class HttpHeaderExample {
    public static void main(String[] args) {
        JSONObject requestHeader = new JSONObject();
        requestHeader.put("Method", "GET");
        requestHeader.put("Request-URI", "https://api.myapp.com/users");
        requestHeader.put("HTTP-Version", "HTTP/1.1");

        String httpStr = HTTP.toString(requestHeader);
        System.out.println(httpStr);
    }
}

Output:

GET "https://api.myapp.com/users" HTTP/1.1

๐Ÿ“Œ Important Notes:

  • For request headers, you must include:
    • "Method"
    • "Request-URI"
    • "HTTP-Version"
  • For response headers, you must include:

    "HTTP-Version"
    • "Status-Code" (e.g., 200, 404)
    • "Reason-Phrase" (e.g., OK, Not Found)
✅The HTTP.toString() method makes it easy to transform a JSON object into a proper HTTP header string.

5.2 Converting HTTP Header String Back to JSONObject

Just like we can convert a JSONObject into an HTTP header string, we can also do the reverse — take an HTTP header string and turn it back into a JSONObject.

For this, we use the method:

HTTP.toJSONObject(String httpHeaderString)
Example :
import org.json.JSONObject;
import org.json.HTTP;

public class HttpHeaderBackExample {
    public static void main(String[] args) {
        String httpHeader = "GET \"https://api.shop.com/products\" HTTP/1.1";
        
        JSONObject obj = HTTP.toJSONObject(httpHeader);
        
        System.out.println(obj.toString(2)); // pretty print
    }
}

Output :

{
  "Method": "GET",
  "Request-URI": "https://api.shop.com/products",
  "HTTP-Version": "HTTP/1.1"
}

๐Ÿ“Œ Key Point:

  • HTTP.toJSONObject() is useful when you receive raw HTTP headers as text and want to parse them into a structured JSONObject for further processing.


skks

Inner Class

 Inner Class

Introduction to Java

Introduction to Java

Java is a programming language developed by James Gosling and his team at Sun Microsystems in 1995. Initially, it was called Oak, but since that name was already registered by another company, it was later renamed to Java.

๐Ÿ“Œ Notes:

  • Development of Java started in 1991 under the “Green Project.”
  • It was officially released in 1995.

In 2010Oracle Corporation acquired Sun Microsystems, and since then Oracle has been responsible for the continued development, stewardship, and support of Java.

The main goal of Java is write once, run anywhere” (WORA) – meaning a program written in Java can run on multiple operating systems (such as Windows, Linux, and macOS) without modification, provided a compatible Java Virtual Machine (JVM) is available.

  • Initial Release: Java 1.0 (January 1996)
  • Major Milestones:
    • Java 2 (J2SE 1.2, 1998): Introduced Swing, Collections, strict JVM specification.
    • Java 5 (2004): Added generics, annotations, enhanced for-loop, autoboxing.
    • Java 8 (2014): A landmark release introducing Lambda expressionsStreams API, and Date/Time API.
    • Java 9 (2017): Introduced the Module System (Project Jigsaw).
    • Java 10 (March 2018): Added var keyword for local variable type inference.
    • Java 11 (September 2018, LTS): Removed Applets, added new HTTP Client API, and became a Long-Term Support (LTS) version.
    • Java 17 (September 2021, LTS): Introduced pattern matching, sealed classes, enhanced switch expressions.
    • Java 21 (September 2023, LTS): The latest LTS version as of 2025, featuring Virtual Threads (Project Loom), record patterns, string templates, and significant JVM improvements.

Many enhanced versions of Java have been released over the years, bringing improvements in performance, security, scalability, cloud support, and developer productivity. (⚠️ Note: The latest long-term support (LTS) version as of 2025 is Java 21, released in September 2023.)

Setting Up the Java Environment

Learn how to set up the Java environment on your system to start building and running Java applications smoothly.

How to Download and Install Java Development Kit (JDK) and Java Runtime Environment (JRE)

In this๐Ÿ‘‰ step-by-step guide to downloading and installing the latest JDK and JRE, you’ll learn how to set up Java for Windows, macOS, and Linux, configure environment variables, and verify your installation for seamless Java programming and application execution.

Overview of Integrated Development Environments (IDEs) like Eclipse, IntelliJ IDEA, and NetBeans

Explore the most popular Java IDEs—Eclipse, IntelliJ IDEA, and NetBeans—and understand their features for faster and more efficient coding.

Instructions for Setting Up the PATH Environment Variable and Verifying Installation

๐Ÿ‘‰Follow this detailed guide on how to set up the Java PATH environment variable to configure Java correctly and verify the installation on your system

Key Features of Java

Java was designed with the following important properties:

  • Simple
  • Platform Independent
  • Object-Oriented
  • Portable
  • Robust
  • Secure
  • Multithreaded

๐Ÿ”น Simple

Java is easy to learn and has a clean, simple syntax.It removed many complicated and rarely used features found in C and C++ (such as pointers and operator overloading).Additionally, Java includes automatic ๐Ÿ‘‰garbage collection, so developers don’t need to manually delete unused objects.

๐Ÿ”น Platform Independent

Java achieves platform independence through the  ๐Ÿ‘‰Java Virtual Machine (JVM).The compiler converts Java code into bytecode, which can be executed on any machine that has a JVM installed.

๐Ÿ”น Object-Oriented Programming Language

Java is an object-oriented programming (OOP) language. Almost everything in Java is treated as an object (except primitive data types).

The four main OOP principles in Java are:

  1.  ๐Ÿ‘‰Abstraction

  2.  ๐Ÿ‘‰Encapsulation

  3.  ๐Ÿ‘‰Inheritance

  4.  ๐Ÿ‘‰Polymorphism

๐Ÿ”น Portable

Java is portable because its compiled bytecode can be executed on any platform that supports the JVM. This means code written on one machine can run on another without modification.

๐Ÿ”น Robust

Java is considered robust because it has strong memory managementgarbage collection, and exception handling, reducing the chances of crashes and errors.

๐Ÿ”น Secure

Java is designed with security in mind. Since it does not use pointers (which can lead to memory access vulnerabilities) and runs inside the JVM sandbox, it prevents unauthorized access and ensures a safer execution environment.

๐Ÿ”น Multithreaded

Java supports multithreading, allowing developers to write programs that can perform multiple tasks simultaneously.Threads in Java share a common memory area, making it efficient and suitable for high-performance applications.


Java Development Kit (JDK) and Java Runtime Environment (JRE)

                  Java Development Kit (JDK) and Java Runtime Environment (JRE)  To download and install the Java Development Kit (  JDK ) ...