Saturday, September 4, 2010

Multidimensinal Arrays in Java

Hello Hardik,

We can make arrays of 3 or 4 or more dimensions though these are
impossible to draw in two dimensions, and they are bit harder to
imagine in our mind.


In Java language, a multidimensional (two or more dimensional) arrays
are simply an array whose components are themselves arrays (Jagged
arrays) or you can say an array of arrays or an array of arrays of
arrays an so on.

In the Java, arrays are objects (you can say 'reference types'), are
dynamically created. A variable of array type holds a reference to an
object. Declaring a variable of array type does not create an array
object or allocate any space for array components.

for example,

Here is declaration of java arrays:
int []a;
int [][]b;
int [][][]c;

"a","b",and "c" are called object variables, and in case of their
declaration space - when declared inside the methods, these object
variables are uninitialized. If these variables are fields (declared
as members of class) then they have a special null value.

You can create an array using (1) creation expression (a=new int[4])
or (2) array

initializer. (a=new int[]{1,22} or int []a={11,22,33,44}).

Example-1
int [][][]threeD=new int[2][3][7];

Example-2

int [][][]threeD;

//Create an array that can store references of two arrays of
arrays of int

elements
threeD=new int[2][][];

//create an array that can store references of 4 arrays of int
threeD[0]=new int[4][];
//create an array that can store references of 2 arrays of int
threeD[1]=new int[2][];

//create an array that can store n int elements
threeD[0][0]=new int[]{22,33,44};
threeD[0][1]=new int[]{7,6,4,4,74};
threeD[0][2]=new int[10];
threeD[0][3]=new int[]{17,26,34,3,7,4};

threeD[1][0]=new int[]{100,200};
threeD[1][1]=new int[]{10,20,30,40,50,60,70};

Example - 3 Array initializer

int [][][]threeD=
{
{
{22,33,44},
{7,6,4,4,74},
new int[10],
{17,26,34,3,7,4}
},
{
{100,200},
{10,20,30,40,50,60,70}
}
};

*/

