Trending December 2023 # How Urlconnection Class Works In Java # Suggested January 2024 # Top 12 Popular

You are reading the article How Urlconnection Class Works In Java updated in December 2023 on the website We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested January 2024 How Urlconnection Class Works In Java

Introduction to Java URLConnection

The URLConnection is a Java Programming Language class that usually represents one of the communication links or links between an URL and an application. This URLConnection class helps read and write the data to the specific/specified resource, which is actually referred to by an URL. It is one of the superclasses of all the classes. This URLConnection class’s instances are helpful to read from and to write, and it is to the resource referenced by the specific URL. Here connecting a connection to a specific URL is one type of multistep process.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax URLConnection openConnection() How does the URLConnection work in Java

URLConnection class works by providing many methods. In the process of multi-steps of connecting an URL involves openConnection() and connect() methods. The openConnection() helps in manipulating the parameters which can affect the remote resource connection. The connect() method helps interacting which is having with the resource, and it is helpful for query header contents and fields.

The connection object is actually created just by invoking the openConnection method or function on an URL. The setup parameters of the connection object and the general request for the properties are to be manipulated. The actual and usual connection which is to the remote object is made with the help of connecting method usage. The remote object of it becomes available, and the header fields along with its contents of one of the remote object could be accessed. The getInputStream() method or function will help return all the data of the specific or specified URL in the particular stream, which can be used to read and display.

The URLConnection class of the Java Programming Language actually works by providing as many methods as need just to display all the data of the webpage or blog just with the help of getting InputStream() method or methods, but the getInputStream() method/function helps a lot in returning all the website data with the help of the specific URL which is mentioned in the stream. This URL will be used to read and used to display the source code of the website or a blog; to get all the source code, one has to use Loops for multiple types of source code display.

There are only two subclasses that extend the URLConnection Class of Java. They are HttpURLConnection and JarURLConnection. HttpURLConnection helps us connect to any type of URL that actually used the “HTTP” as its protocol; then, the HttpURLConnection class will be used. The JarURLConnection will help us trying to establish one of the connections to a specific jar file on the world wide web; then, the JarURLConnection will be used.


Some of the important methods are helpful in using to read or write or to get some info after the connection is established. They are:

1. URLConnection openConnection(): This method helps in opening the connection to the specific or specified URL.

2. Object getContent(): It will retrieve some content of URLConnection.

4. getContentEncoding(): It will return some value of the content-encoding header’s field.

5. getContentLength(): It will return the content header field’s length.

7. getHeaderField (int-i): It will return the header’s i-th index value

8. getHeaderField (String-Field): It will return the field named value “field” in some header which is to get a list of all the header fields.

9. OutputStream getOutputStream(): It will return one of the connection’s output stream.

10. InputStream getInputStream(): It will return one input stream to the open connection.

11. setAllowUserInteraction(boolean): It will set the setting as a TRUE value which means users can interact with the page. By default, the value of it is TRUE.

12. setDefaultUseCaches(boolean): It will set useCache field’s default as the provided value.

14. setDoInput(boolean): It will set only if the user now allows writing on the specific page. By default, its value is FALSE since, most of all, the URL doesn’t even allow writing.

Examples to Implement Java URLConnection

below is the example of implementing java URLConnection:

Example #1

This illustrates the reading and writing of a blog/website URL using the URLConnection class. At first, different types of java libraries are imported. Then the public class is created along with the public main method for java code filling. Then the URL variable is created to add the specific website/blog URL with the help of the URL command. Then “URLConnection” is used to open a connection to the above-mentioned URL. Then Map is used to get all fields map of the specific HTTP header. Then to print all the fields of website URL and their values, FOR LOOP is used. Then BufferedReader is used to get the open connection’s inputstream. Then to print source code line by line, WHILE LOOP is used. While loop will print all the source code, the website/blog url mentioned in the code itself.


import*; import*; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; public class URLConnectionclass1 { public static void main(String[] args) { try { URLConnection urlcon1 = url1.openConnection(); { System.out.print(mp1.getKey() + " : "); System.out.println(mp1.getValue().toString()); } System.out.println(); System.out.println("The Complete source code of the provided URL is-"); BufferedReader br1 = new BufferedReader(new InputStreamReader (urlcon1.getInputStream())); String i1; while ((i1 = br1.readLine()) != null) { System.out.println(i1); } } catch (Exception e1) { System.out.println(e1); } } }



we hope you learned the definition of Java URLConnection and its syntax and explanation, How the URLConnection class works in Java Coding Language, and various examples to better understand the Java URLConnection concept and so easily.

