Sei sulla pagina 1di 23

Basic Programming using Java

Introduction to Java

.+

Introduction to Java
At the end of this chapter you will be able to understand the Java programming language environment and create simple Java programs.

SCOPE
1.1 What is Java? 1.2 Java Versions and Environment 1.3 Features of Java 1.4 Program Types in Java 1.4.1 Applications 1.4.2 Applets 1.5 Java Language Components 1.5.1 Operators 1.5.2 Data types 1.5.3 Variables and Literals 1.5.4 Statements and Expressions 1.5.5 Comments 1.5.6 Variable Scope 1.6 Programming Constructs 1.6.1 if 1.6.2 switch 1.6.3 while 1.6.4 do-while 1.6.5 for 1.6.6 break 1.6.7 continue 1.7 Arrays

Basic Programming using Java

Introduction to Java

1.1 What is Java?


Java language was developed by Sun Microsystems in 1991 as a part of the Green project, a research group working to develop software to control consumer electronic devices. During this time, they developed a device called Star7, for which the operating system was planned to be developed in C++. However, one of the team members, James Gosling, was not very appreciative of the performance of C++. Hence, he developed a new language for star7. He named it as Oak as he used to see an Oak tree outside his office. Later on, it was found that the name Oak was being used by some other language, so Sun renamed this language as Java. Java is a platform independent object oriented programming language. When you are writing programs, you always consider where this program is finally going to be executed. For instance, if the program is going to be executed on windows platform, you use the Microsoft Foundation Classes or if it is a Mac machine, then you use the Mac OS Toolbox. Also, while finally implementing the programs you ensure that along with the source code the compiler has also been sent as every machine uses some or the other kind of processor, and it becomes necessary to compile your program according to the destination machines processor. It would be virtually impossible to implement the applications on the Internet, if we imagine the same scenario there because you dont know where your program is finally going to be downloaded and run. In order to counteract this problem Java has an in-built mechanism called JVM (Java Virtual Machine) which makes your application compatible to the clients machine and your program can run on any machine in the Internet. Unlike C++, Java is totally an object-oriented language. Everything in Java can only be written inside the classes. Though you may think that the programs would somewhat become rigid by confining everything only inside the classes, but it certainly has a profound effect on the programming style. In C++, you have a total flexibility of writing your programs by combining the object oriented or structured programming style. But this mixed approach has a side effect, as the program tends to be less object oriented if the programmer is more comfortable with the structured programming style, and thus depriving the program of the actual OOP benefits. Moreover, it becomes easier for the designers to design if the approach is totally object oriented than the mixed one.

Basic Programming using Java

Introduction to Java

1.2 Java Versions and Environments


Till now Java has undergone three significant version changes. Java was first launched as Java 1.0, which is still extensively supported by a majority of browsers. Then came Java 1.1, which had language enhancements, an improved user interface, and event handling. Since then Java has undergone many more changes and finally Sun has come up with the latest version as Java 1.2.2 which it calls Java 2. Java is available in many environments. Java software is most easily available as JDK (Java Development Toolkit) version 1.0, 1.1 or 1.2. You can download JDK from the Internet at the site http://java.sun.com/products/jdk free of cost. There are many other development environments for Java. Some of them are as follows: Java Workshop Borland Jbuilder Symantec Visual Cafe Visual Java (VJ++) SuperCede etc.

1.3 Features of Java


Java, apart from being object oriented, and providing various features for Internet programming has many more features which makes it distinctively an appealing language.