public class Sample {
public static void main(String []args) {
//There are 3 class rooms, each class room has 4 students.
// Write a 3D array to store marks of five subject for each
student.
int [][][]a=new int[3][4][5];
a[0][0][0]=88; //1st class, 1st student and mark of 1st subject.
a[0][0][1]=98; //1st class, 1st student and mark of 2nd subject.
a[0][1][0]=77; //1st class, 2nd student and mark of 1st subject.


//Another way to declare & create 3D.
//marks of five subject of raj & ram (one-dim for each student)
int []raj={55,66,77,66,55};
int []ram={77,88,66,55,98};

//Now declare & create an array to store references of "raj" &
"ram" array
int [][]studs1={raj,ram};

//marks of five subject of foo, bar & boo (one-dim for each student)
int []foo={85,66,77,66,55};
int []bar={37,68,66,55,98};
int []boo={87,48,66,55,98};

//Now declare & create an array to store references of
"foo","bar" & "boo"

array
int [][]studs2={foo,bar,boo}; //2D - Array of oneD array

//Now, declare & create an array that hold the references of
"studs1" and

"studs2"

int [][][]classes={studs1,studs2}; //3D - Array of TwoD array


System.out.println(studs1[0][0]); //marks of 1st sub of raj
System.out.println(studs2[2][0]); //marks of 1st sub of boo

System.out.println(classes[0][0][0]); // marks of 1st class
of 1st sub of raj


//Print array elements
for(int i=0;i

Thursday, September 2, 2010

Thursday, May 14, 2009

Read resources (xml, text, images) from JAR



 

JAR

The Java Archive (JAR) file format enables you to bundle multiple files into a single archive file. Typically a JAR file contains the class files and auxiliary resources associated with applets and applications.

Get Resource from JAR

Use java.lang.Class class's method : getResource() and getResourceAsStream() - The simplest way to retrieve a resource from JAR file.

  1. URL getResource(String name) - Finds a resource with a given name.
  2. InputStream getResourceAsStream(String name) - Finds a resource with a given name.

EXAMPLE – Source code

This example demonstrate how to read an XML file which is packed into the JAR. This is a java-console application.


 

XML File

Std.xml

<?xml version="1.0" ?>

<Students>

<Std ClassName="1st">

<Roll>10</Roll>

<Name>Mr. Raj</Name>

</Std>

<Std ClassName="3rd">

<Roll>11</Roll>

<Name>Mr. Rohan</Name>

</Std>

</Students>

JAVA source code

ReadStd.java

import org.w3c.dom.*;

import javax.xml.parsers.*;

import java.io.*;


 

public class ReadStd {

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

// Read Resource

InputStream ii=ReadStd.class.getResourceAsStream("Std.xml");


 

DocumentBuilderFactory fact=DocumentBuilderFactory.newInstance();

DocumentBuilder build=fact.newDocumentBuilder();


 

Document doc=build.parse(ii);


 

Element root=doc.getDocumentElement();

System.out.println(root.getTagName());


 

NodeList list=root.getChildNodes();

System.out.println("Total Nodes : " + list.getLength());


 

int i;


 

for(i=0;i<list.getLength();i++) {

Node t=list.item(i);

if(t.hasAttributes())

System.out.print("Node has an attribute");

System.out.println(t.getNodeName() + " " + t.getNodeType() + " " + t.getNodeValue());

if(t.hasChildNodes()) {

NodeList p=t.getChildNodes();

for(int j=0;j<p.getLength();j++) {

                Node t1=p.item(j);

        System.out.println(t1.getNodeName() + " " + t1.getNodeType() + " " + t1.getNodeValue());

}

}

}

}

}

MANIFEST File

m.mf

Main-Class: ReadStd

 

NOTE: All three files namely Std.xml, ReadStd.xml and m.mf must be reside in the same directory/folder.


 

COMPILE & PACKAGE

> javac ReadStd.java

> jar –cvfm kk.jar m.mf .

[

Read more about Packaging & Deployment of Java application.


http://java.sun.com/docs/books/tutorial/deployment/jar/index.html


 

]

DEPLOY & EXECUTE

Copy the kk.jar anywhere or any folder and issue following command to execute it.

> java -jar kk.jar


 


 


 


 

Tuesday, April 21, 2009

Language Integrated Query Part - I

LINQ

LANGUAGE-INTEGRATED QUERY is the name of technologies based on the integration of query capabilities in .NET compliant languages.

With LINQ, a query is now a language construct. By using query syntax, you can perform complex filtering, ordering, and grouping operation of data sources with minimum code. You use the same basic query expression patterns to query and transform data in SQL databases, ADO.NET Datasets, XML documents and streams, and .NET collections.

LINQ Parts

There are three parts of Query operation

  1. The Data source
  2. The Query (Query Expression)
  3. Execute the Query

The Data Source

Types that support IEnumerable(T) or a derived interface such as the generic IQueryable(T) are called Queryable Types. A Queryable Types requires no modification or special treatment to serve as a LINQ data source. If the source data is not already in memory as a queryable type, the LINQ provider must represent it as such.

LINQ provider

A library that implements the functionality of the standard query operators for a specific kind of data source. A LINQ provider translates queries expressed in Visual Basic or C# into the native language of the data source.

LINQ to ADO.NET

A technology that enables you to query over any enumerable object in ADO.NET by using the LINQ programming model. LINQ to ADO.NET consists of two related LINQ technologies: LINQ to DataSet and LINQ to SQL.

LINQ to DataSet

A LINQ technology that makes it easier and faster to query over data cached in a DataSet object. The queries are expressed in the programming language itself and not as string literals embedded in the application code.

LINQ to Objects

The use of LINQ to query in-memory data such as arrays and lists.

LINQ to SQL

A LINQ technology that provides a run-time infrastructure for managing relational data as objects. In LINQ to SQL, the data model of a relational database is mapped to an object model expressed in the programming language of the developer.


 

LINQ to XML

An in-memory programming interface that enables you to work with XML from within the .NET Framework programming languages. You can query and modify a document, and then, after modifying it, you can save it to a file or serialize the result and send it over the Internet.

The Query

The query specifies what information to retrieve from the data source or sources. Optionally, a query also specifies how that information should be sorted, grouped, and shaped before it is returned. A query is stored in a query variable and initialized with a query expression.

Query Operators

The standard query operators are the methods that form the Language-Integrated Query (LINQ) pattern. Most of these methods operate on sequences, where a sequence is an object whose type implements the IEnumerable<(Of <(T>)>) interface or the IQueryable<(Of <(T>)>) interface. The standard query operators provide query capabilities including filtering, projection, aggregation, sorting and more.

Two Sets of LINQ Operator

There are two sets of LINQ standard query operators:

  1. One that operates on objects of type IEnumerable<(Of <(T>)>).
  2. The other that operates on objects of type IQueryable<(Of <(T>)>).

The methods that make up each set are static members of the Enumerable and Queryable classes, respectively. They are defined as extension methods of the type that they operate on. This means that they can be called by using either static method syntax or instance method syntax.

The standard query operators differ in the timing of their execution, depending on whether they return a singleton value or a sequence of values. Those methods that return a singleton value (for example, Average and Sum) execute immediately. Methods that return a sequence defer the query execution and return an enumerable object.

Query Expression

  1. Query expressions can be used to query and to transform data from any LINQ-enabled data source.
  2. Query expressions are easy to learn because they use many familiar C# language constructs.
  3. The variables in a query expression are all strongly typed, although in many cases you do not have to provide the type explicitly because the compiler can infer it.
  4. A query is not executed until you iterate over the query variable in a foreach statement.
  5. At compile time, query expressions are converted to Standard Query Operator method calls according to the rules set forth in the C# specification. Any query that can be expressed by using query syntax can also be expressed by using method syntax. However, in most cases query syntax is more readable and concise.
  6. As a rule when you write LINQ queries, use query syntax whenever possible and method syntax whenever necessary. There is no semantic or performance difference between the two different forms. Query expressions are often more readable than equivalent expressions written in method syntax.
  7. Some query operations, such as Count or Max, have no equivalent query expression clause and must therefore be expressed as a method call. Method syntax can be combined with query syntax in various ways.
  8. Query expressions can be compiled to expression trees or to delegates, depending on the type that the query is applied to. IEnumerable<(Of <(T>)>) queries are compiled to delegates. IQueryable and IQueryable<(Of <(T>)>) queries are compiled to expression trees.

Iteration Statement: foreach

The foreach statement repeats a group of embedded statements for each element in an array or an object collection. The foreach statement is used to iterate through the collection to get the information that you want, but should not be used to change the contents of the collection to avoid unpredictable side effects.

At any point within the foreach block, you can break out of the loop by using the break keyword, or step to the next iteration in the loop by using the continue keyword. A foreach loop can also be exited by the goto, return, or throw statements.

Snippet


 

// Traverse a one-dim array

int []a={11,22,33};

foreach(int p in a) {

Console.WriteLine(p);

}


 

// Traverse a two-dim array

int [,]a={{11,22,33},{22,33,44},{66,77,88}};

foreach (int p in a){

Console.WriteLine(p);

}


 

// Generic List

List<float> p = new List<float>();

p.Add(100f);

p.Add(100.23f);

p.Add(56.44f);

foreach (float t in p){

Console.WriteLine(t);

}


 

// Generic Set

HashSet<int> p = new HashSet<int>();

p.Add(11);

p.Add(40);

p.Add(3);

foreach (int t in p){

Console.WriteLine(t);

}


 

// Generic Stack

Stack<int> p = new Stack<int>();

p.Push(33);

p.Push(44);

p.Push(55);


 

foreach (int t in p){

Console.WriteLine(t);

}


 

// Traverse an ArrayList

ArrayList a = new ArrayList();

a.Add(100);

a.Add("Hello");

a.Add(10.44d);

a.Add(34.44f);

a.Add(DateTime.Now);


 

foreach (object p in a){

Console.WriteLine(p + " " + p.GetType().Name );

}


 

// Traverse Dictionary Object – Hashtable

Hashtable a = new Hashtable();

a.Add("no", 100);

a.Add("name", "Mr. Rajesh");

a.Add("address", "Mehsana");


 

foreach (object p in a){

DictionaryEntry e = (DictionaryEntry)p;

Console.WriteLine(e.Key + " " + e.Value);

}


 


 


 


 

Wednesday, March 4, 2009

C Programming – Memory Management

An Overview of Your Computer

Your computer system consists of two parts: hardware and software. The hardware consists of all the physical parts of the machine. It illustrates that your computer's hardware consists of the physical components of your PC. The software is everything else. Software comprises the programs and data that interact with your hardware. The C language is an example of software.

The System Unit and Memory

The system unit is the large, box-shaped component of the computer. This unit houses the PC's microprocessor. You might hear the microprocessor called the CPU, or central processing unit. The CPU acts like a traffic cop, directing the flow of information throughout your computer system. The CPU is analogous also to the human brain. When you use a computer, you are actually interacting with its CPU. All the other hardware exists so the CPU can send information to you (through the monitor or the printer), and you can give instructions to the CPU (through the keyboard or the mouse).

The CPU also houses the computer's internal memory. Although the memory has several names, it is commonly referred to as RAM (random-access memory). RAM is where the CPU looks for software and data. When you run a C program, for example, you are instructing your computer's CPU to look in RAM for that program and carry out its instructions. C uses RAM space when it is loaded.

RAM is used for many things and is one of the most important components of your computer's hardware. Without RAM, your computer would have no place for its instructions and data. The amount of RAM can also affect the computer's speed. In general, the more RAM your computer has, the more work it can do and the faster it can process data.

The amount of RAM is measured by the number of characters it can hold. A character in computer terminology is called a byte, and a byte can be a letter, a number, or a special character such as an exclamation point or a question mark. If your computer has 640,000 bytes of RAM, it can hold a total of 640,000 characters.

You want as much RAM as possible to hold C, data, and the system programs. Computer RAM is relatively inexpensive, so if your computer has less than 640K bytes of memory, you should consider purchasing additional memory to increase the total RAM to 640K. You can put more than 640K in most PCs. There are two types of additional RAM: extended memory and expanded memory (they both offer memory capacity greater than 640K). You can access this extra RAM with some C systems, but most beginning C programmers have no need to worry about RAM beyond 640K.

RAM is volatile; when you turn the computer off, all RAM is erased. Therefore, you must store the contents of RAM to a nonvolatile, more permanent memory device (such as a disk) before you turn off your computer. Otherwise, you lose your work.

Bell Labs first developed the C programming language in the early 1970s, primarily so Bell programmers could write their UNIX operating system for a new DEC (Digital Equipment Corporation) computer.

Until that time, operating systems were written in assembly language, which is tedious, time-consuming, and difficult to maintain. The Bell Labs people knew they needed a higher-level programming language to implement their project quicker and create code that was easier to maintain.

Because other high-level languages at the time (COBOL, FORTRAN, PL/I, and Algol) were too slow for an operating system's code, the Bell Labs programmers decided to write their own language. They based their new language on Algol and BCPL. Algol is still used in the European markets, but is not used much in America.

BCPL strongly influenced C, although it did not offer the various data types that the makers of C required. After a few versions, these Bell programmers developed a language that met their goals well. C is efficient (it is sometimes called a high, low-level language due to its speed of execution), flexible, and contains the proper language elements that enable it to be maintained over time.

In the 1980s, Bjourn Stroustrup, working for AT&T, took the C language to its next progression. Mr. Stroustrup added features to compensate for some of the pitfalls C allowed and changed the way programmers view programs by adding object-orientation to the language. The object-orientation aspect of programming started in other languages, such as Smalltalk. Mr. Stroustrup realized that C++ programmers needed the flexibility and modularity offered by a true OOP programming language.