Recommended Articles

This is a guide to Java URLConnection. Here we discuss an introduction to Java URLConnection, syntax, how does it work, methods and example. You can also go through our other related articles to learn more –

You're reading How Urlconnection Class Works In Java

How To Create An Immutable Class With Mutable Object References In Java?

Immutable objects are those objects whose states cannot be changed once initialized. Sometimes it is necessary to make an immutable class as per the requirement. For example, All primitive wrapper classes (Integer, Byte, Long, Float, Double, Character, Boolean and Short) are immutable in Java. String class is also an immutable class.

To create a custom immutable class we have to do the following steps

Declare the class as final so it can’t be extended.

Make all fields private so that direct access is not allowed.

Do not provide setter methods (methods that modify fields) for variables, so that it can not be set.

Make all mutable fields final so that their values can be assigned only once.

Initialize all the fields through a constructor doing the deep copy.

Perform cloning of objects in the getter methods to return a copy rather than returning the actual object reference.

If the instance fields include references to mutable objects, don’t allow those objects to be changed

Don’t provide methods that modify the mutable objects.

Don’t share references to the mutable objects. Never store references to external, mutable objects passed to the constructor. If necessary, create copies and store references to the copies. Similarly, create copies of our internal mutable objects when necessary to avoid returning the originals in our methods.


Live Demo

final class Employee {    private final String empName;    private final int age;    private final Address address;    public Employee(String name, int age, Address address) {       super();       this.empName = name;       chúng tôi = age;       this.address = address;    }    public String getEmpName() {       return empName;    }    public int getAge() {       return age;    }    /* public Address getAddress() {       return address;       }    */    public Address getAddress() throws CloneNotSupportedException {       return (Address) address.clone();    } } class Address implements Cloneable {    public String addressType;    public String address;    public String city;    public Address(String addressType, String address, String city) {       super();       this.addressType = addressType;       this.address = address;       chúng tôi = city;    }    public String getAddressType() {       return addressType;    }    public void setAddressType(String addressType) {       this.addressType = addressType;    }    public String getAddress() {       return address;    }    public void setAddress(String address) {       this.address = address;    }    public String getCity() {       return city;    }    public void setCity(String city) {       chúng tôi = city;    }    public Object clone() throws CloneNotSupportedException {       return super.clone();    }    @Override    public String toString() {       return "Address Type - "+addressType+", address - "+address+", city - "+city;    } } public class MainClass {    public static void main(String[] args) throws Exception {       Employee emp = new Employee("Adithya", 34, new Address("Home", "Madhapur", "Hyderabad"));       Address address = emp.getAddress();       System.out.println(address);       address.setAddress("Hi-tech City");       address.setAddressType("Office");       address.setCity("Hyderabad");       System.out.println(emp.getAddress());    } }

In the above example, instead of returning the original Address object we will return a deep cloned copy of that instance. The address class must implement the Cloneable interface.

Output Address Type - Home, address - Madhapur, city - Hyderabad Address Type - Home, address - Madhapur, city - Hyderabad

How Keyfile Works In Mongodb?

Definition of MongoDB keyfile

MongoDB keyfile is used to authenticate our database from unauthorized access, we can authenticate our replica set using MongoDB keyfile. To enforce the access of keyfile using replica set we require to configure the security between each replica set using user access control. After implementing keyfile authentication each member from the replica set will use the same authentication mechanism which was we have developed using MongoDB keyfile. We can generate our keyfile using any method which was available, also we can generate our keyfile between 6 to 1024 characters.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others


Below is the syntax of keyfile in MongoDB.

1) Create keyfile –

2) Set the path of keyfile in MongoDB configuration file –

3) Start the MongoDB instance using keyfile –

Parameter description syntax of keyfile in MongoDB is as follows.

1) Openssl – This is a Linux command which was used to generate keyfile. Using OpenSSL we can generate the 1024 pseudo random password.

2) Encoding method – This parameter is defined as the method which was we have using to encode the pseudo-random code.

3) No of keyfile characters – This is defined as no of characters which was we have used while generating a keyfile.

4) Path and name of keyfile – This parameter is defined as the path where we have stored our keyfile. Also, we need to give keyfile name at the time of keyfile creation.

5) Security – This is the parameter of the MongoDB configuration file which was used to define the authentication method of the MongoDB server. Using this parameter we can define authentication as keyfile in MongoDB.

How Keyfile works in MongoDB?

To use keyfile authentication we need to create database admin users for database administration purpose only.

