0% found this document useful (0 votes)
14 views23 pages

Java Unit 1

Uploaded by

srushtimkumbar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views23 pages

Java Unit 1

Uploaded by

srushtimkumbar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

BSC CS III SEM OOP’S CONCEPT AND PROGRAMMING WITH JAVA

OBJECT ORIENTED PROGRAMMING CONCEPTS AND


PROGRAMMING IN JAVA.

UNIT 1 : INTRODUCTION TO JAVA.

● BASICS OF JAVA PROGRAMMING.


SIMPLE JAVA PROGRAM :
Class Demo
{
Public static void main(string args[])
{
System.out.println(“Welcome to JAVA”);
}
}

*class: class is a keyword and declares that a new class definition.

*Demo: Demo is a java identifier that specifies the name of the class to be
defined.

*public : public is the keyword that can access specifier that declares the main
method as unprotected and therefore making it accessible to all other classes.

*static : static is a access modifier means we can call this method directly
using class name without belong to entire class not the part of class or object.

*void : void is type modifier, void states thet the main method does not return
any value.

*String args[] : it declares a parameter named args, which contains an array


of objects of the class type String.

*System.out.println : it is a java statement that print the arguments passed


into the System.out.println.

System-> is class out-> is variable. println-> method.


Method is a function were java program should having main function.

Notes by, shivaling_shetty,,,


BSC CS III SEM OOP’S CONCEPT AND PROGRAMMING WITH JAVA

STRUCTURE OF JAVA PROGRAM :

* Documentation section :
> the documentation section comprises a set of comment lines giving the name of
the program, the author and other details.
> java also uses a third style comment /*…*/ known as documentation comment.
> Whatever we written in this section compiler ignores the statement.

*Package statement :
> the first statement allowed in a java file is a package statement.
> this statement declares a package name and informs the compiler that the classes
defined here belong to this package.
Ex: package student;

* Import statements :
> the next thing after a package statement but before any class definitions may be a
number of import statements.
Ex: import student.Test;
> this statement instructs the intrepreter to load the Test class contained in the
package student.

* Interface statements :
> an interface is like a class but includes a group of method declarations.
> this is also an optional section and is used only when wish to implement the
multiple inheritance feature in the program.

* class definitions :
> a java program may contain multiple class definitions.
> classes are essential elements of a java program.

Notes by, shivaling_shetty,,,


BSC CS III SEM OOP’S CONCEPT AND PROGRAMMING WITH JAVA
> thees classes are used to map the objects of real world problems .

* Main method class :


> since every java standalone program requires a main method as its starting point,
this class is the essential part of a java program.
> a simple java progarm may contain only this part.
> the main method creates objects of various classes and establishes
communications between them.

JAVA TOKENS :
Smallest individual units in a program are known as tokens.

* Java language includes 5 types of tokens :

1. Keywords :
> keywords have specific meaning in java, we cannot use them as names for
variables, classes, methods and so on.
> all keywords are written in lowercase letters.
> java language has reserved 50 words as keywords.

2. Identifiers :
> identifiers are programmer designed tokens.
> They are used for naming classes, methods, variables, objects, labelks, packages
and interfaces in a program.
> java identifiers follow the following rules to create :
i . they can have alphabets, digits, and the underscore and dollar sign
characters.
ii. They must not begin with a digit.
iii. Uppercase and lowercase letters are distinct.
iv. They can be any length .
v. it should not be a keyword.

3. Literals :
Literals in java are a sequence of characters (digits,letters and other
character) that represent constant values to be stored in variables.
> java language specifies following types of literals :
● Integer literals.
● Floating point literals
● Character literals
● String literals
● Boolean literals
Notes by, shivaling_shetty,,,
BSC CS III SEM OOP’S CONCEPT AND PROGRAMMING WITH JAVA
● Null literals

4. Operators :
An operator is a symbol that takes one or more arguments and
operates on them to produce a result.

> types of java operators :


i. Arithmetic operators : (+, - , / , % , *)
ii. Relational operators : ( < , <= , > , >= , == , !=)
iii. Logical operators : ( && , || , !)
iv. Assignment operators : ( = , += , -= , *= , /=)
v. Increment and Decrement operators : ( ++ , –-)
vi. Conditional operator : ( exp1?exp2:exp3 )

5. Separators :
Separators are symbols used to indicate where groups of code are
divided and arranged.
> they basically define the shape and function of our code.
Ex: () , {} , [] , ; , etc.

