Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
SlideShare a Scribd company logo
Java Programming basics http://ir.linkedin.com/in/ghorbanihamid
١
Java – Overview
- was created in 1991 by (James Gosling, Mike Sheridan, and Patrick Naughton)
- developed and Published by Sun Microsystems which in 1995 as Java 1.0
- Initially called Oak, its name was changed to Java because there was
already a language called Oak.
Editions:
Java ME (Micro Edition): targeting environments with limited resources (mobile
devices, micro-controllers, sensors, gateways, TV set-top boxes, printers)
Java SE (Standard Edition): core Java programming platform
targeting desktop and server environments It contains all of the libraries and APIs that
any Java programmer should learn (java.lang, java.io, java.math, java.net, java.util,
etc...).
Java EE (Enterprise Edition):
targeting large scale softwares (Network or Internet environments)
Versions:
 JDK 1.0 (January 23, 1996)[38]
 JDK 1.1 (February 19, 1997)
 J2SE 1.2 (December 8, 1998)
 J2SE 1.3 (May 8, 2000)
 J2SE 1.4 (February 6, 2002)
 J2SE 5.0 (September 30, 2004)
 Java SE 6 (December 11, 2006)
 Java SE 7 (July 28, 2011)
 Java SE 8 (March 18, 2014)
Note: As of 2015, only Java 8 is officially supported
Java Programming basics http://ir.linkedin.com/in/ghorbanihamid
٢
Principles:
guaranteed to be Write Once, Run Anywhere.
Object Oriented: In Java, everything is an Object.
Secure: With Java's secure feature it enables to develop virus-free, tamper-
free systems.
Portable: Compiler in Java is written in ANSI C with a clean portability
boundary, which is a POSIX subset.
Platform Independent: Unlike many other programming languages including C
and C++, when Java is compiled, it is not compiled into platform specific machine, rather
into platform independent byte code. This byte code is distributed over the web and
interpreted by the Virtual Machine (JVM) on whichever platform it is being run on.
JVM (Java Virtual Machine): bytecode interpreter
JVM is a virtual machine which work on top of your operating system to provide a recommended
environment for your compiled Java code. JVM only works with bytecode. Hence you need to
compile your Java application(.java) so that it can be converted to bytecode format (.class file). Which
then will be used by JVM to run application. JVM only provide the environment It needs the Java code
library to run applications.
Java Programming basics http://ir.linkedin.com/in/ghorbanihamid
٣
JDK (Java Development Kit)
JDK contains everything that will be required to develop and run Java application.
JDK = JRE + development tools
JRE (Java Run time Environment)
JRE contains everything required to run Java application which has already been compiled. It
doesn’t contain the code library required to develop Java application.
JRE = JVM + Java Packages Classes (like util, math, lang, awt, swing etc) + runtime libraries.
The programming structure:
Sun Micro System has prescribed the following structure for developing java application.
Java Programming basics http://ir.linkedin.com/in/ghorbanihamid
۴
Package: Package is a collection of classes, interfaces and sub-packages. A sub package contains
collection of classes, interfaces and sub-sub packages etc. java.lang.*; package is imported by default and
this package is known as default package.
Class: In Java, every line of code that can actually run needs to be inside a class. Notice that when we
declare a public class, we must declare it inside a file with the same name, otherwise we'll get an error
when compiling.
Methods: A method is a set of code which is referred to by name. When that name is encountered in a
program, the execution of the program branches to the body of that method. When the method is
finished, execution returns to the area of the program code from which it was called, and the program
continues on to the next line of code.
Language basics:
Case Sensitivity: Java is case sensitive, which means identifier Hello and hello would have
different meaning in Java.
Class Names: For all class names the first letter should be in Upper Case. If several words are used to
form a name of the class, each inner word's first letter should be in Upper Case.
Example: class MyFirstJavaClass
Method Names: All method names should start with a Lower Case letter. If several words are used
to form the name of the method, then each inner word's first letter should be in Upper Case.
Example: public void myMethodName()
Program File Name: Name of the program file should exactly match the class name. When saving
the file, you should save it using the class name (Remember Java is case sensitive) and append '.java' to
the end of the name (if the file name and the class name do not match, your program will not compile).
Example: Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved as
'MyFirstJavaProgram.java'
public static void main(String args[]): Java program processing starts from the main() method
which is a mandatory part of every Java program.
Java Programming basics http://ir.linkedin.com/in/ghorbanihamid
۵
Java Data types:
There are two data types available in Java:
- Primitive Datatypes: There are 8 basic data types available within the Java language.
Name Type
Minimum
value
Maximum value Default
value
byte number, 1 byte -128 , 128 0
short number, 2 bytes -32,768 32,767 0
int number, 4 bytes - 2,147,483,648
(-2^31)
2,147,483,647 (2^31 -1) 0
long number, 8 bytes -2^63 2^63 -1 0L
float float number, 4 bytes 1.4E^-45 3.4028235E^38 0.0f
double float number, 8 bytes 4.9E^-324 1.7976931348623157E^308 0.0d
char a character, 2 bytes 'u0000' (or 0) 'uffff' (or 65,535) 'u0000'
boolean true or false, 1 bit false
*** Note: To declare and assign a number use the following syntax:
Variable_Type variable_Name;
Example:
int a, b, c; // Declares three ints, a, b, and c.
int a = 10, b = 10; // Example of initialization
byte B = 22; // initializes a byte type variable B.
double pi = 3.14159; // declares and assigns a value of PI.
char a = 'a'; // the char variable a is initialized with value 'a'
- Reference/Object Datatypes : A reference type is a data type that’s based on a class, a
reference type is an instantiable class
Example:
Person person = new Person();
Java Programming basics http://ir.linkedin.com/in/ghorbanihamid
۶
Java Variables
To declare and assign a number use the following syntax:
Variable_Type variable_Name;
***Following are the types of variables in Java:
- Local Variables
- Class Variables (Static Variables)
- Instance Variables (Non-static Variables)
Local Variables: Local variables are declared in methods, constructors, or blocks and are visible
only within the declared method, constructor, or block.
Instance Variables: Instance variables belong to the instance of a class(an object) and every
instance of that class (object) has it's own copy of that variable.
Example:
public class Product {
public int barcode; // an instance variable
}
public class MyFirstJavaProgram {
public static void main(String[] args) {
Product product1 = new Product();
product1.barcode = 123456;
System.out.println(product1.barcode);
}
}
Class Variables: Class variables also known as static variables are declared with the
static keyword in a class, but outside a method, constructor or a block. class variable is
a variable defined in a class of which a single copy exists, regardless of how many instances
of the class exist.
public class MyFirstJavaProgram {
static int barcode;
}
Java Programming basics http://ir.linkedin.com/in/ghorbanihamid
٧
Java Modifiers:
Like other languages, it is possible to modify classes, methods, etc., by using modifiers. There are
two categories of modifiers:
Access Modifiers: default, public , protected, private
Non-access Modifiers: final, abstract, strictfp
if-else statement:
An if statement can be followed by an optional else statement, which executes when the
Boolean expression is false.
if( x < 20 ) {
System.out.print("This is if statement");
}else {
System.out.print("This is else statement");
}
while-loop
A while loop statement in Java programming language repeatedly executes a target
statement as long as a given condition is true.
int x = 0;
while( x < 20 ) {
System.out.print("This is while statement : " + x);
X++;
}
do-while-loop
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed
to execute at least one time.
int x = 0;
while( x < 20 ) {
System.out.print("This is while statement : " + x);
X++;
}
Java Programming basics http://ir.linkedin.com/in/ghorbanihamid
٨
for-loop
A for loop is a repetition control structure that allows you to efficiently write a loop that
needs to be executed a specific number of times.
for( int i = 0; i < 20; i++ ) {
System.out.print("This is for-loop statement : " + i);
}
For-each loop
The for-each loop(Advanced or Enhanced For loop) introduced in Java5. It is mainly
used to traverse array or collection elements. The advantage of for-each loop is that it
eliminates the possibility of bugs and makes the code more readable.
for(data_type variable : array | collection){ …. }
Example 1:
int arr[]={12,13,14,44};
for( int i:arr) {
System.out.print("This is for- each loop statement : " + i);
}
Example 2:
ArrayList<String> list=new ArrayList<String>();
list.add("vimal");
list.add("sonoo");
list.add("ratan");
for(String s:list){
System.out.println(s);
}
Java Programming basics http://ir.linkedin.com/in/ghorbanihamid
٩
Branching Statements
Java offers three branching statements:
 break
 continue
 return
