Trending December 2023 # Complete Guide To Jdbc Getconnection # Suggested January 2024 # Top 19 Popular

You are reading the article Complete Guide To Jdbc Getconnection 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 Complete Guide To Jdbc Getconnection

Introduction to JDBC getConnection

The following article provides an outline for JDBC getConnection. Java database connectivity gets connection method is used for establishing the connection between the java application program where you are working and the database that will be used for storing and manipulating the data of your application. There are certain basic steps that you should follow to establish the connection. There are also multiple approaches using which you can establish the connection.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Connection Establishment in JDBC

Import all the necessary packages: All the java programming packages that will be required in you program should be included and imported right at the beginning of the file by using the import statement.

Registration of JDBC driver: The loading of the required driver inside the memory of the system is done by the Java Virtual Machine for the handling and fulfilling of all the further requests that will be made.

Formation of the uniform resource locator un database: The URL plays an important role and is necessary to build while establishing a connection. This helps in recognizing the appropriate address and the target database which needs to be connected.

Object creation for connection: getConnection() method is given the call in this step which is an object of the driver manager that will, in turn, create an object of the connection establishing the actual connection to the database from our application.

Syntax of JDBC getConnection

Given below is the syntax in detail about each of the steps seen above:

1. Import Package

The syntax of importing is basically writing the import statement followed by the name of the package that you wish to import. This helps the java compiler to identify the classes that should be called and referred. This import statements are always written in the beginning part of the code covering the first few lines. For most of the manipulations related to SQL database operations, we will import the following two packages.

Import java.math. *; Import java.sql.*;

The first package helps in support of big integers and big decimals while the second package is used in the standard programs of JDBC.

2. Driver Registration

The class files of the driver get loaded inside the memory which can be further used further by interfaces of JDBC. The registration of the driver can be done by using either of the two approaches mentioned below.

a. Using Class.forName()

The following example demonstrates the syntax of the same.

try { Class.forName("com.mysql.jdbc.Driver"); } catch(ClassNotFoundException sampleException) { System.out.println("Sorry! We cannot load the class for the driver"); System.exit(1); }

b. Using DriverManager.registerDriver()

When we are making the use of the Java Virtual Machine which is non- JDK compliant like Microsoft then we can make the use of this static method called DriverManager.registerDriver() that will help you to register your driver.

try { Driver sampleExampleDriver = new com.mysql.jdbc.Driver(); DriverManager.registerDriver( sampleExampleDriver ); } catch(ClassNotFoundException sampleException) { System.out.println("Sorry! We could not establish the driver registration"); System.exit(1); } Formulation of URL for Database

We can create the connection by using the DriverManager.getConnection() method that is overloaded in three ways.

geConnection(String UniformResourceLocator, String username, String associatedPassword)

geConnection(String UniformResourceLocator)

geConnection(String UniformResourceLocator, Properties associatedProps)

Format of Uniform Resource Locator Name of the JDBC Driver Relational Database Management System

jdbc:oracle:thin:@name of host:number of port:name of database oracle.jdbc.driver.OracleDriver Oracle

jdbc:sybase:Tds:name of host: port Number/name of database com.sybase.jdbc.SybDriver Sybase

jdbc:mysql://name of host/ name of database com.mysql.jdbc.Driver


jdbc:db2:name of host:port Number/name of database DB2

We can specify the information of the connection URL of the user name, associated password and the port address information of the host along with IP address and the TCP/ IP protocol for transportation of the data containing request and response.

The below extract shows the sample of the info that will show this method.

Connection conn = DriverManager.getConnection(URL_TO_CONNECT, USERNAME, ASSOCIATED_PASSWORD);

Alternatively, you can also specify just a single url for connection establishment but in this case, the url should contain the information of username and the password in it as shown in the below sample.

Connection sampleConnection = DriverManager.getConnection(educba_URL);

One more method includes the specification of properties username and password same as above.

Closing the Connection

For sample statement consider shown below:

sampleConnectionObject.close(); Example of JDBC getConnection