DATA TYPES :

* Integer types (int) :


> integer types can hold whole numbers such as 123,-90, and 4356.
> java supports four types of integers follows :
i. byte - 1 byte.
ii. short - 2 bytes
Notes by, shivaling_shetty,,,
BSC CS III SEM OOP’S CONCEPT AND PROGRAMMING WITH JAVA
iii. int - 4 bytes
iv. long - 8 bytes

* Floating point types (float) :


> floating point type to hold numbers containing fractional parts such as 25.44 and
-22.3.
> there are two types in java :
i. float - 4 bytes
ii. double - 8 bytes

* Character type (char) :


> in order to store character constants in memory, java provides a character data
type called char.
> the char type assumes size of 2 bytes but basically it can hold only a single
character.

* boolean type (boolean) :


> boolean type is used when we want to test a particular condition during execution
of the program.
> there are only two values that a boolean type can hold : true or false.
> keyword : boolean uses one bit of storage.

VARIABLES :
A variable is an identifier that denotes a storage location used to store a data
value.
> variable may take different values at different times during the execution of the
program
> as mentioned earlier, variable names may consist of alphabets, digits, the
underscore and dollar character, subjects to the following condition :
i. They must not begin with a digit.
ii. Uppercase and lowercase are distinct
iii. It should not be a keyword
iv. White space is not allowed
v. variable names can be of any length.

* Declaration of variables :
Declaration does three things :
i. It tells the compiler what the variable name is.
ii. It specifies what type of data the variable will hold.
iii. The place of declaration decides the scope of the variable.
A variable must be declared before it is used in the program.

Syntax : datatype var1,var2,...varn;


Ex: int n;

Notes by, shivaling_shetty,,,


BSC CS III SEM OOP’S CONCEPT AND PROGRAMMING WITH JAVA
* Initializing variables :
A variable must be given a value after it has been declared but before it is
used in an expression.
This can be achieved in two ways
1. By using an assignment statement.
2. By using a read statement

1. By using an assignment statement :


A simple method of giving value to a variable is through the assignment
statement as follows :
Syntax: var_name=value;
It is also possible to assign a value to a variable at the time of its declaration :

Syntax: datatype var_name=value;


Ex: int a=10;

“The process of giving initial values to variables is known as the initialization.”

2. By using a read statement :


We may also give values to variables interactivity through the keyboard using
the readLine() method, as illustrated in the program below.

Program:

import java.io.DataInputStream;
class Reading
{
public static void main(String args[])
{
DataInputStream in=new DataInputStream(System.in);
int n=0;
float f=0.0f;
try
{
System.out.println(“Enter an integer: ”);
n=Integer.parseInt(in.readLine());
System.out.println(“Enter a float number: ”);
f=Float.valueOf(in.raedLine().floatValue());
}
catch(Exception e)
{
System.out.println(“Input Error”+e);
}
System.out.println(“int number =”+n);
System.out.println(“float number =”+f);
}
}

Notes by, shivaling_shetty,,,


BSC CS III SEM OOP’S CONCEPT AND PROGRAMMING WITH JAVA
The readLine() method (which is invoked using an object of the class
DataInputStream) reads the input from the keyboard as a string which is then
converted to the corresponding datatype using the datatype wrapper classes.

> Reading input from keyboard can also done by these other ways. :

1. Use System.Console class :


Ex:
class ConsoleDemo
{
public static void main(String args[])
{
System.out.println(“What is your name? ”);
String name=System.Console().readLine();
System.out.println(“Your name is: ”+name);
}
}

2. Use java.util.Scanner class and System.in :


Ex:
import java.util.Scanner;
class ScannerDemo
{
public static void main(String args[])
{
Scanner scan=new Scanner(System.in);
String s=scan.nextLine();
int a=scan.nextInt();
System.out.println(“Entered string: ”+s);
System.out.println(“Entered integer: ”+a);
}
}

OPERATORS:
An operator is a symbol that tells the computer to perform certain
mathematical or logical manipulations
> operators are used in programs to manipulate data and variables.
> java supports a rich set of operators. We have already used several of them, such as
=, +, - ,* ,etc,,

> java operators are classified into number of categories below :


1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment and decrement operators
6. Conditional operators
Notes by, shivaling_shetty,,,
BSC CS III SEM OOP’S CONCEPT AND PROGRAMMING WITH JAVA
7. Bitwise operators
8. Special operators