Break
This statement can be used to terminate a switch, for, while, or do-while loop
for(int i=1;i<=10;i++){
if(i==5){
break;
}
System.out.println(i);
}
Continue
The continue keyword causes the loop to immediately jump to the next iteration of the loop.
for(int i=1;i<=3;i++){
for(int j=1;j<=3;j++){
if(i==2&&j==2){
continue;
}
System.out.println(i+" "+j);
}
}
return
used to exit from the current method.
public static int minFunction(int n1, int n2) {
int min;
min = n2;
return min;
}
Java Programming basics http://ir.linkedin.com/in/ghorbanihamid
١
Switch statement
The Java switch statement executes one statement from multiple conditions. It is like if-
else-if ladder statement.
Example:
public class SwitchExample {
public static void main(String[] args) {
int number=20;
switch(number){
case 10: System.out.println("10");break;
case 20: System.out.println("20");break;
case 30: System.out.println("30");break;
default:System.out.println("Not in 10, 20 or 30");
}
}
}
public class Test {
public static void main(String args[]) {
char grade = 'C';
switch(grade) {
case 'A' :
System.out.println("Excellent!");
break;
case 'B' :
case 'C' :
System.out.println("Well done");
break;
case 'D' :
System.out.println("You passed");
case 'F' :
System.out.println("Better try again");
break;
default :
System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);
}
}
Java Programming basics http://ir.linkedin.com/in/ghorbanihamid
١
Arrays
Java arrays, is a data structure which stores a fixed-size sequential collection of elements
of the same type. An array is used to store a collection of data, but it is often more useful
to think of an array as a collection of variables of the same type.
Syntax:
1)
dataType[] arrayName; or
dataType arrayName[];
Example:
// declaration
Int[] myList;
// instantiate object
myList = new int[10];
2)
dataType[] arrayName = new datatype[size];
Example:
double[] myList = new double[10];
Array initialization:
1) after declaration:
 a[0]=10;
 a[1]=20;
 a[2]=70;
 a[3]=40;