Given below is the example mentioned:

Let us consider one sample program for setting up the connection by using the getConnection() method.


import java.sql.Connection; import java.sql.DriverManager; public class sampleEducbaPayalConnectionEstablishment{ public static void main(String args[]) throws ClassNotFoundException { String sampleURL; Connection sampleConnection = null; try { Class.forName("com.mysql.jdbc.Driver"); sampleURL="jdbc:mysql://localhost:3306/educba"; username="root"; associatedpassword=""; sampleConnection = DriverManager.getConnection(sampleURL,username,associatedpassword); System.out.println("Successfully Established the connection!"); sampleConnection.close(); System.out.println("The established connection has been closed!"); } catch (Exception sampleException) { System.out.println(sampleException.toString()); } } }



The creation of the connection to the database from the java application can be done by using the method getConnection by using the methodologies. Note that creating the connection consumes memory. Hence, after you are done with performing all your operations related to the database, you should close the created connection to clear up the resources.

Recommended Articles

This is a guide to JDBC getConnection. Here we discuss the introduction, how it works & the steps required? formulation of URL for database & example. You may also have a look at the following articles to learn more –

You're reading Complete Guide To Jdbc Getconnection

Complete Guide To Db2 Row_Number

Introduction to DB2 row_number

DB2 ROW_NUMBER is a function provided by IBM for generating a sequential number that can begin from 1 and continuously show an iterating value in the column name specified. Analytical Processing (OLAP) and is itself a window function. It is only possible because of this function that we don’t need to reiterate the data of the table again and again to induce a functionality of getting incremental values. It can be used in many real-time applications. One of the most frequent and popular usages of this function is pagination. In this article, we will see how we can use the ROW_NUMBER function, its syntax, and examples.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others


The ROW_NUMBER() function will generate a column that will contain the integer values beginning from the value assigned to the first row. One of the most useful but optional features in this syntax is the usage of partitions which can help us to assign the sequential number based on the groups or partitions of the data.

In the above syntax, the clause for partition is optional in nature. If we use this function, the result set rows are firstly divided into multiple groups based on the partition key and then the ROW_NUMBER function is implemented on each of the grouped data. By default, if we don’t specify the clause for partitions in our query statement then all the rows of the result set are considered as a single partition or group and then the function is implemented for it. The clause for the partition of syntax has the following syntax for specifying the partition key –

PARTITION BY [key1, key2, ….keyn]

Where key1, key2, ….keyn can be the names of the columns or any expression value on the basis of which we want to segregate the result.

The clause for ordering is used to order the data that is generated in the result set based on one or more order keys that are specified. The ORDER BY clause works individually for each partition. We can either specify the ordering to be done in ascending or descending manner depending on our requirement by using ASC or DESC at the end of the ORDER BY clause. By default, if we don’t specify either of them the ordering is done in ascending mode. We can also specify whether we have to display all the NULL values first or last in the result set by using the NULLS FIRST and NULLS LAST statements in the syntax of the clause for the order. The syntax of the order clause is shown below –

ORDER BY sort_exp1 [,sort_exp2, ..., sort_expn]

In the above syntax, the sort_exp1 [,sort_exp2, …, sort_expn] is the list of expressions like columns or collective use it number which is different with respect to each row in the result set. The specification of ASC or DEC is optional in nature to specify the order of the column values and result in ascending or descending order explicitly. By default, it’s done in ascending order. Many times, there is a requirement to display the data in the format where all the NULL values are displayed in the top at first in the result or all the result set is ordered in a way where all the rows with NULL values in it are displayed at the end. This is done by using the NULLS FIRST or NULLS LAST respectively.

Examples of DB2 row_number

Let us take one table named Sales_Customers which is created by using the following query statement –

) ;

The content of the table can be seen by using the following query statement –

SELECT * FROM Sales_Customers;

Which gives the following output –