1. Arithmetic operators :
Arithmetic operators are used to construct mathematical expressions as in
algebra. Java provides all the basic arithmetic operators.

Operator meaning
+ Addition or unary plus
- Subtraction or unary minus
* Multiplication
/ division
% Modulo (remainder)

> these can operate on any built-in numeric data type of java. We cannot use these
operators on boolean type.
> arithmetic operators are used as shown below :
a+b a-b a*b etc

2. Relational operators :
> we often compare two quantities, and depending on their relation, to take certain
decision.
> java supports six relational operators in all, these operators and their meaning are
shown below :

Operator meaning
< is less than
<= is less than or equal to
> is greater than
>= is greater than or equal to
== is equal to
!= is not equal to

> when arithmetic expressions are used on either side of a relational operator, the
arithmetic expression will be evaluated first and then the results are compared.
> relational operators are results only in true or false
Ex: 4-2<10; o/p: true
2>=4; o/p:false
> relational expressions are used in decision statements such as, if and while to decide
the action of running program.

3. Logical operators :
> in addition to the relational operators, java has three logical operators, they are:

Operator meaning
&& logical AND
Notes by, shivaling_shetty,,,
BSC CS III SEM OOP’S CONCEPT AND PROGRAMMING WITH JAVA
|| logical OR
! logical NOT

> the logical operators && and || are used when we want to form compound conditions
by combining two or more relations.
Ex: 2==3&&3==2
> like the simple relational expressions a logical expressions also results a value of true
or false, they results according to the below truth table:

Operand1 operand2 op1&&op2 op1||op2


true true true true
true false false true
false true false true
false false false false

> note: * logical AND results true if both operands are true otherwise it results false.
*logical OR results false if both operands are false otherwise it results true.
> the logical NOT operator is use to reverse the result of any expression or condition.
If the result of condition is true, the result will be reversed to false

4. Assignment operators :
> assignment operators are used to assign the value of an expression to a variable.
We have seen the usual assignment operator ‘=’.
> in addition, java has a set of ‘shorthand’ operators which are: +=, -=, *=, /=, %=.
Ex: x += 2; is equivalent to x = x + 2;
> advantages of shorthand operators are:
1. What appears on the left-hand side need not be repeated and therefore it
becomes easier to write.
2. The statement is more concise and easier to read.
3. Use of shorthand operator results in a more efficient code.

5. Increment and decrement operators :


> java has two very useful operators not generally found in many other languages.
These are the increment(++) and decrement(--) operators.
> the operators ++ adds 1 to the operand while – – subtracts 1. Both are unary
operators and are used as:
++x; or x++;
--x; or x–;
* ++x is equivalent to x = x +1; or x += 1;
> if the operator is used before the operand it operates first and then uses the
operand in the program.(pre increment or pre decrement)

Notes by, shivaling_shetty,,,


BSC CS III SEM OOP’S CONCEPT AND PROGRAMMING WITH JAVA
> if the operator is used after the operand it uses operand first and then operates on
operand.(post increment or post decrement)

6. Conditional operator :
> the character pair ? : is a ternary operator available in java. This operator is used to
construct conditional expression of the form:
exp1 ? exp2 : exp3 ,where exp is an expression.

> the operator ? : works as follows:


exp1 is evaluated first. If it is true, then the expression exp2 is evaluated and
becomes the value of the conditional expression. If exp1 is false, exp3 is evaluated
and its value becomes the conditional expression.

Ex: x = (a > b) ? a : b;
Here, a>b is evaluated, if a is bigger (true) then value of a is assigned to x
otherwise (false) value of b is assigned to x.

7. Bitwise operators :
> java has a distinction of supporting special operators known as bitwise operators for
manipulation of data at values of bit level.
> these operators are used for testing the bits, or shifting them to the right or left.
> bitwise operators may not be applied to float or double.
> list of bitwise operators:
Operator meaning
& bitwise AND
! bitwise OR
^ bitwise exclusive OR
~ one’s complement
<< shift left
>> shift right
>>> shift right with zero fill

8. Special operators :
> java supports some special operators of interest such as instanceof operator and
member selection operator (.) .
> the instanceof is an object reference operator and returns true if the object on the
left-hand side is an instance of the class given on the right-hand side.
> the dot operator (.) is used to access the instance variables and methods of class
objects.
Notes by, shivaling_shetty,,,
BSC CS III SEM OOP’S CONCEPT AND PROGRAMMING WITH JAVA

