Sunday, April 1, 2012

Arrays


Declaration of Arrays
---------------------------

One Dimensional Arrays:
-----------------------------

form1
-------
          datatype arrname[];

form2
-------
          datatype [] arrname;

Examples:
          int number[];
          float average[];
          int[] count;
          float[] marks;

Creation of Arrays:
-----------------------
We need to create in the memory.
syntax:
          arrayname=new type[size];

Examples:
          number=new int[5];
          average=new float[10];

Combine the two steps- declaration and creation
syntax:
          datatype arrname[]=new datatype[size];
ex:
          int number[]=new int[15];
Initialization of Arrays:
----------------------------
syntax:
          datatype arrayname[]={list of values};
          ex:
          int number[]={34,45,56,67};
          It is possible to assign an array object to another.
          int a[]={2,43,5};
          int b[];
          b=a;

get and print the array elements
-------------------------------------
import java.io.*;
class array1
{
          public static void main(String args[])throws IOException
          {
                   DataInputStream din=new DataInputStream(System.in);
                   int a[]=new int[10];
                   int n,i;
                   System.out.println("How many numbers :");
                   n=Integer.parseInt(din.readLine());
                   System.out.println("Enter  "+n+" Numbers :");
                   for(i=0;i<n;i++)
                   a[i]=Integer.parseInt(din.readLine());
                   System.out.println("Array elements are :");
                   for(i=0;i<n;i++)
                             System.out.println(a[i]);
                   }
          }


Average an array of values.
--------------------------------
import java.io.*;
class array2
{
          public static void main(String args[])throws IOException
          {
                   DataInputStream din=new DataInputStream(System.in);
                   int a[]=new int[10];
                   int n,i,result=0;
                   System.out.println("How many numbers :");
                   n=Integer.parseInt(din.readLine());
                   System.out.println("Enter  "+n+" Numbers :");
                   for(i=0;i<n;i++)
                   {
                   a[i]=Integer.parseInt(din.readLine());
                   result=result+a[i];
                    }

                   System.out.println("Average is "+result/n);

                   }
          }

Sorting n numbers
----------------------
import java.io.*;
class array3
{
          public static void main(String args[])throws IOException
          {
                   DataInputStream din=new DataInputStream(System.in);
                   int a[]=new int[10];
                   int n,i,j,t;
                   System.out.println("How many numbers :");
                   n=Integer.parseInt(din.readLine());
                   System.out.println("Enter  "+n+" Numbers :");
                   for(i=0;i<n;i++)
                   a[i]=Integer.parseInt(din.readLine());
                   for(i=0;i<n-1;i++)
{
                             for(j=i+1;j<n;j++)
                             {
                                       if(a[i]>a[j])
                                       {
                                      t=a[i];
                                      a[i]=a[j];
                                      a[j]=t;
                                       }
                             }
}
                   System.out.println("Sorted list :");
                   for(i=0;i<n;i++)
                             System.out.print(a[i]+"   ");
                   }
          }

Multidimensional Arrays
----------------------------
Syntax:
          datatype arrname[][]=new datatype[][];
ex:
          int twoD[][]=new int[4][5];
get and print the matrix element
--------------------------------------
import java.io.*;
class array4
{
          public static void main(String args[])throws IOException
          {
                   DataInputStream din=new DataInputStream(System.in);
                   int a[][]=new int[2][2];
                   int n,i,j;
                   System.out.println("Enter 4 Elements:");
                   for(i=0;i<2;i++)
                   for(j=0;j<2;j++)
                   a[i][j]=Integer.parseInt(din.readLine());
                   System.out.println("Matrix Elements are :");
                   for(i=0;i<2;i++)
                   {
                             System.out.print("\n");
                             for(j=0;j<2;j++)
                             {
                             System.out.print(a[i][j]+"\t");
                             }
                    }
}
}