As it can be seen the table has 14 rows in it and all are sorted based on the primary key customer_id when they are retrieved. We can assign the row number value as a pseudo column to see which row is on which number and how many rows are there by using the window function named ROW_NUMBER and using the following query statement for the same –


The output of the above query statement is as shown below –

If we want to order the data based on the amount of purchase done by that customer. We can do that by using the following query statement and mentioning the column name in the order by clause of the ROW_NUMBER() function –


The output of the above query is as shown below –

row_number <= 15

In big_customers the order by clause made sure that the customers are ordered and sorted based on the amount of bill of customers. Further, the ROW_NUMBER got applicable to all the resulted data having bill amounts arranged in ascending order, hence unique sequential numbers got assigned to each row, and by using the where clause we filtered out all the customers whose row numbers were in the range of 7 to 15 exclusive.

Suppose that we want the top 3 customers from the sales_customers table then we can do that by applying the partition on customer_id and setting the result set in the descending order of the bill amounts of the customer by using the following query statement –


which gives the following output –


We can make use of the ROW_NUMBER function to generate a pseudo column in the result set which is sequential in nature and can be used to assign the unique incremental values to rows.

Recommended Articles

This is a guide to DB2 row_number. Here we discuss the Introduction, syntax, and examples with code implementation. You may also have a look at the following articles to learn more –

Complete Guide To Archicad Shortcuts

Introduction to ArchiCAD Shortcuts

Start Your Free Design Course

3D animation, modelling, simulation, game development & others

Short cut commands of option of File Menu

The very first thing which we do before starting any project or work we create a New file or document and this option you can find in the File menu and for a shortcut of it you can press the Ctrl + N button on the keyboard.

By pressing Ctrl + Alt + N keys of the keyboard you can go for the New and Reset option of this menu.

Ctrl + O keys refer to shortcut key for opening any work, image, or any supported file format of this software.

You can close any window or tab of this software very quickly by pressing the Ctrl + W buttons of the keyboard.

The very important thing you do is to save your document and this option is also available in the File menu but you can press Ctrl + S for saving your work.

Ctrl + Shift + S is for Save as the option of this menu that means if you already saved your document and want to save it in another format or with another name then you can go with this option and its shortcut.

You Plot your work by pressing the Ctrl + P button of the keyboard and for its setup dialog box press the Ctrl + Shift + P button. You can also use Ctrl + P for printing any work.

Ctrl + Q are used for quitting this application program that means when you want to close the whole software then you can go with it.

File Modules and XREF commands’ short cut:

For placing the module in this software you can press Ctrl + ’ keys of the keyboard.

By pressing Ctrl + Shift + ’ you can go for Hotlink Manager.

Shortcut commands of File GDL Objects:

Press Ctrl + Shift + N for a new object in your work.

Ctrl + Shift + O will help for opening any object.

Ctrl + Shift + N can use for the ‘Save Project As’ option.

Edit menu Commands:

We need to undo our steps much time so this shortcut is very helpful during our working and it is Ctrl + Z not only this you can redo any steps you it undo by mistake and press Ctrl + Shift + Z for this.

There may be a lot of elements in our work and many times we need to select them all so press Ctrl + A for selecting them by one shortcut key.

Ctrl + B allows you to repeat your last used command.

For dragging any element of your designed component you can press Ctrl + D keys.

Press Ctrl + E for rotating an object or element.

Ctrl + F can be used for the Split command.

Stretch can do by pressing the Ctrl + H keys of the keyboard.

Ctrl + M keys will work for the mirror command.

Resize can do by pressing Ctrl + K keys.

For Adjust command press Ctrl + – buttons of the keyboard.

Press Ctrl + 0 for the ‘Trim to roof’ command during your designing work.

You can set tools as per your requirement and press Ctrl + T for the tool settings box.

For ‘Editing selection set’ you can go with Ctrl + Shift + T.

With Ctrl + Shift + D you can drag a copy of an object or element and same as for rotating it, you can press Ctrl + Shift + E, and for mirroring a copy of the object go with Ctrl + Shift + M keys of the keyboard.