CONTROL STATEMENTS :
The if statement is a powerful decision making statement and is used to control
the flow of execution of statements. It is basically a two-way decision statement and
is used in conjunction with an expression, it takes following form:
if(test condition);
It allows the compiler to evaluate the expression first and then, depending on
whether the value of the expression is true or false , it transfers the control to a
particular statement.

1. Simple if statement :
Syntax:
if(test_condition)
{
statement_block;
}
> the ‘statement_block’ may be a single statement or a group of statements.
> if the test_condition is true, the statement_block will be executed, otherwise the
statement_block will be skipped and the execution will jump to the next statements in
the program.

Example program:
import java.util.Scanner;
class Sum
{
public static void main(String args[])
{
Scanner scan=new Scanner(System.in);
int c=0;
System.out.println(“Enter a:”);
int a=scan.nextInt();
System.out.println(“Enter b:”);
int b=scan.nextInt();
if(a!=0 || b!=0)
c=a+b;
System.out.println(“Sum is:”+c);
}
}

2.if-else statement :

Notes by, shivaling_shetty,,,


BSC CS III SEM OOP’S CONCEPT AND PROGRAMMING WITH JAVA
Syntax:
if(test_condition)
{
statement_block1;
}
else
{
statement_block2;
}

If the test_condition is true, then the statement_block1 is executed, otherwise


statement_block2 is executed .

Example program:
import java.util.Scanner;
class Big
{
public static void main(String args[])
{
Scanner scan=new Scanner(System.in);
System.out.println(“Enter a:”);
int a=scan.nextInt();
System.out.println(“Enter b:”);
Int b=scan.nextInt();
if(a>b)
System.out.println(“a is bigger:”+a);
else
System.out.println(“b is bigger:”+b);
}
}

3. Nested if-else statement :


A if-else statement within the if-else statement is called a nested if-else
statement.
Syntax:
if(test_condition1)
{
if(test_condition2)
{
statement_block1;
}
else
{
Notes by, shivaling_shetty,,,
BSC CS III SEM OOP’S CONCEPT AND PROGRAMMING WITH JAVA
statement_block2;
}
}
else
{
statement_block3;
}

Here, statement_block1 is executed if the test_condition1 and test_condition2


both results true, statement_block2 is executed if the test_condition1 results true and
test_condition2 results false, and statement_block3 is executed if test_condition1
results false (hence if test_condition1 results false then test_condition2 does not
evaluated).

Example program:
class Bigger
{
public static void main(String args[])
{
int a=15,b=20,c=40;
System.out.println(“Bigger is:”);
if(a>b)
{
if(a>c)
System.out.println(a);
else
System.out.println(c);
}
else
{
if(c>b)
System.out.println(c);
else
System.out.println(b);
}
}
}

4. Else if ladder :
There is another way of putting ifs together when multipath decisions are
involved. A multipath decision is a chain of ifs in which the statement with each else is
an if.
Syntax:
Notes by, shivaling_shetty,,,
BSC CS III SEM OOP’S CONCEPT AND PROGRAMMING WITH JAVA
if(condition_1)
statement_1;
else if(condition_2)
statement_2;
else if(condition_3)
statement_3;
…………
else if(condition_n)
statement_n;
else
default_statement;

This is the syntax of else if ladder, here the conditions are evaluated from the
top if there any condition results true then statements associated with that condition
are executed, and control is transferred out of the else if ladder. When all conditions
result false then the final else containing default statement will be executed.

Example program:
class Big4
{
public static void main(String args[])
{
int a=35,b=10,c=26,d=20;
System.out.println("Bigger is:");
if(a>b && a>c && a>d)
System.out.println(a);
else if(b>a && b>c && b>d)
System.out.println(b);
else if(c>a && c>b && c>d)
System.out.println(c);
else
System.out.println(d);
}
}

5. Switch statement :
When we have many alternatives to be selected, java has a built-in multiway decision
statement known as switch. The switch statement tests the value of a given variable
against a list of case values and when a match is found, a block of statement

Notes by, shivaling_shetty,,,


BSC CS III SEM OOP’S CONCEPT AND PROGRAMMING WITH JAVA
associated with that case is executed. If value of variable doesn’t match with any
cases then default statement is executed.

Syntax:
switch(expression)
{
case value_1: statement_block1;
break;
case value_2: statement_block2;
break;
…………
case value_n: statement_blockn;
break;
default: default statement;
break;
}