Architecture Neutral
Over a period of time Java has gained a huge popularity because of its very nature of platform independence. Java has established itself as a high performance cross platform language. Java programs can run on any kind of client machine on the Internet without actually making any changes to the source code. As mentioned earlier this is achieved through JVM or Java Virtual Machine. JVM does not allow your program to directly interact with the hardware and acts as an interface between the hardware and the code. So as Java program reaches the client side, it helps in the execution of program specific to the local processor. The following description is about how a Java program is executed. Java programs (.java file) execute in two stages. It is compiled at the developers end, uploaded on the Internet server, then it is interpreted again and executed. Java programs are compiled and converted to something called byte code( .class file). Byte code is nothing but a series of instructions in the form of bytes. These instructions are not specific to any machine, but are written for the JVM. JVM is the software for a virtual machine, i.e., the machine that really does not exist, but in reality is a simulated

Basic Programming using Java

Introduction to Java

environment. The byte code or the .class file is not capable of running on its own, and it has to resides in the web page. You can make the web page through HTML and call the .class file inside it. The web page is then transported over the Internet by uploading it at a specific web site. At the client side the web page is accessed using a browser. The browser should have Java component inside it, i.e., it should be Java enabled otherwise it would simply not recognize the applet and take it as an ordinary HTML text. When the web page is accessed by the client, the Java program embedded inside the HTML document begins to run. As the very first step, a security check is applied on the incoming Java code in order to find out whether it is a true Java code or not. It would then be linked and finally interpreted according to the current machines architecture. In the meantime, if any errors or exceptions occur, they would be handled and the program runs.

-------------------------------------

Source code (.java file)

Security check

Rejected

Class library loaded Java compiler Code transported on the internet 0011010 0100010 0100001 0101100 Byte code (.class file) Executable code Exceptions handled Rejected interpreted

Developers end

Internet

Client end

Fig. 1.1 how an applet runs

Robust
Most of the programs succumb to failure because due emphasis is not paid either on memory management or exceptional behaviour of the program in different situations. It is very important to look after the memory management issues than just achieving the aim of the module or program. Sometimes certain exceptional conditions like file not found

Basic Programming using Java

Introduction to Java

are encountered when you expected the file to be definitely present. As a result the program collapses! These issues are specifically dealt with in Java through the techniques called garbage collection and exception handling. In garbage collection a daemon thread (thread which becomes alive when the system is comparatively free) keeps on freeing the objects, which are not being referenced. So, the programmer does not have to worry about the heap area piling up. Through exception handling any unexpected behaviour, like accidentally trying to access an element of an array beyond its upper bound, which would lead to the crashing of the program, can be dealt with during runtime itself. Appropriate corrections can be made during runtime through the piece of codes exclusively written for such error prone situations, and the program can proceed smoothly from there on.

Reliable, Safe and Secure


Java program is capable of being transported over the Internet and running on anybodys machine, but how does the receiver ensure that the incoming program is not going to cause any harm. You always dont download the information from a known source and it may be possible that the downloaded program accesses the file system and deletes certain files. So in order to make the Java programs reliable, Java does not allow the program coming from the Internet and running in the browser, called the applet, to access the local systems file system. Though the pointers introduce immense flexibility and power in writing programs, Java has eliminated the usage of pointers completely. This makes Java programs very safe as the possibility of arbitrarily overwriting any memory location or hacking the system resources is not there. As the applet arrives at its destination, before it is interpreted, a security check is applied on it. This ensures that the Java code, which has arrived, is a true Java code, i.e., it does not contain any undesirable elements like the viruses. You can also sign your Java code before sending it and the receiver can tally the signatures before receiving it. This is called digitally signing your code and if the signatures do not match, you would come to know that some third person has hacked the code and might as well tampered it.

Simple and Easy to Learn


Once the basic concepts of object-oriented programming are clear, you can very easily write productive Java programs. Many languages provide a number of ways to accomplish a particular task by providing n number of features that could ever be used. This, in turn makes the language chaotic and difficult to learn. Java has not adopted this approach and has tried to keep mainly essential features, emphasized upon their usefulness and tried to avoid complexity.

Basic Programming using Java

Introduction to Java

