Wednesday, 4 September 2019

Derived Data Types-Collections


ArrayList

inta[]=new int a[5];
Limitation of normal array

  • Contain same data type of element
  • Array size is fixed


Operations On Array List:

1.How to declare array list
2.How to add elements/values to array list
3.Find size of array list
4.remove the element/values from array list
5.insert a new value into array list
6.Read values from array list


1.How to declare array list

ArrayList list=new ArrayList();

ArrayList <String> list=new ArrayList<Strings>();
ArrayList <Integer> list=new ArrayList<Integer>();

2.How to add elements/values to array list

  list.add("John");
  list.add("Smith");

3.Size of array list

 list.size();

4.Remove the element/values from array list
  list.remove(Index);

5.Insert a new value into array list
list.add(index,value)

6.Read values from array list
for(Object s:list) // Object type variable can hold any type of values
{
System.out.printlin(s);
}

HashMap
 
  1. How to declare Hashmap
  2. Remove elements from Hashmap
  3. Read pairs from Hashmap
Declaration:
HashMap <Integer,String> hm=new HashMap<Integer,String>();

Adding pairs into hashmap:
hm.put(101,"John");
hm.put(102,"Scott");
hm.put(103,"David");
hm.put(104,"Smith");
hm.put(105,"Kim");

Print pairs from hasmap:
System.out.println(hm);

Remove a pair from hashmap:
hm.remove(103);
System.out.println("After removing a pair: "+hm)

Reading pairs using for loop:
for(Map.Entry m:hm.entrySet())
{
System.out.println(m.getkey()+" "+m.getValue());
}

JDBC

Java Database Connectivity

Pre-requisite
1.Download database driver(.jar file)
2.Add driver jar to your project

Steps to write JDBC program
1.Create a connection
2.Create a query/statement
3.Execute statement/query
4.close connection

Create a connection:
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521/pdborcl","hr","hr")

Create a query/Statement:
Statement stmt=con.createStatement();
String s="insert into student values(101,'Scott')";

Execute statement query:
stmt.executeQuery(s);

Close connection
con.close();

For select query we need to loop the data from database

String s="select employee_id,first_name,last_name from employees"

ResultSet rs=stmt.executeQuery(s);

while(rs.next())
{
int eid=rs.getInt("EMPLOYEE_ID");
String fname=rs.getString("FIRST_NAME");
String lname=rs.getString("LAST_NAME")
}

No comments:

Post a Comment