Example program:
import java.util.Scanner;
class Switch
{
public static void main(String args[])
{
Scanner scan=new Scanner(System.in);
System.out.println("Enter two numbers:");
int a=scan.nextInt();
int b=scan.nextInt();
int c=0;
System.out.println("Choice operation to be perform:");
System.out.println("1.Addition");
System.out.println("2.Subtraction");
System.out.println("3.Multiplication");
int d=scan.nextInt();
switch(d)
{
case 1: c=a+b;
break;
case 2: c=a-b;
break;
case 3: c=a*b;
Notes by, shivaling_shetty,,,
BSC CS III SEM OOP’S CONCEPT AND PROGRAMMING WITH JAVA
break;
default : System.out.println("Error in input");
}
System.out.println("Result is "+c);
}
}

LOOPING CONTROL STATEMENTS :


The process of repeatedly executing a block of statements until condition
satisfies is known as looping.
> a looping process includes following four steps:
1. Initialization of a counter variable.
2. Execution of the statements in the loop.
3. Test for a specified condition for execution of the loop.
4. Incrementing the counter variable.

> the java language provides for three constructs for performing loop operations. They
are:
1. while construct
2. do while construct
3. for construct

1. while statement :
Syntax:
initialization;
while(test_condition)
{
body of the loop;
incrementing;
}
The while is an entry-controlled loop statement. The test_condition is evaluated
and if the condition is true, then the body of the loop is executed. After execution of
the body, the counter variable is increased and once again test_condition is
evaluated; if it is true, the body of the loop is executed once again. This process of
repeated execution of the body of the loop continues until the test_condition becomes
false and control is transferred out of the loop.

Example program:
class Fact
{
Notes by, shivaling_shetty,,,
BSC CS III SEM OOP’S CONCEPT AND PROGRAMMING WITH JAVA
public static void main(String args[])
{
int n=1; //initializing counter variable
while(n<=10)//test_condition
{
int fact=1;
int temp=n;
while(temp>0)
{
fact *= temp;
temp–; //decrementing counter variable
}
System.out.println(“Factorial of”+n+” is “+fact);
n++;
}
}
}

2. Do while statement :
Since the do while statement is an exit-controlled loop before evaluating the
test_condition for loop, once the body of the loop is executed. It means if
test_condition fails at first evaluation, the body of the loop is executed once.

Syntax:
initialization;
do
{
body of the loop;
}
while(test_condition);

Here, on reaching the do keyword, the body of the loop is executed once and
after test_condition in while is evaluated if it is true once again the body of the loop is
executed. This process continues as long as the test_condition is true. When the
test_condition becomes false, the loop will be terminated and the control goes out of
the loop.

Example program:
class Do
{
public static void main(String srgs[])
{
Notes by, shivaling_shetty,,,
BSC CS III SEM OOP’S CONCEPT AND PROGRAMMING WITH JAVA
int x=15;
do
{
System.out.println("value of x:"+x);
x++;
}while(x<20);
}
}

3. For statement :
The for loop is another entry-controlled loop that provides a more concise loop
control structure.
Syntax:
for(initialization;test_condition;increment)
{
body of the loop;
}

The execution of the for statement is as follows:


1. initialization of the counter variables is done first, using assignment operator i.e,
i=0. The variable i is known as loop counter variable.
2. The value of the counter variable is tested using test_condition. The
test_condition is a relational expression, such as i<10 that determines when the
loop will exit. If the condition is true, the body of the loop is executed. Otherwise
the loop is terminated and control transferred out of the loop.
3. When the body of the loop is executed, control is transferred to the back for the
statement, now the counter variable is incremented using increment statement.
Using a new counter variable test_condition is tested and if it is true once again
the body of the loop is executed or it is transferred out of the loop. This process
continues until the condition satisfies.
Example program:
class For
{
public static void main(String a[])
{
for(int n=1;n<=5;n++)
Notes by, shivaling_shetty,,,
BSC CS III SEM OOP’S CONCEPT AND PROGRAMMING WITH JAVA
{
System.out.println(n);
}
}
}