Powerful
Java unleashes an immense power through a complete range of classes present in the class library. Java 2 has over a thousand of classes, which aids in achieving just about anything in a program. This does not mean snatching away the creativity by introducing a good amount of encapsulation. These classes provide n number of small independent functions. The combination of these and object oriented methodology enables you to write flexible and powerful programs.

Distributed
Java objects can be distributed over various servers on the Internet. These objects can be included in any Java program, and it run them as if they were its own components. This significantly introduces reusability in Java.

1.4 Program Types in Java


The Java language basically has two types of programs, the applets, and the applications. Applets are the programs that have the capability to run on the Internet through a browser, whereas the applications do not possess this capability. For a browser to be able to run an applet, it should have a Java component inside it. The Internet Explorer 3.1 and above are able to run the applets successfully. There is another major difference between the two the applications can access the local file system and the resources, but the applet is restricted from doing that. Applications are trustworthy as are you very much aware of its functionality, and you know the person who has handed over the program to you. In case of applets, you do not know who is the author of the program, or if the program safe enough etc. Keeping this in mind, the applets are allowed to access the file system or anything else of only that machine, from where they came(the server hosting the applet), rather than the local or the client machine on which they will run.

1.4.1 Applications
The applications and applets are written completely in the form of classes as everything in Java has to be present inside the class. There cannot be anything written outside a class, unlike C++ where you could define the functions etc. outside a class. The class names should be following the naming conventions and it is case sensitive. While executing an application, the JVM looks for the class with the same name as the file name. This class is called the initiating class. The public access specifier is given with the class so that the class is visible from outside, i.e., to the JVM. It must have a method called the main() which is the first method automatically executed by the complier. From this method all the other classes and their methods are linked. A simple example of an application is given below:

Basic Programming using Java

Introduction to Java

public class SimpleApp { public static void main ( String args[]) { System.out.println( You have created your first application ); } }
Listing 1.1 A Simple Java Application

There is no inbuilt development environment in JDK. The programs can be written in the DOS editor- edit, or notepad. The file should be saved with the same name as the initiating class name with the .java extension, like in the above case it is SimpleApp.java. Now, let us see the various components in the definition of the main() method. The public keyword is given so as to make the main() method visible outside the program, i.e., the compiler is capable of seeing the main() method. The static keyword is given so that the JVM is able to access the main() method directly without instantiating the class that contains the main(). The keyword void is given, as the main() is not supposed to return anything to the runtime environment from where it originated. The System.out.println() is a method to print on the output stream. It automatically provides a linefeed after printing the contents. The program is then compiled with the Java complier (javac). Before you compile the program set the path as path=.;c:\java2\bin;c:\java2\lib;c:\java2\include, where java2 is the directory storing Java software.
c:> javac SimpleApp.java

After compilation a .class file is made which contains the byte code. It is then executed as:
c:> java SimpleApp

1.4.2 Applets
Similar to the applications, we start writing an applet with a class having the same name as the filename. There is no main method, unlike the application. There are various other methods present in an applet. All these methods would be dealt with extensively later on. Let us now look at how an applet runs.
import java.applet.*; import java.awt.*; public class Apple extends Applet {

Basic Programming using Java

Introduction to Java

public void paint(Graphics g) { g.drawString( An Apple a Day Keeps the Doctor Away , 50,50); } }
Listing 1.2 Java Applet

The first two statements are for importing or including the packages in the applet. A package is a set of classes categorized under a specific name and kept in the library. This program has included the java.awt package as it is using the paint() method and java.applet as the main class must be inherited from the Applet class. The extends keyword is used for inheritance. The paint (Graphics g) is a method used to draw a picture or text on the applet. It gets the applets graphics context automatically as a parameter. The graphics context is nothing but an area where you would write or draw something. So, the Graphics g in the paint () function gets the applets graphics context, a handle to the applets area where drawing etc. would happen. We are using the function drawString( String text, int posx, int posy ) in order to write some text on the applet. The above applet must be saved with the same name as that of the class ,i.e., Apple.java and compiled as:
javac Apple.java

