ARRAYS
An array is a data structure that holds a fixed number of values of a single type in
a single name which has contiguous memory location.
Each item in an array is called an element, and each element is accessed by its
numerical index.
Index always starts with 0. Index is neither negative nor greater than or equal to
size of array.
Arrays are objects
They are created during runtime
The Array length is fixed
1. One dimensional array - Creating, Initializing, and Accessing an Array
Syntax to Decalring array variables Declaring an array variable, but
memory is not allocated
type var-name[]; (or) type []var-name => declaring an array
var-name=new type[size]; => Instantiation of an Array
or
type var-name[]=new type[size]
Creating an array and assigning the reference of the
array to the variable is done through new operator
here type refer to base type of an array. It could be primitive type or class.
The base type for the array determines what type of data the array will hold.
E.g., int a[]=new int[10];
- Variable name is ‘a’ of integer type, can hold upto 10 integer values.
- Pictorial representation of array ‘a’
the shortcut syntax to declaration, instantiation and initialization
int[] anArray = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
the length of the array is determined by the number of values provided
between { and }.
Pictorial representation of array ‘anArray’
E.g., Program that finds the sum of 5 numbers
output
import java.util.*; Length of the integer array =10
class TestArray 1
{ 2
public static void main(String[] args) 3
{ 4
int a[]=new int[10]; 5
Scanner s=new Scanner(System.in); sum of integer array =15
int sum=0
System.out.println("length of the integer array =" + a.length );
for(int i=0;i<5;i++)
{
a[i]=s.nextInt();
sum+=a[i];
}
System.out.println("sum of integer array =" + sum );
2. MULTIDIMENSIONAL ARRAY- Creating, Initializing, and Accessing 2D array
an array of arrays (also known as a multidimensional array) can be created using two or
more sets of square brackets, such as [ ] [ ].
The general form of two dimensional array
type var-name[][]; (or) type [][]var-name;
var-name=new type[rowsize][colsize];
or
type varname[][]=new type[rowsize][colsize];
the shortcut syntax to declaration, instantiation and initialization
int[][] matrix = {{100, 200, 300}, {400, 500, 600}};
E.g., Program for transpose of a matrix
import java.util.*;
class matrix
{
public static void main(String args[])
{
final int r=3;
final int c=2;
int [][]a= new int[r][c];
Scanner in=new Scanner(System.in);
System.out.println("Input elements of matrix");
for (int i = 0; i < a.length; ++i)
{
System.out.print("ith row: " + i);
for(int j = 0; j < a[i].length; ++j)
{ a[i][j]=in.nextInt(); }
} // end of i
System.out.println("PRint matrix");
for(int[] row : a) {
for (int column : row)
{ System.out.print(column + " "); }
System.out.println();
}// end of row
for (int j = 0; j < c; ++j)
{
for(int i = 0; i < r; ++i)
{
System.out.print(a[i][j] + " ");
}
System.out.println();
}
}// main end
} class end
3. Array of objects
stores an array of objects.
array elements store the location of the reference variables of the object.
Syntax: Class obj[]= new Class[array_length]
obj[i]=new Class_constructor();
E.g.,
class ObjectArray{ obj
public static void main(String args[]){ 0 1
Account obj[] = new Account[2] ; Reference Reference
obj[0] = new Account(1,2); of obj[0] of obj[1]
obj[1] = new Account(3,4);
System.out.println("For Array Element 0");
obj[0].showData(); $a=3 _b=4
$a=1 _b=2
System.out.println("For Array Element 1");
obj[1].showData();
}
}
class Account{
int $a;
int _b;
Account(int a,int b)
{ this.$a=a; this._b=b;}
public void showData(){ For Array Element 0
System.out.println("Value of a ="+$a); Value of a =1
System.out.println("Value of b ="+_b); Value of b =2
} For Array Element 1
} Value of a =3
Value of b =4
4. Anonymous Array in Java
Java supports the feature of an anonymous array, so you don't need to declare the array
while passing an array to the method.
//Java Program to demonstrate the way of passing an anonymous array
//to method.
public class TestAnonymousArray{
//creating a method which receives an array as a parameter
static void printArray(int arr[]){
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]);
}
public static void main(String args[]){ Anonymous array
printArray(new int[]{10,22,44,66});//passing anonymous array to method
}}
OPERATORS IN JAVA
1. Assignment Operator => Symbol is "=".
• It assigns the value on its right to the variable on its left.
int cnt = 0; boolean found = false; char ch = ‘y’;
• This operator can also be used on objects to assign object references
A a= new A(); // creates an instance of class A
A b=a; // assigns reference of a to b which is an instance of class A
• Multiple assignment also possible in java. Eg. int a=b=c=d
2. Arithmetic Operators
+ additive operator (used as String concatenation)
int result = 10 % 7; // result is now 3
- subtraction operator / unary minus double result2 = 10 % 9.1; // result2 is
* multiplication operator , / division operator now 0.9000000000000004
% remainder operator(applied to both integer as well as floating point numbers )
+= , -=, *= , /=, %= => arithmetic assignment operators(compound assignments )
++ Incrementor, -- Decrementor
3. Unary Operators=> requires only one operand(+,-,++,--,!)
result = -result; // result is now -1
boolean success = false; success = !success; // success become true
4. Relational Operators => result is always boolean (it cannot be converted to
integers or any other type)
5. Ternary operators => ?:,
• simplified version of the if-else statement with a value to be returned.
• Called as ternary because it has 3 operators
e.g., int value1 = 1;
int value2 = 2;
int result;
result = (value1< 0) ? value1 : value2;
//result is assigned to 2
CONTROL FLOW STATEMENTS
break up the flow of execution by employing decision making, looping, and
branching, enabling program to conditionally execute particular blocks of code.
Types
1. Decision-making / selection statements – if-then, if-then-else(else-if
ladder), switch
2. The looping / iteration statements – for ,while, do-while
3. Branching / Jump statements – break, continue, return
1. Decision Making
a) If statement
if (condition)
{ //Statement-block1; }
else
{ Statement-block2; }
b) Nesting Of If…else Statements
c) Else…if Ladder / Cascaded If Statement(alternate to switch statement)
d) Switch statement
Syntax
switch(expression/variable)
{
case value1: // statement sequence
break;
case value2:// statement sequence
break;
…
case valueN:// statement sequence
break;
default : // statement sequence
}
expression must of type byte, short, int, char. Other types are not allowed
Default is optional, if you do not want this could be ignored
Each case value must be unique literals, duplicate values are not allowed
2. Iteration statements / loops
a. while – pre-conditional loop
b. do-while – post-conditional loop
c. for – determination loop
d. for-each
a. While 3. for loop
while (condition) for(intialization1 [,initialization2,..] ;condition ; inc1 [,inc2,…] )
{ // body of the loop; { statement[s]; }
}
b. Do-while loop For-Each loop / Eanhanced for loop
do is used to iterate values from an array or collection variable
{ it is not requires to test explicitly, whether end of the array or
// statement[s]; collection is reached
}while(condon Syntax:
for (type var : array)
{ //body-of-loop }
Pictorial representation
3. Jump statements/unconditional control statement
1. BREAK
• leads to immediate
termination of a loop
• used to terminate a case in
the switch statement
• supports labeled break:
break label;
2. CONTINUE (skipping part of
loop)
instead of forcing loop termination, continue statement forces the next
iteration of the loop to take place
when continue statement get executed inside the loop, all statements available after
continue statement will not get executed, instead next iteration takes place
for(i=1;i<5;i++)
{
for(j=1;j<5;i++)
{
if(i == j)continue;
System.out.print(“\t”+j);
}
System.out.println();
}
3. RETURN => return expression;
PACKAGES
Defn-1: A package in Java is used to group related classes(a folder in a file
directory.)
Defn-2:A package can be defined as a grouping of related type(classes , interfaces)
providing access protection and name space management
Packages are container for classes; they are used for the following reason:
o To avoid name collision of classes developed by different programmer,
different software company
o To import classes: Classes stored in a package are explicitly imported, without
making copy of that in your folder
o Packages are also used to control accessibility of the classes, members
of the classes
Package in java can be categorized in two form
1. Predefined packages
2. User-defined packages
1. Predefined packages
are developed by SUN micro systems and supplied as a part of JDK (Java
Development Kit) to simplify the task of java programmer.
some of the predefined packages are
java.lang , java.util, ,java.awt, java.io
2. User –defined packages /defining packages
To create a package include a package keyword at the top of the source file
A package statement must be the first statement in the java source file.
Any classes declared within that file will belong to specified package.
A source file must have only one package statement
If you omit package statement in java source code, the classes in thesource code
are put into the default package, which has no name
The general form of the package statement is:
E.g., package mypackage;
The package name and folder name in which your java file stored must have
the same name
Hierarchy of packages can also be created
- done by creating a hierarchy of folder, and separating each package name
using period(.).
- The general form of multileveled package : package pkg1[.pkg2[.pkg3]];
- E.g., : package pack1.subpack1;
Note: package in java is converted into directory (i.e., folder) during
execution. e.g., java.util.* is converted as java\util\.*
package mypack;
class Simple Welcome to package
{
public static void main(String args[])
{ System.out.println("Welcome to package"); }
}
To Run the package program
Compile using java: C:\Users\Sathya\Desktop\sathiya\JP\mypack>javac
Simple.java
Run using java: C:\Users\Sathya\Desktop\sathiya\JP\mypack>java mypack.Simple
Setting a class path
- By default java runtime(i.e., interpreter) looks for .class files only in the current
directory
- Because java runtime uses the current working directory as its starting point
- To import classes in the package from anywhere, add a path of parent directory of
your package, where it residing into environment variable classpath.
- For example if your package pkg1.pkg2 is residing in d:\sathiya then you have to
set classpath has
set classpath=%classpath%;d:\sathiya;.; Output (from samePackage)
Private variable: 10// accessed through
public method
Default variable: 20
e.g., Protected variable: 30
Public variable: 40
package p1.sp1; package p1.sp1;
public class SamePackage {
public class Parent
public static void main(String args[]) {
{ Parent p = new Parent();
// error, private variable not accessible outside its class
private int a=10;
//System.out.println("Private variable" + p.a);
int b=20;
// used public method to access "a" of same class
protected int c=20;
System.out.println("Private variable: " + p.getA());
public int d=40;
System.out.println("Default variable: " + p.b);
public int getA()
System.out.println("Protected variable : " + p.c);
{ return a; }
System.out.println("Public variable: " + p.d);
} }
}
import p1.sp1.*;
class OtherPackage {
OtherPackage() {
output //p1.sp1.Parent p = new p1.sp1. Parent();
other package constructor Parent p=new Parent();
Private variable: 10 System.out.println("other package constructor");
Public variable: 40 System.out.println("Private variable: " + p.getA());
// System.out.println("Default variable: " + p.b);
// System.out.println("Protected variable : " + p.c);
System.out.println("Public variable: " + p.d);
}
public static void main(String a[])
{
OtherPackage op=new OtherPackage();
}
}
Importing package/class importation / access package from another package
A class can use all classes from its own package and all public classes from other
packages.
Accessing public classes from other packages can be done in
a. Using fully qualified name
Add full package name in front of every class name. E.g., p1.sp1.Parent
b. Using import statement
Can import certain classes from a package or whole package
Syntax : import pkg1[.pkg2].(classname | * ); specify classname or *.
Here * indicates that the java compiler should import the entire package
into memory
In java source file, import statements must occur immediately following
package statement and before any class definitions
e.g.1: using import statement e.g.2 (without import statement –
import java.util.Scanner; // (or) import using fully qualified name)
java.util.*; class Employee
class Employee {
{ public static void main(String args[])
public static void main(String args[]) { {
String name; String name;
Scanner input=new Scanner(System.in ); java.util.Scanner in=new java.util.
System.out.println(input.nextInt()); Scanner(System.in );
} System.out.println(input.nextInt());
} }
}
Java Static Import
- the static import facilitate the java programmer to access any static member of a
class directly. There is no need to qualify it by the class name.
- static import declaration comes in two flavors: single-static import and static-
import-on-demand.
- A single-static import declaration imports one static member from a type.
o import static <<package name>>.<<type name>>.<<static member
name>>
o e.g., import static java.lang.System.out
- A static-import-on-demand declaration imports all static members of a type
import static <<package name>>.<<type name>>.*;
Syntax : import static packagename.classname.*;
e.g., : import static java.lang.System.*;
E.g., single-static import E.g., static-import-on-demand
import static java.lang.System.out; package p1.sp1;
class StaticImportExample public class statimport
{ {
public static void main(String args[]) static public int a;
{ public static void get()
out.print("Hello"); {
out.println(" Java"); System.out.println("A = " + a);
} }
} }
Output
Hello Java package p1.sp2;
import static p1.sp1.statimport.*;
class accstatic
{
public static void main(String a[])
{
get();
}
}
Output
A=0
JavaDoc comments
- documentation comment
Javadoc utility is a tool which comes with JDK and it is used for generating Java code
documentation in HTML format from Java source code, which requires documentation
in a predefined format.
is identified by /** …….*/
Documentation comments make it convenient to document your programs
- javadoc Tags
Document tags that begin with an “at” sign (@) are called stand-alone tags, and
they must be used on their own line.
Tags that begin with a brace, such as {@code}, are called in-line tags, and they
can be used within a larger description
1. @author=> @author description=> javadoc extracts the author name from this
tag.
2. @version => @version info=>info is a string that contains version information
3. @param=>@param parameter-name explanation
i. parameter-name specifies the name of a parameter
ii. meaning of that parameter is described by explanation.
4. @return=>@return explanation=>explanation describes the type and meaning
of the value returned by a method
E.g.,
/** @author II CSE
@version 3.2 */
public class comm
{
/** @param b reads float value
@return int returns 5 */
public int a(float b)
{
return 5; To compile
} javadoc comm.java -author -version
/**
demo for documentation comment
@param a array of strings
*/
public static void main(String a[])
{}
}