JAVA METHODS :
> We must add methods that are necessary for manipulating the data contained in the
class.
> methods are declared inside the body of the class but immediately after the
declaration of instance variables.
> declaration syntax:
datatype methodname(parameter_list)
{
method body;
}
> method declaration have four basic steps:
1. The datatype of the value the method returns (datatype).
2. The name of the method (methodname).
3. A list of parameters (parameter_list).
4. The body of the method.
> the datatype specifies the type of value the method would return. Such as int
datatype or void datatype if the method didn’t return any value.
>the method name should be a valid identifier.
> the parameter list is always enclosed in parentheses. This list contains variable
names and types of all the values we want to input in the method.
>variables in parentheses are separated by comma, in the case where no input data
are required the declaration must retain the empty parentheses.
Example:
class Rectangle
{
int length;
int width;
void getData(int x,int y) // method declaration
{
Notes by, shivaling_shetty,,,
BSC CS III SEM OOP’S CONCEPT AND PROGRAMMING WITH JAVA
length=x;
width=y;
}
}

METHOD OVERLOADING :
> in java, it is possible to create methods that have the same name, but different
parameter lists and different definitions. This is called method overloading.
> this is used when objects are required to perform similar tasks but using different
input parameters.
> when we call a method in an object, java matches up the method name first and
then the number and type of parameters to decide which one of the definitions to
execute. This process is known as polymorphism.
> to create an overloaded method, all we have to do is to provide several different
method definitions in the class, all with the same name, but with different parameter
lists.
> the difference may either be in the number or type of arguments. That is, each
parameter list should be unique.
> example:
class Room
{
float length;
float breadth;
Room(float x,float y) //constructor1
{
length=x;
breadth=y;
}
Room(float x) //constructor2
{
length=breadth=x;
}
int area()
{
return(length*breadth);

Notes by, shivaling_shetty,,,


BSC CS III SEM OOP’S CONCEPT AND PROGRAMMING WITH JAVA
}
}
Here, we are overloading the constructor method Room(). An object representing a
rectangular room will be created as:
Room room1=new Room(25.0,24.0); // using constructor1
On the other hand, if the room is square, then may create corresponding object as:
Room room2=new Room(10.0); // using constructor2

MATH CLASS :
Java supports basic math functions through the Math class defined in the
java.lang package.
List some functions defined in the Math class:

Functions Action
sin(x) returns the sine of the angle x in radians
cos(x) returns the cosine of the angle x in radians
tan(x) returns the tangent of the angle x in radians
asin(x) returns the angle whose sine is y
pow(x,y) returns x to the power y
log(x) returns the logarithm of x
sqrt(x) returns the square root of x
abs(x) returns absolute value of x
max(x,y) returns the maximum of x and y
min(x,y) returns the minimum of x and y

Example program:
class math
{
public static void main(String a[])
{
double x;
x=Math.max(20,10);
System.out.println(“Maximum of 20 and 10:”+x);

Notes by, shivaling_shetty,,,


BSC CS III SEM OOP’S CONCEPT AND PROGRAMMING WITH JAVA
x=Math.sqrt(25);
System.out.println(“Square root of 25:”+x);
x=Math.pow(3,2);
System.out.println(“square of 3:”+x);
}
}

ARRAYS IN JAVA :
“Array is a linear collection of homogeneous data elements.”
* creating an array:
> Like variables, arrays must be declared and created in the computer memory before
they are used.
> creation involves three steps:
1. Declaring the array.
2. Creating memory locations(size)
3. Initializing array.
> declaration of array:
Syntax: datatype arrayname[]; or datatype[] arrayname;
Ex: int a[];
float[] b;
Note: we do not enter the size of the array in the declaration.
>creation of array :
After declaring an array, we need to create it in the memory. Java allows us to
create an array using a new operator only.
Syntax: arrayname=new datatype[size];
Ex: a=new int[4];
This line create necessary memory locations for the array a and designate it as
int respectively. Now variable a refers to an array of 4 integers.

It is also possible to combine the two steps declaration and creation into one line
Syntax: datatype arrayname[]=new datatype[size];
Ex: int a[]=new int[4];

> initialization of array :

Notes by, shivaling_shetty,,,


BSC CS III SEM OOP’S CONCEPT AND PROGRAMMING WITH JAVA
The final step is to initialize values into the array created.
Syntax: arrayname[subscript]=value;
Ex: a[0]=10;
a[1]=20;
a[2]=30;
a[3]=40;
> also initialize in single line:
Ex: int a[]={10,20,30,40};

> array length:


> in java all arrays store the allocated size in a variable named length. We can obtain
the length of the array using the length keyword.
Syntax: datatype variable=arrayname.length;
Ex: int n=a.length;

Example program:
class Array
{
public static void main(String args[])
{
int[] a = {10, 20, 30, 40, 50};
System.out.println("Array elements:");
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
}
}

Notes by, shivaling_shetty,,,

You might also like