This makes the .class file which contains the byte code. Since this is an applet, the .class file now will have to be embedded inside an HTML document and run through a browser. A very basic HTML document may be written as:
<html> <head> <title> The Applet is Running </title> </head> <body> <applet code=Apple height=200 width=200 > </applet> </html>
Listing 1.3 HTML Code Enveloping an Applet

<html> </html> tag specifies the beginning and the end of the HTML document <head> </head> tag specifies the header in which title section has been specified through <title> </title> <body> </body> tag specifies the document region where text can be written and in which we want our applet to appear .

Basic Programming using Java

Introduction to Java

Finally, the applet is called through the <applet> </applet> tag. The code specifies the .class file name, height and width determines the size of the applet. Now, you can call the HTML document in the browser. As soon as the file is opened, the applet enveloped inside the HTML file also starts running.

1.5 Java Language Components


The Java language has a various components like variables, constants, different data types, operators and various programming constructs. All of these are described below.

1.5.1 Operators
TYPE Arithmetic DESCRIPTION addition subtraction multiplication division modulus increment addition assignment subtraction assignment multiplication assignment division assignment modulus assignment decrement NOT SYMBOL + * / % ++ += -= *= /= %= -~ USAGE int no = 1 + 1 int no = 1 1 int no = 1 * 1 int no = 1 / 1 int no = 1 %1 no++ or ++no no = no + 4 or no += 4 no = no 4 or no -= 4 no = no * 4 or no *= 4 no = no / 4 or no /= 4 no = no % 4 or no %= 4 no-- or --no a = 2 Binary Rep. a = 10 ~a = 01 a = 2 b = 3 Binary Rep. a = 10 b = 11 a & b = 10 a = 2 b = 3 Binary Rep. a = 10 b = 11 a | b = 11 a = 2 b = 3

Bitwise

AND

&

OR

EXCLUSIVE-OR

Basic Programming using Java

Introduction to Java

TYPE

DESCRIPTION

SYMBOL

Shift right

>>

USAGE Binary Rep. a = 10 b = 11 a ^ b = 01 a = 8 Binary Rep. a = 1000 a = a>>3 a = 0001 Hence a=1 a = 8 Binary Rep. a = 1000 a = a>>>3 a = 0001 Hence a=1 a = 2 Binary Rep. a = 10 a = a<<3 a = 10000 Hence a=16

Shift right zero fill

>>>

Shift left

<<

The >> operator is used with the numeric values. It shifts each high order bit with the previous value, but preserving the signed bit. This may be undesirable in certain cases like when you are working with pixel based values in graphics and you want to fill a zero in the high order bit irrespective of its previous value. This aspect is taken care of when you use the >>>(right shift zero fill operator).
TYPE Relational DESCRIPTION Equal to Not equal to Greater than Less than Greater-than or equal to Less-than or equal to SYMBOL == != > < >= <=

1.5.2 Data Types


Java defines eight basic or simple data types. Apart from these, there are other data types, which are the classes, interface and the arrays. Class and interface would be dealt with in the later sessions. Rest of these data types along with their features are given below:

Basic Programming using Java

Introduction to Java

DATA TYPE

WIDTH

RANGE

USAGE

Numbers & Floating point numbers byte 8 -128 to 127 Useful when working with stream of data short s;

short

16

-32,768 to 32,767 -2,147,483,648 to 2,147,483,647 -263 to 263 -1

int

32

int x=200;

long

64

long seconds;

double

64

1.7 e-308 to 1.7 e+308

Used when more precision is needed double speed_of_light;

float

32

3.4 e-038 to 3.4 e+038

Used when a lesser level of precision is needed float sinResult;

Characters char 16 0 to 65,536 Java uses unicode to define characters Characters can be assigned character values or codes equivalent to some character char char choice = y ; trap = 27;

boolean

true / false

boolean flag = true;

Basic Programming using Java

Introduction to Java

