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.


Tuesday, 28 July 2020

Exception handling in Method Overriding

Exception handling in Method Overriding

We can override a method by changing only the exception handling in java.

An overriding method (the method of child class) can throw any unchecked exceptions, regardless of whether the overridden method (method of base class) throws exceptions or not. 
However the overriding method should not throw checked exceptions that are new or broader than the ones declared by the overridden method. The overriding method can throw those checked exceptions, which have less scope than the exception(s) declared in the overridden method.

Case 1: If  superclass doesn’t throw any exception but child class throws an unchecked exception.

package com.tutorial4u;

class A {

       void m1() {

             System.out.println("method A");

        }

}

class B extends A {

       void m1() throws NullPointerException {

             System.out.println("Method B");

       }

}

public class OverridingExample {

       public static void main(String args[]) {

             A a = new B();

             a.m1();

       }

}

Output : Method B

Case 2 :  If  superclass doesn’t throw any exception but child class throws an checked exception

package com.tutorial4u;

import java.io.IOException;

class A {

       void m1() {

             System.out.println("method A");

       }

}

class B extends A {

       // Exception IOException is not compatible with throws clause in A.m1()

       void m1() throws IOException {

             System.out.println("Method B");

       }

}

public class OverridingExample {

       public static void main(String args[]) {

             A a = new B();

             a.m1();

       }

}

Output : Exception in thread "main" java.lang.Error: Unresolved compilation problem: Exception IOException is not compatible with throws clause in A.m1()

Note : We cannot throw a checked exception if the overridden method(method of base class) is not throwing an exception.

Case 3 : If superclass throws checked exception but subclass throws narrower (subclass of) checked exception

package com.tutorial4u;

import java.io.FileNotFoundException;

import java.io.IOException;

class A {

       void m1() throws IOException {

             System.out.println("method A");

       }

}

class B extends A {

       void m1() throws FileNotFoundException {

             System.out.println("method B");

       }

}

public class OverridingExample {

       public static void main(String args[]) throws IOException {

             A a = new B();

             a.m1();

       }

}

Output : method B

Case 4 : If superclass throws checked exception but subclass throws broader (superclass of ) checked exception.

package com.tutorial4u;

import java.io.IOException;

class A {

       void m1() throws IOException {

             System.out.println("method A");

       }

}

class B extends A {

       // Exception Exception is not compatible with throws clause in A.m1()

       void m1() throws Exception {

             System.out.println("Method B");

       }

}

public class OverridingExample {

       public static void main(String args[]) {

             A a = new B();

             try {

                    a.m1();

             } catch (Exception e) {

                    e.printStackTrace();

             }

       }

}

Output : 

Exception in thread "main" java.lang.Error: Unresolved compilation problem: Exception Exception is not compatible with throws clause in A.m1()

Note : Getting compilation error because the m1() method of child class is throwing Exception which has a broader scope than the exception thrown by method m1() of parent class.

But if child class method have child exception of the super class declared exception or same  or not throwing any exception. It will execute fine.

Case 5 : If superclass throws checked exception but subclass throws an unchecked Exception (RuntimeException)

package com.tutorial4u;

import java.io.IOException;

class A {

       void m1() throws IOException {

             System.out.println("method A");

       }

}

class B extends A {

       // Exception Exception is not compatible with throws clause in A.m1()

       void m1() throws ArithmeticException {

             System.out.println("Method B");

       }

}

public class OverridingExample {

       public static void main(String args[]) {

             A a = new B();

             try {

                    a.m1();

             } catch (Exception e) {

                    e.printStackTrace();

             }

       }

}

Output : Method B


Case 6 : If superclass throws unchecked Exception but subclass throw a checked exception.


package com.tutorial4u;

import java.io.IOException; 

class A {

       void m1() throws ArithmeticException {

             System.out.println("method A");

       }

}

class B extends A {

       // Exception IOException is not compatible with throws clause in A.m1()

       void m1() throws IOException{

             System.out.println("Method B");

       }

}

public class OverridingExample {

       public static void main(String args[]) {

             A a = new B();

             try {

                    a.m1();

             } catch (Exception e) {

                    e.printStackTrace();

             }

       }

}

Output : 

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
Exception IOException is not compatible with throws clause in A.m1()

Case 7: If superclass and subclass both throw an unchecked Exception (RuntimeException)

package com.tutorial4u;

class A {

       void m1() throws ArithmeticException {

             System.out.println("method A");

       }

}

class B extends A {

       void m1() throws NullPointerException {

             System.out.println("method B");

       }

}

public class OverridingExample {

       public static void main(String args[]) {

             A a = new B();

             a.m1();

       }

}

Output : method B


Case 8 : If superclass and  subclass both throws a checked exception

package com.tutorial4u; 

import java.io.IOException;

class A {

       void m1() throws IOException {

             System.out.println("method A");

       }

}

class B extends A {

       void m1() throws IOException {

             System.out.println("method B");

       }

} 

public class OverridingExample {

       public static void main(String args[]) throws IOException {

             A a = new B();

             a.m1();

       }

}

Output : method B

Case 9 : if superclass throws a checked exception but subclass does not throw any exception.

package com.tutorial4u;

import java.io.IOException; 

class A {

       void m1() throws IOException {

             System.out.println("method A");

       }

}

class B extends A {

       void m1() {

             System.out.println("method B");

       }

}

public class OverridingExample {

       public static void main(String args[]) throws IOException {

             A a = new B();

             a.m1();

       }

}

Output : method B

Case 10 : If superclass  throws an unchecked exception but subclass doesn't throw any exception 

package com.tutorial4u;

class A {

       void m1() throws ArithmeticException {

             System.out.println("method A");

       }

}

class B extends A {

       void m1() {

             System.out.println("method B");

       }

}

public class OverridingExample {

       public static void main(String args[]) {

             A a = new B();

             a.m1();

       }

}

Output : method B

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 ) ...