2) with declaration:
int[] arr = {1, 2, 3, 4, 5};
String[] days = { “Mon”, “Tue”, “Wed”, “Thu”, “Fri”, “Sat”,“Sun”};
Java Programming basics http://ir.linkedin.com/in/ghorbanihamid
١
Note1: The elements of an array have indexes from 0 to n-1.
Note that there is no array element arr[n]! This will result in an
"array-index-out-ofbounds" exception.
Note2: You cannot resize an array.
public class TestArray {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (int i = 0; i < myList.length; i++) {
System.out.println(myList[i] + " ");
}
// Summing all elements
double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
System.out.println("Total is " + total);
// Finding the largest element
double max = myList[0];
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
}
System.out.println("Max is " + max);
}
}
Java Programming basics http://ir.linkedin.com/in/ghorbanihamid
١
Copying Array:
1) reference Copy: use the assignment statement (=)
list2 = list1;
2) Value Copy:
2_1) write a loop to copy every element:
2_2) use arraycopy method: it is in the java.lang.System class
arraycopy(sourceArray, srcPos, targetArray, tarPos, length);
 srcPos and tarPos indicate the starting positions in sourceArray and
targetArray, respectively.
 The number of elements copied from sourceArray to targetArray is
indicated by length.
arraycopy(sourceArray, 0, targetArray, 0, sourceArray.length);
Java Programming basics http://ir.linkedin.com/in/ghorbanihamid
١
Multidimensional Arrays:
1) int[][] arr = new int[3][3]; //3 row and 3 column
2) // declaring and initializing 2D array
int arr[][] = {{1,2,3},{2,4,5},{4,4,5}};
Example:
// String array 4 rows x 2 columns
String[][] dogs = {
{ "terry", "brown" },
{ "Kristin", "white" },
{ "toby", "gray"},
{ "fido", "black"}
};
Example:
// character array 8 x 16 x 24
char[][][] threeD = new char[8][16][24];
Java Programming basics http://ir.linkedin.com/in/ghorbanihamid
١
Lengths of Two-Dimensional Arrays
x = new int[3][4];
x.length is ?
Traversing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
Output:1 2 3
2 4 5
4 4 5
Java Programming basics http://ir.linkedin.com/in/ghorbanihamid
١
The Array Class
The java.util.Arrays class contains various static methods for sorting and searching arrays,
comparing arrays, and filling array elements.
Sort:
This method sorts the specified array of ints into ascending numerical order.
BinarySearch:
searches the specified array of ints for the specified value using the binary search
algorithm.The array must be sorted before making this call.
import java.util.Arrays;
public class ArrayDemo {
public static void main(String[] args) {
// initializing unsorted int array
int iArr[] = {2, 1, 9, 6, 4};
// sorting array
Arrays.sort(iArr);
for (int number : iArr) {
System.out.println("Number = " + number);
}
int searchVal = 12;
int retVal = Arrays.binarySearch(intArr,searchVal);
System.out.println("The index of element 12 is : " + retVal);
}
}
Java Programming basics http://ir.linkedin.com/in/ghorbanihamid
١
equals: You can use the equals method to check whether two arrays are equal.
import java.util.Arrays;
public class ArrayDemo {
public static void main(String[] args) {
// initiliazing three object arrays
Object[] arr1 = new Object[] { 1, 123 };
Object[] arr2 = new Object[] { 1, 123, 22, 4 };
Object[] arr3 = new Object[] { 1, 123 };
// comparing arr1 and arr2
boolean retval=Arrays.equals(arr1, arr2);
System.out.println("arr1 and arr2 equal: " + retval);
// comparing arr1 and arr3
boolean retval2=Arrays.equals(arr1, arr3);
System.out.println("arr1 and arr3 equal: " + retval2);
}
}
fill: You can use the fill method to fill in the whole array or part of the array.
import java.util.Arrays;
public class ArrayDemo {
public static void main(String[] args) {
// initializing int array
int arr[] = new int[] {1, 6, 3, 2, 9};
// using fill for placing 18
Arrays.fill(arr, 18);
for (int value : arr) {
System.out.println("Value = " + value);
}
}
}