There is also a shortcut key for editing text. So let us discuss them too.

Edit Commands for Text:

For finding and replace any particular text in your designing we use the Find and Replace command and the shortcut of it is Ctrl + H. You can press Ctrl + F to simply find any text in your design.

Tools’ shortcut keys:

Ctrl + G can be used for grouping a number of elements or objects and you can go with Ctrl + Shift + G for ungrouping them if there is no need for their grouping.

Alt + G will suspend a group and Alt + Shift + G can use for the Auto Group option.

The patch can be created by pressing Ctrl +; keys of the keyboard.

Ctrl + = will work for Explode command.

Press Shift + F6 functional key of a keyboard for ‘Bring to Front’ option and by pressing on by F6 you can use the ‘Bring Forward’ option. F5 can use for the ‘Send backward’ option and Shift + F5 is used for Send to back option.


There is so many short cut in this software which makes our work easy and you need not to worry about remembering them just start working with this software and use short cut keys for any command instead of using traditional ways for that and with a pass of time it will become your habit.

Recommended Articles

This is a guide to ArchiCAD Shortcuts. Here we discuss the introduction and Short cut commands of option of File Menu. You can also go through our other suggested articles to learn more –

A Complete Guide To Django Validators

Introduction to Django Validators

Web development, programming languages, Software testing & others


Raise validationerror("")

The process of raising a validation error occurs through validators. You can achieve this by using the validation error exception, which you can raise at both the form level and the field level. Here using this will raise the error and display it on the console. Place the message to be raised between double quotes. The value within the double quotes will display as the error message. Methods like clean() or even clean_fieldname can raise these validation-based errors. You can use validation errors to check all fields across the forms section. The error message displayed on the screen from the syntax will greatly assist in determining the type of message being printed.

Create a Django Validator

Given below shows the creation of the Django validator:

1. Changes in chúng tôi file

As the syntax section mentions, the email field must be declared in the chúng tôi file. It is noticeable that the email field is declared as the age field in the model. In this case, the email field will be retrieved by default from the user table, which is an inbuilt table associated with four different fields. The fields are username, password, email, password confirmation, etc. These fields will be displayed using the form display used. The user table is an inbuilt table associated with four different fields.

from chúng tôi import models from django.contrib.auth.models import User # Model variables # Create your models here. class Bride(models.Model): Django_Validators_Example_name = models.CharField(max_length=200,null=True) Django_Validators_Example_thegai = models.CharField(max_length=200,null=True) Django_Validators_Example_State = models.CharField(max_length=50,null=True) Django_Validators_Example_District = models.CharField(max_length=50,null=True) Django_Validators_Example_Address = models.TextField(null=True) Django_Validators_Example_Phone = models.BigInteger_Example_Field(null=True) Django_Validators_Example_profession = models.CharField(max_length=200,null=True) Django_Validators_Example_salary = models.BigInteger_Example_Field(null=True) Django_Validators_Example_Under_Graduation_Degree = models.CharField(max_length=200,null=True) Django_Validators_Example_Under_Graduation_college = models.CharField(max_length=400,null=True) Django_Validators_Example_Post_Graduation_Degree = models.CharField(max_length=200,null=True) Django_Validators_Example_Post_Graduation_college = models.CharField(max_length=400,null=True) Django_Validators_Example_Rasi = models.CharField(max_length=200,null=True) Django_Validators_Example_Nakshatra = models.CharField(max_length=200,null=True) def __str__(self): return 2. Changes in chúng tôi file

Make sure you correctly set all the values and database connections in the chúng tôi file to ensure flexible execution of the project. In addition, appropriately declare the mentioned middleware items in the chúng tôi file as these middlewares are responsible for the application’s functioning during the processing of GET and PUT messages. Additionally, the templates used also need to fill so that the template processing happens in the background.