The first step is to create keyfile, the main purpose of the MongoDB keyfile is to authenticate every database instance using the contents of the keyfile. Using this content and proper keyfile only the MongoDB instance is connected to the replica set.

If suppose we don’t have keyfile we cannot connect the replica set, it will show the error like authentication is failed.

We can generate a minimum of 6 characters and a maximum of 1024 characters keyfile in MongoDB. Also, keyfile contains characters in the base-64 format.

After generating the keyfile we need to copy the file on every server on which the replica set is running. We need to ensure that the user which was running the mongod instance is the owner of the file and he is able to access that keyfile.

After copying keyfile on each server we need to change the security method to keyfile and need to restart all the replica set.

rs.initiate ()

rs.status ()

After connecting to the primary replica set we need to create database user which have admin privileges on the database server.

After connecting to the primary replica set we need to check the user authentication using the replica set.

After checking user authentication we need to create a cluster-admin user for the admin database.


The below steps shows create keyfile in MongoDB. We have to create keyfile of the replica set.

1) Create keyfile

In the below example, we have to create a keyfile name as mongodb_keyfile and we have to store this file into the MongoDB data directory.

We have created the keyfile using the OpenSSL command. We have used 525 characters to create keyfile.


cat /var/lib/mongo/mongodb_keyfile

Figure – Example to create keyfile.

2) Copy the keyfile on every replica member

After creating the keyfile we need to copy this file on each replica set. We have using cp command to copy the file.


ls -lrt /var/lib/mongo2/mongodb_keyfile

Figure – Example to Copy the keyfile on every replica member.

3) Enable the access control on every replica set

We have enabled access control on every server. For enabling the access control we need to configure the same into our configuration file.

After enabling the authentication we need to restart the replica set.


cat /etc/mongod.conf

Figure – Example of enable the access control on replica set.

systemctl status mongod

Figure – Example start the MongoDB replica instance.

4) Connect to the replica set

After starting the replica set connect to the replica instance using mongo command.



Figure – Example to connect the replica set.

5) After connecting to the replica set check the status of replication

After connecting to the database server need to check the status of the replica set. We have to check the replication status using rs. status () command.


rs.status ()

Figure – Example to check status of replica set.

6) Create the administrator user


roles: [ { role: “userAdminAnyDatabase” (Admin access of any database) , db: “admin” (database name) } ] )

Figure – Example to create administrator user.

7) Authenticate the user

In the below example, we have to authenticate our admin database user.


db.getSiblingDB ("admin" (database name) ).auth("mongodb_admin" (user name), passwordPrompt())

Figure – Example of authenticate the user.

8) Create cluster-admin user

In the below example, we have created the cluster-admin user for keyfile authentication.


roles: [ { role: “userAdminAnyDatabase” (Admin access of any database) , db: “admin” (database name) } ] } )

Figure – Example to create cluster-admin user.


MongoDB keyfile is used to authenticate the database from unauthenticated access. We need to create keyfile using the encryption method. In the above example, we have created keyfile using the OpenSSL command. Keyfile is very important and useful in MongoDB to authenticate the database from unauthorized access.

Recommended Articles

This is a guide to MongoDB keyfile. Here we discuss the definition, syntax, How keyfile works in MongoDB? examples with code implementation. You may also have a look at the following articles to learn more –

How Does Generic Class Work In Scala?

Definition of Scala Generic

Scala Generic classes are different then we have generic classes in Java. Generic classes are those classes which takes the type of the variable as the parameter. We are not sure which type of variable would be we just specify it in square brackets []. The type would be verified by the compiler at runtime. Generic classes are mostly utilized for the collection in scala. We mostly use parameter name as A to define the generic class type but it is not mandatory we can use any character to define it.

Start Your Free Software Development Course


class class_name[A] { private varvaribale_name: List[A] }

In the syntax above we are using A as the type for the list we are defining. This A can contain any data type like Int, Float, String or any other user defined object as well. We can use any other character name as well in the place of A it is the standard that we follow.

class Demo[A] { private varmyList: List[A] = {20, 30, 40, 50) } How does Generic Class Work in Scala?

Collections are very useful when we have same type of data into our list or set. This helps us from typecasting of the elements as well which reduce the line of code. Not with generic we define this type into the [] brackets for example;

using collection :val list = new List[Int] : we are specifying the type at the time of creation only. Now take a look at generic in scala; using generic : class MyDemo[A] {} val list = new MyDemo[String] val list = new MyDemo[Double] val list = new MyDemo[Float] val list = new MyDemo[Student]