Manually allocate differing size second dimensions
-------------------------------------------------------------
import java.io.*;
class array5
{
          public static void main(String args[])throws IOException
          {
                   DataInputStream din=new DataInputStream(System.in);
                   int a[][]=new int[4][];
                   a[0]=new int[1];
                   a[1]=new int[2];
                   a[2]=new int[3];
                   a[3]=new int[4];
                   int i,j,k=0;

                   for(i=0;i<4;i++)
{
                             for(j=0;j<i+1;j++)
{
                             a[i][j]=k;
                             k++;
                             }
}

                    for(i=0;i<4;i++)
                   {
                             System.out.print("\n");
                             for(j=0;j<i+1;j++)
                             {
                             System.out.print(a[i][j]+"\t");
                             }
                    }
}
}

Three D Matrix:
--------------------
import java.io.*;
class array4
{
          public static void main(String args[])throws IOException
          {
                   DataInputStream din=new DataInputStream(System.in);
                   int a[][][]=new int[3][4][5];
                   int i,j,k;
                   for(i=0;i<3;i++)
                   for(j=0;j<4;j++)
                   for(k=0;k<5;k++)
                   a[i][j][k]=i*j*k;

                   for(i=0;i<3;i++)
{

                   for(j=0;j<4;j++)
{
                   for(k=0;k<5;k++)
                   System.out.print(a[i][j][k]+"   ");
                   System.out.println();
          }
          System.out.println();
}
}
}

length
-------
it will always hold the size of the array.
//This program demonstrates the length array member.
class Length
{
          public static void main(String args[])
{
                   int a1[]=new int[10];
                   int a2[]={3,45,56,67,-45,23,-9};
                   int a3[]={5,4,3,23};

                   System.out.println("length of a1 is "+a1.length);
                   System.out.println("length of a2 is "+a2.length);
                   System.out.println("length of a3 is "+a3.length);
          }
}
---------------------
class CommandLine
{
          public static void main(String args[])
{
                   for(int i=0;i<args.length;i++)
                   System.out.println("args["+i+"]="+args[i]);
          }
}

Vectors
----------
The Vector class contained in the java.util package.  This class can be used to create a generic dynamic array known as vector that can hold objects of any type and any number.  The objects do not have to be homogeneous.
ex:
          Vector intVect=new Vector();//declaring without size
          Vector list=new Vector(5);
Vectors possess a number of advantages over arrays.
1.  It is convenient to use vectors to store objects.
2.  A vector can be used to store a list of objects that may vary in size.
3.  We can add and delete objects from the list as and when required.
we cannot directly store simple data type in a vector, we can only store objects.  Therefore we need to convert simple types to objects.This can be done using the wrapper classes

Important Vector Methods
Method Call                                                Task performed
list.addElement(item)        Adds the item specified to the list at the end
list.elementAt(10)             Gives the name of the 10th object
list.size()                           Gives the number of objects present
list.removeElement(item)    Removes the specified item from the list
list.removeElementAt(n)   Removes the item stored in the nth position of       the list
list.removeAllElements()            Removes all the elements in the list
list.copyInto(array)              Copies all items from list to array.
list.insertElementAt(item,n) Inserts the item at nth position

Working with vectors and arrays
---------------------------------------
import java.util.*;
class LanguageVector
{
 public static void main(String args[])
{
          Vector list=new Vector();
          int length=args.length;
          for(int i=0;i<length;i++)
          {
                   list.addElement(args[i]);
          }
          list.insertElementAt("JAVA",2);
          int size=list.size();
          String listArray[]=new String[size];
          list.copyInto(listArray);
          System.out.println("List of Languages :");
          for(int i=0;i<size;i++)
          {
                   System.out.println(listArray[i]);
          }

}
}

Wrapper Classes
---------------------
Vectors cannot handle primitive data types like int,float,long,char, and double.
Primitive data types may be converted into object types by using the wrapper classes contained in the java.lang package.

Wrapper Classes for Converting Simple Types

Simple Type                                     Wrapper Class
boolean                                    Boolean
char                                         Character
double                                     Double
float                                         Float
int                                            Integer
long                                         Long


Converting Primitive Numbers to Object Numbers Using Constructor
----------------------------------------------------------------------------------
Methods
-----------
Constructor Calling                                    Conversion Action

Integer IntVal=new Integer(i);           Primitive Integer to Integer object
Float FloatVal=new Float(f)             Primitive Float to Float object
Double DoubleVal=new Double(d);  Primitive Double to Double object
Long LongVal=new Long(l);             Primitive long to Long object