MIDDLEWARE = [ '', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ] ROOT_URLCONF = 'Matrimony.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [Template_DIR,], 'APP_DIRS': True, 'OPTIONS': { 'render_dict_processors': [ 'django.template.render_dict_processors.debug', 'django.template.render_dict_processors.request', 'django.contrib.auth.render_dict_processors.auth', 'django.contrib.messages.render_dict_processors.messages', ], }, }, ] 3. Changes in the chúng tôi file

Add the signup page here using the URL function. Use the views.sign_up_request to render the sign-up page when necessary. The page named “registered” facilitates user registration.

from django.contrib import admin from chúng tôi import path from chúng tôi import url from matrimony_pages import views from chúng tôi import settings from django.conf.urls.static import static urlpatterns = [ url(r'^$',views.Welcome_page,name='Welcome_page'), url(r'Mainpage/',views.Main_page,name='Main_page'), url(r'form/',views.form_view,name='form_view'), url(r"signup/", views.Sign_up_request, name="register"), url(r"login/", views.login_request, name="login"), path(r'profile//',views.Integer_Field_Example_page,name='profile'), url(r'logout/',views.logout_request,name='logout'), url(r'reg/',views.Integer_Field_Example_reg_user,name='reg'), path(r'update//',views.form_update,name='update'), path('admin/',, ]+ static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) 4. Changes in

The chúng tôi has the actual validations in place. The validations are implemented in the NewuserForm. This form serves as a signup request and includes validation rules for the email field. It verifies the input values and throws an error if the email field contains any unexpected values.

chúng tôi

from django import forms from .models import Bride from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django.core.exceptions import ValidationError # Create your forms here. Rasi_CHOICES =( ("1", "Mesham"), ("2", "Rishabam"), ("3", "Mithunam"), ("4", "Kadakam"), ("5", "Simmam"), ("6", "Kanni"), ("7", "Thulam"), ("8", "Viruchikam"), ("9", "Thanusu"), ("10", "Makaram"), ("10", "Kumbam"), ("10", "Meenam"), ) State_Choices = ( ("1", "Mesham"), ("1", "Mesham")) class Valueform(forms.ModelForm): Rasi = forms.ChoiceField(choices = Rasi_CHOICES) class Meta: model = Bride fields = "__all__" class NewUserForm(UserCreationForm): email = forms.EmailField(required=True,error_messages={'required': 'Please enter your name'}) def clean(self): cleaned_data = super(NewUserForm, self).clean() email_passed = cleaned_data.get("email") print("came here") raise forms.ValidationError("Sorry, the email submitted is invalid. All emails have to be registered on this domain only.") return email_passed class Meta: model = User fields = ("username", "email", "password1", "password2") def save(self, commit=True): user = super(NewUserForm, self).save(commit=False) = self.cleaned_data['email'] if commit: return user 5. Formulate an HTML file for displaying the signup form


{% block content %} {% csrf_token %} {{ Sign_up_form }} {% endblock %} function form1() { } function redirect1() { } function redirect2() { }


Conclusion – Django Validators

This article portrays how the email field can be docilely professed in a Django setup. The variations can be rendered to an html page with validation errors populated onto the screen when a bad value has been placed.

Recommended Articles

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

Complete Guide To The Rmi Architecture

Overview of RMI Architecture

Web development, programming languages, Software testing & others

RMI stands for Remote Method Invocation. Java provides an API allowing an object residing in one JVM (Java Virtual Machine) to access or invoke an object running on another. The other JVM could be on the same machine or a remote machine. This is an interesting feature because, in real-time applications, it becomes very easy for Java applications to communicate directly with each other without any external communication mechanism. Also, it is always a need for secure communication between applications based on distributed application architecture.

RMI Design

Before we go into detailed architecture, we will understand the basic design of RMI architecture.

RMI API is provided in the package chúng tôi Let’s introduce two terms for the understanding of RMI design architecture. First is the client, the JVM that will call the remote object; second is the server, the JVM contains the remote object. So, the client will call the server, in this case, on the object for method invocation.