In the above case, we have created one class with a generic type specify it by using A in the square brackets[]. Now at the time of object creation for the list we are mentioning its type as String or it can be anything we want. If we follow the standard given by scala then the generic parameter should be of single character only. Also, we can have multiple parameter as well see below;

: class MyClass[Key1, Value1]: In this, we are passing two-parameter here. Also, we can use these parameters with traits in scala which will make them generic too. For syntax how to make them generic see below;

class Jasmin extends Flower

Suppose we have flower class, rose and jasmine are the child class of Flower here. We have different type of variance related to this.

Question is: If Rose extends Flower so does a list of Rose also extend a list of Flower here from above example?

1. Invariance

IF we chose to answer No for the question then we would require to create the list of Rose and Flower separately and in this case we would use Invariance for this.

class InvariantList[A] valinvariantAnimalList: InvariantList[Flower] = new InvariantList[Rose]

In this we can define them in scala.

2. Covariance

If we choose to answer yes for the above question then we should go for Covariance here. We can define this Covariance by using the PLUS(+) symbol in the scala. Like this: class CovariantList[+A]

This + simplify that it is a covariance class. val f: FLower = new Rose valfList: CovariantList[Flower] = new CovariantList[Rose]

In this example, we are assigning the instance of rose to its parent class because it’s a subclass for flower and creating list for them.

3. Contravariance

If we choose not to answer any of the above then we can go for Contravariance in scala. In this, we use a minus sign (-) to make use of it while working in code. Below is the syntax to use this type in scala:

class ContravariantList[-A] Examples of Scala Generic Classes 1. Single Parameter Generic Classes

In this type we pass only one character to make it Generic in scala. See example below for better understanding;


object Main extends App{ defaddValues[A](a: A, b: A)(implicit x: Numeric[A]): A =, b) println("Sum of the values are  ::::  ") println(addValues(100, 300)) }


2. Contravariance

To define and use this we use minus operator (-).


object Main extends App{ valic = new ICICI valsb = new SBI valBankType = new BankType } abstract class Bank [-T]{ defrate : Unit } class ICICI extends Bank[Int]{ override def rate: Unit = { println("icici called  ::") println(" sub type icici !!") } } class SBI extends Bank[Int]{ override def rate: Unit = { println("SBI called  ::") println("sub type SBI !!") } } class BankType{ defshow(x: Bank[Int]){ x.rate } }

3. Covarience

To define this type we use PLUS (+) operator.


object Main extends App{ valic = new ICICI valsb = new SBI valBankType = new BankType } abstract class Bank [+T]{ defrate : Unit } class ICICI extends Bank[Int]{ override def rate: Unit = { println("icici called  ::") println(" sub type icici !!") } } class SBI extends Bank[Int]{ override def rate: Unit = { println("SBI called  ::") println("sub type SBI !!") } } class BankType{ defshow(x: Bank[Int]){ x.rate } }



Generic are important to write efficient code for our application. It makes then code more readable, easily, clear, and also reduces the repetitive logic and line of code in our program. We have discussed its various types also according to the different case we have more better understanding. They are mostly use with collection in scala.

Recommended Articles

We hope that this EDUCBA information on “Scala Generic” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

How To Replace Function Works In Xslt?

Definition of XSLT replace Function

XSLT replace is deterministic and does string manipulation that replaces a sequence of characters defined inside a string that matches an expression. In simple terms, it does string substitution in the specified place by replacing any substrings. Fn: replace function is not available in XSLT1.0 and it is well treated in XSLT2.0. XSLT2.0 handles more complicated operations.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others


Replace Function takes three parameters namely input as text, pattern a string fragment, replacement string.

How to replace function works in XSLT?

The Replace function works by writing an XSLT template for this function and calls this replace whenever replacement of the string action is required. This function is very similar to regex-group (). If the specified input string has no substring that matches the defined regular expression, it gives the output as a single string similar to the input string. As defined in the syntax, the dollar sign references the matches with the expressions as well as sub-expressions. The expressions are a string of text and the sub-expressions are shown with parenthesis. Let’s have a look at this statement.

The output is displayed as

contact me (321) 555-7680 hello.

The function returns the value of the first string passed as an argument with every substring defined by the regular structure in the second string and finally, it is replaced by the third argument.

For a given string with a regular expression

The Specified replacement String of above statement is

Here it replaces part of a string that matches a declared regular expression.

M go to n go to p

The sample code shows how it works.


Let us examples of XSLT replace.

Example #1: Simple Example with Replace function





Example #2: Replica of the function file.