1.5.3 Statements and Expressions


The statements simply mean the commands in a language, which result in certain action. Some of the statements in Java as follows:
char reply = y; int book_no; System.out.println( resulting statement);

Every statement in Java has to be followed by a semicolon. The clubbing of the statement can be done by confining the statements in the opening and closing curly braces {} . The set of statements defined within the opening and closing curly braces is called a block.
-----------{ int count = 0; --------------------{ count = count + 1; --------------------} }

Outer block Inner block

Expressions are compose of operators and operands, which leads to producing values. For instance, in the above example, the statement count = count + 1; contains the expression count + 1.

1.5.4 Variables and Literals


Variables are the very basic unit of storage. It can be defined as :
type identifier = value; For example: boolean status = true; int height = 60;

Literals are nothing but the constant values. There can be literals in numbers, string etc. Given below are the examples of literals:
lilly , Tulip

Basic Programming using Java

Introduction to Java

100, 5179, 79 etc.

1.5.5 Comments
Comments basically can be written down in two ways. These are the // and /* */. // is used to comment a single line. It can be placed anywhere in the line and the compiler would ignore anything following it. /* */ is used to mark a block as a comment entry. This is very useful when the comment entry extends several lines.

1.5.6 Variable Scope


The scope of a variable is defined by the block in which it is declared. The variable is visible from the block in which it is declared, to all subsequent blocks inside it. Consider the following example:
public class Visibility { public static void main(String args[]){ block1: // This is a label { int gvar = 100; block2: { int lvar = 200; System.out.println(Global variable + gvar); System.out.println(Local variable + lvar); } } gvar = gvar + 1; System.out.println(Global variable + gvar); lvar = lvar + 1; // Error } } }
Listing 1.4 Showing the visibility of the variables

In this example, two variable gvar and lvar are defined in the outer (block1) and inner( block2) blocks respectively. The variable gvar is visible in both the blocks, but the variable lvar is visible only in the inner block, i.e.,block2. As soon as, you try to access lvar outside the block2 you receive an error message.

Note that it is not allowed in Java to define the variables with the same name, but different scopes, i.e, if you try to define the variable gvar in the block2 again, it would not be acknowledged as a separate variable, hence you receive an error message.

Basic Programming using Java

Introduction to Java

1.6 Programming Constructs


In object oriented programming languages, a lot of emphasis is given to data, its storage, security and usage. However, due importance should also be given to the flow of control of the program in order to control the execution order of your program. Programming constructs like branching, looping etc. are provided in Java to write the programs efficiently. The syntax of these constructs has been borrowed from C++ and nothing much has been added to it.

1.6.1 if- else


The if-else construct causes the statement to execute different pieces of code depending upon a boolean condition. The syntax is given below.
if ( boolean_test_condition) { // Statements if condition is true } else { // Statements when the condition is false }

For instance, the following example compares the two numbers and finds out the smaller of the two.
public class Comp { public static void main(String args[ ]) { int number1 = 10; int number2 = 20; if (number1 < number2) System.out.println(Number1 is smaller than number2); else System.out.println(Number2 is smaller than number1); } }
Listing 1.5 Finding the smaller number

It may happen that you would like to test multiple conditions through multiple if statements. These if statements are written independently if the conditions are not related to each other. However, if the conditions are dependent on each other, they can be written together using the nested if statements. For instance, the following example states that each consecutive if statement is dependent upon the previous one and only if the previous if statement is false the next one is executed.

Basic Programming using Java

Introduction to Java

--------------------------if ( marks > 90 ) grade = Excellent; else if ( marks > 75) grade = Merit; else if ( marks > 50) grade = Pass; else grade = Fail; ---------------------------

1.6.2 switch
If you want to execute different pieces of code based upon the changing value of a single variable, the switch statement provides a simple and clean solution to it. Though the same can be achieved through nested if statements, but switch is a less complex way to write this type of code. Here is the syntax and an example of the switch construct:
switch(expression) { case 1 : // statements break; case 2 : // statements break; case 3 : //statements break; default : //statements }

Depending upon the value of the expression a single case would be executed, i.e., if the expression value matches any of the case conditions, that particular case construct would be executed. In case, the value supplied in the switch construct does not match any of the cases, the default case is executed. The break statement must be supplied after finishing with the statements of a particular case.
----------------------switch(letter) { case a :

Basic Programming using Java

Introduction to Java

case e : case i : case o : case u : System.out.println( The letter is a vowel); break; default : System.out.println( The letter is a consonant); break; } -----------------------

If the break statement is omitted for a particular case construct, further statements of the next case would keep on getting executed until a break statement is encountered or the switch construct reaches its end.

1.6.3 while
The while loop is the most basic of the looping constructs. The loop depends upon a boolean condition. As long as the condition is true the loop continues, otherwise, it terminates. The while loop takes the following form:
-----------while ( boolean-condition) { //statements } ----------------------int counter = 1; while (counter <= 10 ) { sum=sum + counter; counter = counter + 1; } -----------------------

In this example the while loop runs till the time the variable counter becomes greater than 10 as this leads to the boolean condition becoming false. Inside the body of the loop the counter is added to sum variable. This eventually gives the sum of first ten natural numbers.

1.6.4 do-while

Basic Programming using Java

Introduction to Java

Sometimes it becomes desirable to run the body of the loop at least once irrespective of the while conditions being true or false. In such cases, the do-while loop is preferred over the while loop. This loop takes the form as:
do { // statements } while ( boolean-condition )

For example , you want to show a menu and then accept the choice from the user. If the user opts to quit the menu is dismissed. In this case, the menu is at least shown once irrespective of the option, which could then be to continue or quit.
----------------------int option = 1; do { System.out.println( System.out.println( System.out.println( System.out.println( System.out.println( ----------------------}while( option != 3) ; ----------------------String Manipulation); 1. Reverse the String); 2. Copy the String); 3. Exit); Choose the option (1 / 2 /3) ); // Statements for taking in the input

1.6.5 for
The for loop is similar to the while loop. It gets executed in four parts. Firstly, the control comes to the initialisation part, next it checks the condition, then it goes to the body, and finally it reaches the iteration part. From next iteration onwards it does not go back to the initialisation part and proceeds as termination condition body iteration until the termination condition becomes false.
For (initialisation ; termination-condition ; iteration ) { / / Statements } -----------------------

Basic Programming using Java

Introduction to Java

For example, this loop draws a line made up of fifty hyphens.


-----------for ( int i = 0 ; i <50 ; i ++) { System.out.println(-); } -----------------------

You can also nest the for loops. This depicted in the following case:
public class Num_Pyramid { public static void main( String args[]) { for ( int i = 1 ; i < 4 ; i ++) { System.out.print(\n ); for ( int j = 1 ; j { System.out.print( j ); } } } }
Listing 1.6 Drawing a pyramid of numbers

<= i ;

j ++)

The output for the above program would be;


1 1 2 1 2 3

The System.out.println() function does not provide a linefeed on its own and if required it is given explicitly using the \n escape sequence.

Basic Programming using Java

Introduction to Java

1.6.6 break
The break statement is used to prematurely exit out of the current loop. Let us take an example, in which you try to find out that whether a number is a prime number or not.
public class FindPrime { public static void main ( String args[ ] ) { int i = 2, j , max = 50; boolean flag = true; int rem = 0; while ( i < max ) { for ( j = 2; j < i ; j ++ ) { rem = i % j ; if ( rem == 0 ) { flag = false; break; } } if ( flag == true) { System.out.println( i ); } flag = true; i++; } } }

Listing 1.7 finding prime numbers upto fifty

The above example finds out the prime numbers up to 50. If a number is not divisible by any number apart from 1 and the number itself; it is a prime number. Here, the matter of concern is the break statement. The moment the break statement is encountered, it takes the control out of the current loop, i.e., the for loop, to the statement just after it. There may be situations where when you not only would like to break out of the current loop, but also from the loop superior in hierarchy. This can be achieved by making use of labels along with the break statement. It may take the form as:
----------------------loop1_label:

Basic Programming using Java

Introduction to Java

for( ; ; ) { for( ; ; ) { break loop1_label; } } -----------------------

1.6.7 continue
The continue statement also is used inside the loop. Unlike the break statement, it terminates the current iteration only and resumes the loop. When continue is encountered, all the statements below it are ignored and the control goes to the condition of the while loop. It is used as:
while (condition) { ---------------------------------if ( condition) continue;
------------

The example given below shows the usage of the continue statement. This piece of code searches for a book code. If the book code is found in the file it prints the details, otherwise it goes to the beginning of the loop.
------------ // Open the file ------------ // Accept the key to be searched while ( < not end-of-file-condition >) { ----------------------if ( key != book_code ) continue; print_record(); ----------------------}

Basic Programming using Java

Introduction to Java

1.7 Arrays
Arrays are a group of contiguous similar type of variables referred by a common name. Arrays can be of any dimension, one dimension or two dimension etc. Consider the following example, which shows the creation and the handling of a two-dimension array using a class called empbonus. This class stores the employees name and bonus in the array and then displays them.
public class EmpBonus { public static void main(String args[]) { String ebonus[ ][ ] = new String [2][5]; ebonus[0][0] = P. K. Roy; ebonus[0][1] = Anita Rana; ebonus[0][2] = Mr. Sai; ebonus[0][3] = Deepak Sharma; ebonus[0][4] = Jagjeet Singh; ebonus[1][0] = 6000; ebonus[1][1] = 8000; ebonus[1][2] = 10000; ebonus[1][3] = 5000; ebonus[1][4] = 5500; for(int i=0; i < 5; i++) { System.out.println(Employee Name : + ebonus[0][i]); System.out.println(Bonus Received : + ebonus[1][i]); } } }
Listing 1.8 Array handling

In Java most of the features of array handling are similar to that of any other language, like C or C++, but its creation is slightly different. It takes the form as:
type name[ ] = new type[ no. of elements ]; int item_Code[ ] = new int[10] String week_Days[ ] = new String[ 7 ];

The new keyword is used to allocate the memory to the variables of reference type. So, it must be used here in order to allocate memory to the array. In Java the string handling is done with the help of a class called the String class. This class not only enables you to create a string, but also provides a number of functions to do string handling. Two dimension or multi dimension arrays can be created as:

Basic Programming using Java

Introduction to Java

float twoD_Array[ ][ ] = new float[5][10];

It is also possible to create a two-dimension array with different number of columns. It is depicted as below:
int list[ ][ ] = new int[2][ ]; list[0] = new int[6]; list[1] = new int[15];

It looks like the following:

In this array you are able to store two lists with different number of elements.

Basic Programming using Java

Introduction to Java

SUMMARY
Java was developed by Sun Microsystems in 1991, originally called Oak. Java is platform independent, object oriented language. It has many good features which gives it an edge above others. Java is architecture neutral, robust, simple and easy to learn, reliable, safe, secure, powerful and distributed. Java is client server and the power of Java lies in its ability to run on any platform. It has two types of program, application and applet. Applications do not run on the internet, whereas the applets run on the internet. Applets are embedded in the HTML document and they require a browser to run. The statements the commands in a language, which result in certain action whereas the expressions result in some value. Variables are defined the type name = value. Comments in Java are with // or /* */. The Java language has a various data types, like the arithmetic, relational and bitwise operators. It has various programming constructs like the if, while, do-while, for loop, break, continue etc. Arrays can be defined as single dimension array or multi dimension array. The multi dimension arrays can be defined with varying number of columns in the rows.

Potrebbero piacerti anche