The server will then return the reference of the object to the client. The catch here is both the objects, i.e., local and remote, will appear as a local object on the server. There will be no differentiation between the two. The syntax of the methods of both objects is also the same. Therefore, the server JVM acts like a normal JVM without knowing of any object, whether it is local or remote.

The same object can be both a server and a client. The program obtains the remote object’s reference and utilizes it as a local object. The RMI infrastructure is responsible for finding the remote object, intercepting method calls, and processing the remote request remotely. The client invokes methods on the object only after obtaining a reference to a remote object.

RMI Architecture

Below is a diagram of RMI architecture in a simple way. You will find various forms of the same architecture on the internet, but we have a simple one to help explain it better.

The client and server applications are the respective JVMs of the client machine and server machines. In the RMI application, we write two programs: the client program, which resides on the client, and the server program, which resides on the server machine.

1. Application Layer

This layer is the actual systems, i.e. client and server, which are involved in communication. The Java program on the client side communicates with the Java program on the server side.

2. Stub

We have client objects from the design intro; In RMI architecture, it is known as Stub. It is an object that resides on the client machine and acts as a proxy for the remote object. It is like a gateway for the client program.

The stub has the same methods as a remote object. When the client calls on the stub object, the stub forwards this request to a remote object (Skeleton) via RMI infrastructure, which is then executed on the server.

Initiates connection with remote JVM.

Writes and transmits (Marshals) parameters to remote JVM.

Waits for the result.

Pass the received result to the caller.

3. Skeleton

The server object, which is located in a server machine, is referred to as the Skeleton. Stub communicates with the server application with the help of an intermediate Skeleton object.

The responsibility of the skeleton object is to send parameters to method implementation and send the return values back to the client.

Skeleton Performs the following events:

Invokes the method on an actual Remote object.

Transmit/pass the result to the caller.

4. Stub / Skeleton layer

The Proxy Layer, also known as the Stub/Skeleton layer, intercepts calls made by the client and redirects them to the remote object. Stub and Skeleton are the proxies for the client and server. The Stub and Skeleton objects are like an interface between an application and the rest of the RMI System.

This layer aims to transfer data to Remote Reference Layer by Object Serialization. This process of converting data/objects into a byte stream is known as Marshalling, and the reverse is known as Unmarshalling. Marshaling is performed when requesting the object from the server, and Unmarshalling is performed when data/object reference is received from the server.

5. Remote Reference Layer

The Remote Reference Layer connects the proxy layer to the RMI mechanism. This layer is responsible for communicating and transferring objects between client and server. This layer defines and supports the invocation semantics of the RMI connection.

The remote Reference Layer maintains the session during the method call. i.e., It manages the references made by the client to the remote server object. This layer is also responsible for handling duplicated objects.

6. Transport Layer

The transport layer is responsible for setting up communication between the two machines. This layer uses standard TCP/IP protocol for connection. This layer performs the actual transportation of data. This layer is part of the Remote Reference Layer.


The Remote Method Invocation (RMI) is a highly useful API provided in Java that facilitates communication between two separate Java Virtual Machines (JVMs). It allows an object to invoke a method on an object residing in another address space.

It provides a secure way for applications to communicate with each other. It achieves this functionality using concepts Stub (Client calling object) and Skeleton (Remote object residing on the server).

RMI is used to build distributed applications. It preserves the type of safety. RMI architecture minimizes the complexity of the application in a distributed architecture.

Recommended Articles

This has been a guide to RMI Architecture. Here we discussed the basic concept, RMI design, and architecture. You can also go through our other suggested articles to learn more –

Complete Guide To Javascript Indexof() (Examples)

Introduction to JavaScript indexOf()

The JavaScript indexOf() method finds an item’s occurrence in an array. Method name indicates index means sequence values position. So, the indexOf() method is always used with an array. indexOf() position always starts with 0 and ends with N-1. N is an array length.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

How does the indexOf() method work in JavaScript?