Converting Object Numbers to Primitive Numbers Using typeValue()
----------------------------------------------------------------------------------
Method
----------
Method Calling                                                    Conversion Action

int i=IntVal.intValue();                     Object to primitive integer
float f=FloatVal.floatValue();           Object to primitive float
long l=LongVal.longValue();             Object to primitive long
double d=DoubleVal.doubleValue(); Object to primitive double

Converting Numbers to String Using toString() Method
-------------------------------------------------------------------
Method Calling                                 Conversion Action

str=Integer.toString(i);                     Primitive integer to string
str=Float.toString(f);                          Primitive float to string
str=Double.toString(d);                   Primitive double to string
str=Long.toString(l);                       Primitive long to string

Converting String Objects to Numberic Objects Using the Static Method
--------------------------------------------------------------------------------------ValueOf()
-------------
Method Calling                                           Conversion Action

DoubleVal=Double.valueOf(str);      Converts string to Double object
FloatVal=Float.valueOf(str);            Converts string to Float object
IntVal=Integer.valueOf(str);              Converts string to Integer object
Longval=Long.valueOf(str);              Converts string to Long object

Converting Numeric Strings to Primitive Numbers Using Parsing Methods
-----------------------------------------------------------------------------------------
Method Calling                                           Conversion Action

int i=Integer.parseInt(str);                 Converts string to primitive integer
long l=Long.parseLong(str);             Converts string to primitive long



The Enumeration Interface
------------------------------
The Enumeration interface defines the methods by which we can enumerate (obtain one at a time) the elements in a collection of objects.

Enumeration specifies the following two methods:
boolean hasMoreElements( )
Object nextElement( )
When implemented, hasMoreElements( ) must return true while there are still more elements to extract, and false when all the elements have been enumerated.

nextElement( ) returns the next object in the enumeration as a generic Object reference.

Hashtable
------------
package:

import java.util
Like HashMap, Hashtable stores key/value pairs in a hash table. When using a Hashtable, we specify an object that is used as a key, and the value that we want linked to that key.

The Hashtable constructors are shown here:
Hashtable( )
Hashtable(int size)
Hashtable(int size, float fillRatio)
Hashtable(Map m)

Method                                                       Description
void clear( )                                       Resets and empties the hash table.
Object clone( )                         Returns a duplicate of the invoking object.
Enumeration elements( )            Returns an enumeration of the values
contained in the hash table.

Object get(Object key) Returns the object that contains the value
associated with key. If key is not in the hash table, a null object is returned.

Enumeration keys( ) --Returns an enumeration of the keys contained in the hash table.

Object put(Object key, Object value) Inserts a key and a value into the hash
table. Returns null if key isn’t already in the hash table; returns the previous value associated with key if key is already in the hash table.

No comments:

Post a Comment

Slider

Image Slider By engineerportal.blogspot.in The slide is a linking image  Welcome to Engineer Portal... #htmlcaption

Tamil Short Film Laptaap

Tamil Short Film Laptaap
Laptapp

Labels