SQL Functions Defined


The first argument of the function is the name element defined in the value-of statement. Second argument is the regular expression with ^hh. It produces same result as an XML file with the function.


Example #3: With special characters

XSL file


A very simple approach in XSLT2.0 with the values for replacing is taken. Here I have taken a string png to replace and the literal _R. The result should look like this.


Example #4: Replacing multiple strings in the content




The above template replaces the character string with the replacement. Therefore the result of calling this stylesheet is shown below. So when I type on the browser I get the following response.



With the help of the XSLT2.0 replace () function removes undesired characters from a string in powerful regular expressions. XSLT replaces corresponding single characters, not the entire string.

The dollar sign ($) interprets the rightmost characters in the string as literal. And if the single-digit is higher than the sub-expressions the digit or character is replaced with an empty string.


Somehow, we have discussed and concluded on replace function. This function will get deep specification to stay grip on it and highlighted how to walk through the replace strings with the regular expressions and create Stylesheet functions to do with templates.

Recommended Articles

This is a guide to XSLT replace. Here we discuss the Introduction, syntax, How to replace function works in XSLT?, and examples. You may also have a look at the following articles to learn more –

How When Statement Works In Kotlin With Examples?

Introduction to Kotlin when

Web development, programming languages, Software testing & others


In kotlin language, it has many default keywords, variables, and functions to implement the application. One of the default keywords can be used in both expression and non-expression scenarios.

val variablename; when(variablename) { —some coding logics it depends upon the requirement— } }

The above codes are the basic syntax for utilizing the when keyword on the kotlin codes. We want to write the expression based on the function’s requirement on the child function, or the inheritance concept will be implemented on the application.

Working of when statement in Kotlin

Generally, “when” is one of the keywords, and it is used in both expression and non-expression; it also checks and combined with the valid conditional statements depending on the calculation based on the user requirements, in kotlin, when it is constructed, and it can be thought of as the replacement for the switch case statement, which is similar to the other languages when the keyword is used as the expression and validating the condition like matching the values for overall expression. If condition statement, the values of the individual branches are always ignored, each branch can be of the block, and its value is the last expression of the block values.

Else loop is evaluated if none of the other branches and the condition is satisfied with the boolean condition statements; else, a loop is mandatory unless the compiler can prove that all possible cases are covered with the loop conditions. The scope of the variable is introduced with the keyword for when the subject is restricted to the body of this keyword for when expression. We can check and validate the condition using a particular type in both compile and runtime in the kotlin operators. With the help of conditional statements, the loop will use the control, and it executes the other conditions based on their needs.

Examples of Kotlin when

Below are the examples of Kotlin when:

Example #1


package one; println("Welcome To My Domain it’s a first example regarding the When keyword using the kotlin program logics") var first = 7 var second = when(first) { } println("$second") var third = when(second) { } println("Thank you users have a nice day please find your outputs $first") }


We used the above example when keywords in basic formats like int, string, string, and string formats. We can print the statements on the user console screen.

Example #2


package one; println("Welcome To My Domain it’s a second example regarding the When keyword using the kotlin program logics") var first = 'A' when(first){ } println("Thank you users have a nice day kindly try again please keep and stay with our application $first") var yrsage = 16 when(yrsage) { val numlast = 100 - yrsage println("Your marraige age is in $numlast years") } } }


Example #3


package one; enum class Third(val exampl: Boolean = false){ January(true), February, March, April(true), May, June, July(true), August, September, October, November, December(true); companion object{ fun demo(obj: Third): Boolean { } } } fun demos(th: Third) { when(th) { } } fun main(){ println("Welcome To My Domain its a third example regarding the When keyword using the kotlin program logics") for(eg in Third.values()) { println("${eg.ordinal} = ${} and is months in ${eg.exampl}") } val demo1 = Third.April; println("Thank you users your current month is ${Third.demo(demo1)}") }


In the final example, we used to calculate the current month status by using the boolean condition. We used the when keyword to print the enum class value on the function.


In the conclusion part, kotlin when is one of the conditional statements like if, else, etc. The when keyword supports non -conditional expressions also instead of the switch case statement, these statements will execute the user inputs on each step. It supports all types of user browsers, so it’s compatible when keyword satisfied with some range intervals, which depends upon the requirement.

Recommended Articles

This is a guide to Kotlin when. Here we discuss the introduction, syntax, and working of when statement in Kotlin along with the examples and outputs. You may also have a look at the following articles to learn more –

Update the detailed information about How Urlconnection Class Works In Java on the website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!