JavaScript indexOf() method always works for the search operation. If the item is not found, it returns a -1 value. The search will begin at the given position through the indexOf() method. Suppose we did not mention any start position; then, the search starts from the 0th index. Like indexOf(“any value or string”,1(position)). While searching the specified item in the indexOf() method, if an item is present more than once, then the indexOf() method returns the first occurred item from the list.


Array_Name.indexOf (item,starting position);


Item: Pass the required item from an array.

Starting position: Pass the number to where to start the search operation.

Examples of JavaScript indexOf()

Examples of the following are given below:

Example #1

Searching the index of a book from an array (without mentioning a position): Below example, we do not specify any position within the indexOf() method, so the search starts at the 0th.


function searchIndex(name) { var book=[“Maths”,”Physics”,”Biology”,”Chemistry”,”English”,”Polity”,”Economics”]; return book.indexOf(name); } var book1=”English”; var book2=”Zoology”; var indexOfBook=searchIndex(book1); var indexOfBookNotExisted=searchIndex(book2); document.write(book2+” position is :”+indexOfBookNotExisted);



As we can observe from the output, we can see if we pass existed items from an array given to the indexOf() method. It will return the actual index position. Whereas if we pass not existed value to the indexOf() method, it will return -1.

Note: Index position always starts from 0.

Example #2

Searching the index of an animal from an array (mentioning a position): Below example, we specify any position within the indexOf() method, so the search starts at the specified index.


function searchIndexOfAnimal(animal,postion) { var animal=[“Dog”,”Cat”,”Monkey”,”Rabbit”,”Tiger”,”Lion”,”Cow”]; return animal.indexOf(animal,postion); } var animal1=”Cow”; var animal2=”Dog”; var indexOfAnimal=searchIndexOfAnimal(animal1,1); var indexOfAnimalNotExisted=searchIndexOfAnimal(animal2,1); document.write(animal2+” position is : “+indexOfAnimalNotExisted);


In the above example, we can see while we are accessing Cow from the array, then prints 6 as the index position. While trying to access the Dog from the array, then prints -1. It may surprise the output. The animal array has a Dog value but prints -1 because we are starting the search operation at the 1st index position. So, the indexOf() method neglects the 0th index and starts searching from the 1st.

Example #3

Searching the index of a character from an array (mentioning a position): In a String, every character considers as the particular index. Example: “How” is a string with the H=0th, o=1st, and w=2nd index positions, respectively.


function searchStringIndex(character,postion) { var string=”Hi, I am Amardeep. I am Paramesh.”; return string.indexOf(character,postion); } var c1=”a”; var c2=”am”; var c3=”Paramesh”; var indexOfStr1=searchStringIndex(c1); var indexOfStr2=searchStringIndex(c2,9); var indexOfStr3=searchStringIndex(c3); document.write(c3+” position is : “+indexOfStr3);



If we pass multiple characters at a time to the indexOf() method, first, it will check whether that sequence of characters existed or not. If it existed, it returns the first index position in that sequence of characters. So, the searchStringIndex(“Paramesh”) gives 24 as output. Here P’s index position is 24, so it printed 24 as output. We can conclude when multiple characters are in sequence, if those are present in a string, it will print the first character index.

Example #4

Access exceeding index from an array:


function getIndex(name,postion) { var array=[“1″,”Apple”,”@12″,”Paramesh”]; return array.indexOf(name,postion); } var name=”Paramesh”; var indexOfArray=getIndex(name,6); document.write(name+” position is : “+indexOfArray);



Above, we are trying to access out of the bounded index of 6. First, the indexOf() method checks whether the given position is within the actual position limit or not. An actual position limit is only 3, but we are trying to access the 6th index value. So, it gives -1 as output.


indexOf() method has the only item; it will start searching from the 0th index. indexOf() method has item and position, then it will begin by specifying the position index value. No search item results in a -1 value.

Recommended Articles

This is a guide to JavaScript indexOf(). Here we discuss the introduction, how the indexOf() method works in JavaScript, and the examples. You can also go through our other related articles to learn more–

Update the detailed information about Complete Guide To Jdbc Getconnection 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!