About Blogging (1) Advance Data Structure (2) ADVANCED COMPUTER ARCHITECTURE (4) Advanced Database (4) ADVANCED DATABASE TECHNOLOGY (4) ADVANCED JAVA PROGRAMMING (1) ADVANCED OPERATING SYSTEMS (3) ADVANCED OPERATING SYSTEMS LAB (2) Agriculture and Technology (1) Analag and Digital Communication (1) Android (1) Applet (1) ARTIFICIAL INTELLIGENCE (3) aspiration 2020 (3) assignment cse (12) AT (1) AT - key (1) Attacker World (6) Basic Electrical Engineering (1) C (1) C Aptitude (20) C Program (87) C# AND .NET FRAMEWORK (11) C++ (1) Calculator (1) Chemistry (1) Cloud Computing Lab (1) Compiler Design (8) Computer Graphics Lab (31) COMPUTER GRAPHICS LABORATORY (1) COMPUTER GRAPHICS Theory (1) COMPUTER NETWORKS (3) computer organisation and architecture (1) Course Plan (2) Cricket (1) cryptography and network security (3) CS 810 (2) cse syllabus (29) Cyberoam (1) Data Mining Techniques (5) Data structures (3) DATA WAREHOUSING AND DATA MINING (4) DATABASE MANAGEMENT SYSTEMS (8) DBMS Lab (11) Design and Analysis Algorithm CS 41 (1) Design and Management of Computer Networks (2) Development in Transportation (1) Digital Principles and System Design (1) Digital Signal Processing (15) DISCRETE MATHEMATICS (1) dos box (1) Download (1) ebooks (11) electronic circuits and electron devices (1) Embedded Software Development (4) Embedded systems lab (4) Embedded systems theory (1) Engineer Portal (1) ENGINEERING ECONOMICS AND FINANCIAL ACCOUNTING (5) ENGINEERING PHYSICS (1) english lab (7) Entertainment (1) Facebook (2) fact (31) FUNDAMENTALS OF COMPUTING AND PROGRAMMING (3) Gate (3) General (3) gitlab (1) Global warming (1) GRAPH THEORY (1) Grid Computing (11) hacking (4) HIGH SPEED NETWORKS (1) Horizon (1) III year (1) INFORMATION SECURITY (1) Installation (1) INTELLECTUAL PROPERTY RIGHTS (IPR) (1) Internal Test (13) internet programming lab (20) IPL (1) Java (38) java lab (1) Java Programs (28) jdbc (1) jsp (1) KNOWLEDGE MANAGEMENT (1) lab syllabus (4) MATHEMATICS (3) Mechanical Engineering (1) Microprocessor and Microcontroller (1) Microprocessor and Microcontroller lab (11) migration (1) Mini Projects (1) MOBILE AND PERVASIVE COMPUTING (15) MOBILE COMPUTING (1) Multicore Architecute (1) MULTICORE PROGRAMMING (2) Multiprocessor Programming (2) NANOTECHNOLOGY (1) NATURAL LANGUAGE PROCESSING (1) NETWORK PROGRAMMING AND MANAGEMENT (1) NETWORKPROGNMGMNT (1) networks lab (16) News (14) Nova (1) NUMERICAL METHODS (2) Object Oriented Programming (1) ooad lab (6) ooad theory (9) OPEN SOURCE LAB (22) openGL (10) Openstack (1) Operating System CS45 (2) operating systems lab (20) other (4) parallel computing (1) parallel processing (1) PARALLEL PROGRAMMING (1) Parallel Programming Paradigms (4) Perl (1) Placement (3) Placement - Interview Questions (64) PRINCIPLES OF COMMUNICATION (1) PROBABILITY AND QUEUING THEORY (3) PROGRAMMING PARADIGMS (1) Python (3) Question Bank (1) question of the day (8) Question Paper (13) Question Paper and Answer Key (3) Railway Airport and Harbor (1) REAL TIME SYSTEMS (1) RESOURCE MANAGEMENT TECHNIQUES (1) results (3) semester 4 (5) semester 5 (1) Semester 6 (5) SERVICE ORIENTED ARCHITECTURE (1) Skill Test (1) software (1) Software Engineering (4) SOFTWARE TESTING (1) Structural Analysis (1) syllabus (34) SYSTEM SOFTWARE (1) system software lab (2) SYSTEMS MODELING AND SIMULATION (1) Tansat (2) Tansat 2011 (1) Tansat 2013 (1) TCP/IP DESIGN AND IMPLEMENTATION (1) TECHNICAL ENGLISH (7) Technology and National Security (1) Theory of Computation (3) Thought for the Day (1) Timetable (4) tips (4) Topic Notes (7) tot (1) TOTAL QUALITY MANAGEMENT (4) tutorial (8) Ubuntu LTS 12.04 (1) Unit Wise Notes (1) University Question Paper (1) UNIX INTERNALS (1) UNIX Lab (21) USER INTERFACE DESIGN (3) VIDEO TUTORIALS (1) Virtual Instrumentation Lab (1) Visual Programming (2) Web Technology (11) WIRELESS NETWORKS (1)

LinkWithin