More Related Content

Java programming basics

  • 1. Java Programming basics http://ir.linkedin.com/in/ghorbanihamid ١ Java – Overview - was created in 1991 by (James Gosling, Mike Sheridan, and Patrick Naughton) - developed and Published by Sun Microsystems which in 1995 as Java 1.0 - Initially called Oak, its name was changed to Java because there was already a language called Oak. Editions: Java ME (Micro Edition): targeting environments with limited resources (mobile devices, micro-controllers, sensors, gateways, TV set-top boxes, printers) Java SE (Standard Edition): core Java programming platform targeting desktop and server environments It contains all of the libraries and APIs that any Java programmer should learn (java.lang, java.io, java.math, java.net, java.util, etc...). Java EE (Enterprise Edition): targeting large scale softwares (Network or Internet environments) Versions:  JDK 1.0 (January 23, 1996)[38]  JDK 1.1 (February 19, 1997)  J2SE 1.2 (December 8, 1998)  J2SE 1.3 (May 8, 2000)  J2SE 1.4 (February 6, 2002)  J2SE 5.0 (September 30, 2004)  Java SE 6 (December 11, 2006)  Java SE 7 (July 28, 2011)  Java SE 8 (March 18, 2014) Note: As of 2015, only Java 8 is officially supported
  • 2. Java Programming basics http://ir.linkedin.com/in/ghorbanihamid ٢ Principles: guaranteed to be Write Once, Run Anywhere. Object Oriented: In Java, everything is an Object. Secure: With Java's secure feature it enables to develop virus-free, tamper- free systems. Portable: Compiler in Java is written in ANSI C with a clean portability boundary, which is a POSIX subset. Platform Independent: Unlike many other programming languages including C and C++, when Java is compiled, it is not compiled into platform specific machine, rather into platform independent byte code. This byte code is distributed over the web and interpreted by the Virtual Machine (JVM) on whichever platform it is being run on. JVM (Java Virtual Machine): bytecode interpreter JVM is a virtual machine which work on top of your operating system to provide a recommended environment for your compiled Java code. JVM only works with bytecode. Hence you need to compile your Java application(.java) so that it can be converted to bytecode format (.class file). Which then will be used by JVM to run application. JVM only provide the environment It needs the Java code library to run applications.
  • 3. Java Programming basics http://ir.linkedin.com/in/ghorbanihamid ٣ JDK (Java Development Kit) JDK contains everything that will be required to develop and run Java application. JDK = JRE + development tools JRE (Java Run time Environment) JRE contains everything required to run Java application which has already been compiled. It doesn’t contain the code library required to develop Java application. JRE = JVM + Java Packages Classes (like util, math, lang, awt, swing etc) + runtime libraries. The programming structure: Sun Micro System has prescribed the following structure for developing java application.
  • 4. Java Programming basics http://ir.linkedin.com/in/ghorbanihamid ۴ Package: Package is a collection of classes, interfaces and sub-packages. A sub package contains collection of classes, interfaces and sub-sub packages etc. java.lang.*; package is imported by default and this package is known as default package. Class: In Java, every line of code that can actually run needs to be inside a class. Notice that when we declare a public class, we must declare it inside a file with the same name, otherwise we'll get an error when compiling. Methods: A method is a set of code which is referred to by name. When that name is encountered in a program, the execution of the program branches to the body of that method. When the method is finished, execution returns to the area of the program code from which it was called, and the program continues on to the next line of code. Language basics: Case Sensitivity: Java is case sensitive, which means identifier Hello and hello would have different meaning in Java. Class Names: For all class names the first letter should be in Upper Case. If several words are used to form a name of the class, each inner word's first letter should be in Upper Case. Example: class MyFirstJavaClass Method Names: All method names should start with a Lower Case letter. If several words are used to form the name of the method, then each inner word's first letter should be in Upper Case. Example: public void myMethodName() Program File Name: Name of the program file should exactly match the class name. When saving the file, you should save it using the class name (Remember Java is case sensitive) and append '.java' to the end of the name (if the file name and the class name do not match, your program will not compile). Example: Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved as 'MyFirstJavaProgram.java' public static void main(String args[]): Java program processing starts from the main() method which is a mandatory part of every Java program.
  • 5. Java Programming basics http://ir.linkedin.com/in/ghorbanihamid ۵ Java Data types: There are two data types available in Java: - Primitive Datatypes: There are 8 basic data types available within the Java language. Name Type Minimum value Maximum value Default value byte number, 1 byte -128 , 128 0 short number, 2 bytes -32,768 32,767 0 int number, 4 bytes - 2,147,483,648 (-2^31) 2,147,483,647 (2^31 -1) 0 long number, 8 bytes -2^63 2^63 -1 0L float float number, 4 bytes 1.4E^-45 3.4028235E^38 0.0f double float number, 8 bytes 4.9E^-324 1.7976931348623157E^308 0.0d char a character, 2 bytes 'u0000' (or 0) 'uffff' (or 65,535) 'u0000' boolean true or false, 1 bit false *** Note: To declare and assign a number use the following syntax: Variable_Type variable_Name; Example: int a, b, c; // Declares three ints, a, b, and c. int a = 10, b = 10; // Example of initialization byte B = 22; // initializes a byte type variable B. double pi = 3.14159; // declares and assigns a value of PI. char a = 'a'; // the char variable a is initialized with value 'a' - Reference/Object Datatypes : A reference type is a data type that’s based on a class, a reference type is an instantiable class Example: Person person = new Person();
  • 6. Java Programming basics http://ir.linkedin.com/in/ghorbanihamid ۶ Java Variables To declare and assign a number use the following syntax: Variable_Type variable_Name; ***Following are the types of variables in Java: - Local Variables - Class Variables (Static Variables) - Instance Variables (Non-static Variables) Local Variables: Local variables are declared in methods, constructors, or blocks and are visible only within the declared method, constructor, or block. Instance Variables: Instance variables belong to the instance of a class(an object) and every instance of that class (object) has it's own copy of that variable. Example: public class Product { public int barcode; // an instance variable } public class MyFirstJavaProgram { public static void main(String[] args) { Product product1 = new Product(); product1.barcode = 123456; System.out.println(product1.barcode); } } Class Variables: Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block. class variable is a variable defined in a class of which a single copy exists, regardless of how many instances of the class exist. public class MyFirstJavaProgram { static int barcode; }
  • 7. Java Programming basics http://ir.linkedin.com/in/ghorbanihamid ٧ Java Modifiers: Like other languages, it is possible to modify classes, methods, etc., by using modifiers. There are two categories of modifiers: Access Modifiers: default, public , protected, private Non-access Modifiers: final, abstract, strictfp if-else statement: An if statement can be followed by an optional else statement, which executes when the Boolean expression is false. if( x < 20 ) { System.out.print("This is if statement"); }else { System.out.print("This is else statement"); } while-loop A while loop statement in Java programming language repeatedly executes a target statement as long as a given condition is true. int x = 0; while( x < 20 ) { System.out.print("This is while statement : " + x); X++; } do-while-loop A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time. int x = 0; while( x < 20 ) { System.out.print("This is while statement : " + x); X++; }
  • 8. Java Programming basics http://ir.linkedin.com/in/ghorbanihamid ٨ for-loop A for loop is a repetition control structure that allows you to efficiently write a loop that needs to be executed a specific number of times. for( int i = 0; i < 20; i++ ) { System.out.print("This is for-loop statement : " + i); } For-each loop The for-each loop(Advanced or Enhanced For loop) introduced in Java5. It is mainly used to traverse array or collection elements. The advantage of for-each loop is that it eliminates the possibility of bugs and makes the code more readable. for(data_type variable : array | collection){ …. } Example 1: int arr[]={12,13,14,44}; for( int i:arr) { System.out.print("This is for- each loop statement : " + i); } Example 2: ArrayList<String> list=new ArrayList<String>(); list.add("vimal"); list.add("sonoo"); list.add("ratan"); for(String s:list){ System.out.println(s); }
  • 9. Java Programming basics http://ir.linkedin.com/in/ghorbanihamid ٩ Branching Statements Java offers three branching statements:  break  continue  return Break This statement can be used to terminate a switch, for, while, or do-while loop for(int i=1;i<=10;i++){ if(i==5){ break; } System.out.println(i); } Continue The continue keyword causes the loop to immediately jump to the next iteration of the loop. for(int i=1;i<=3;i++){ for(int j=1;j<=3;j++){ if(i==2&&j==2){ continue; } System.out.println(i+" "+j); } } return used to exit from the current method. public static int minFunction(int n1, int n2) { int min; min = n2; return min; }
  • 10. Java Programming basics http://ir.linkedin.com/in/ghorbanihamid ١ Switch statement The Java switch statement executes one statement from multiple conditions. It is like if- else-if ladder statement. Example: public class SwitchExample { public static void main(String[] args) { int number=20; switch(number){ case 10: System.out.println("10");break; case 20: System.out.println("20");break; case 30: System.out.println("30");break; default:System.out.println("Not in 10, 20 or 30"); } } } public class Test { public static void main(String args[]) { char grade = 'C'; switch(grade) { case 'A' : System.out.println("Excellent!"); break; case 'B' : case 'C' : System.out.println("Well done"); break; case 'D' : System.out.println("You passed"); case 'F' : System.out.println("Better try again"); break; default : System.out.println("Invalid grade"); } System.out.println("Your grade is " + grade); } }
  • 11. Java Programming basics http://ir.linkedin.com/in/ghorbanihamid ١ Arrays Java arrays, is a data structure which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. Syntax: 1) dataType[] arrayName; or dataType arrayName[]; Example: // declaration Int[] myList; // instantiate object myList = new int[10]; 2) dataType[] arrayName = new datatype[size]; Example: double[] myList = new double[10]; Array initialization: 1) after declaration:  a[0]=10;  a[1]=20;  a[2]=70;  a[3]=40; 2) with declaration: int[] arr = {1, 2, 3, 4, 5}; String[] days = { “Mon”, “Tue”, “Wed”, “Thu”, “Fri”, “Sat”,“Sun”};
  • 12. Java Programming basics http://ir.linkedin.com/in/ghorbanihamid ١ Note1: The elements of an array have indexes from 0 to n-1. Note that there is no array element arr[n]! This will result in an "array-index-out-ofbounds" exception. Note2: You cannot resize an array. public class TestArray { public static void main(String[] args) { double[] myList = {1.9, 2.9, 3.4, 3.5}; // Print all the array elements for (int i = 0; i < myList.length; i++) { System.out.println(myList[i] + " "); } // Summing all elements double total = 0; for (int i = 0; i < myList.length; i++) { total += myList[i]; } System.out.println("Total is " + total); // Finding the largest element double max = myList[0]; for (int i = 1; i < myList.length; i++) { if (myList[i] > max) max = myList[i]; } System.out.println("Max is " + max); } }
  • 13. Java Programming basics http://ir.linkedin.com/in/ghorbanihamid ١ Copying Array: 1) reference Copy: use the assignment statement (=) list2 = list1; 2) Value Copy: 2_1) write a loop to copy every element: 2_2) use arraycopy method: it is in the java.lang.System class arraycopy(sourceArray, srcPos, targetArray, tarPos, length);  srcPos and tarPos indicate the starting positions in sourceArray and targetArray, respectively.  The number of elements copied from sourceArray to targetArray is indicated by length. arraycopy(sourceArray, 0, targetArray, 0, sourceArray.length);
  • 14. Java Programming basics http://ir.linkedin.com/in/ghorbanihamid ١ Multidimensional Arrays: 1) int[][] arr = new int[3][3]; //3 row and 3 column 2) // declaring and initializing 2D array int arr[][] = {{1,2,3},{2,4,5},{4,4,5}}; Example: // String array 4 rows x 2 columns String[][] dogs = { { "terry", "brown" }, { "Kristin", "white" }, { "toby", "gray"}, { "fido", "black"} }; Example: // character array 8 x 16 x 24 char[][][] threeD = new char[8][16][24];
  • 15. Java Programming basics http://ir.linkedin.com/in/ghorbanihamid ١ Lengths of Two-Dimensional Arrays x = new int[3][4]; x.length is ? Traversing 2D array for(int i=0;i<3;i++){ for(int j=0;j<3;j++){ System.out.print(arr[i][j]+" "); } System.out.println(); } Output:1 2 3 2 4 5 4 4 5
  • 16. Java Programming basics http://ir.linkedin.com/in/ghorbanihamid ١ The Array Class The java.util.Arrays class contains various static methods for sorting and searching arrays, comparing arrays, and filling array elements. Sort: This method sorts the specified array of ints into ascending numerical order. BinarySearch: searches the specified array of ints for the specified value using the binary search algorithm.The array must be sorted before making this call. import java.util.Arrays; public class ArrayDemo { public static void main(String[] args) { // initializing unsorted int array int iArr[] = {2, 1, 9, 6, 4}; // sorting array Arrays.sort(iArr); for (int number : iArr) { System.out.println("Number = " + number); } int searchVal = 12; int retVal = Arrays.binarySearch(intArr,searchVal); System.out.println("The index of element 12 is : " + retVal); } }
  • 17. Java Programming basics http://ir.linkedin.com/in/ghorbanihamid ١ equals: You can use the equals method to check whether two arrays are equal. import java.util.Arrays; public class ArrayDemo { public static void main(String[] args) { // initiliazing three object arrays Object[] arr1 = new Object[] { 1, 123 }; Object[] arr2 = new Object[] { 1, 123, 22, 4 }; Object[] arr3 = new Object[] { 1, 123 }; // comparing arr1 and arr2 boolean retval=Arrays.equals(arr1, arr2); System.out.println("arr1 and arr2 equal: " + retval); // comparing arr1 and arr3 boolean retval2=Arrays.equals(arr1, arr3); System.out.println("arr1 and arr3 equal: " + retval2); } } fill: You can use the fill method to fill in the whole array or part of the array. import java.util.Arrays; public class ArrayDemo { public static void main(String[] args) { // initializing int array int arr[] = new int[] {1, 6, 3, 2, 9}; // using fill for placing 18 Arrays.fill(arr, 18); for (int value : arr) { System.out.println("Value = " + value); } } }