Java_Unit-1
Java_Unit-1
1 Introduction
JAVA History:
• It is true object oriented programming language
• It was developed by Sun Microsystems of USA in 1991.
• It was specially design for the software for electronics devices such as TV, VCRs, Mobile, DVD,
etc.
• Initially name of JAVA was Oak.
• This new language developed by removing certain drawbacks of C and C++ such as reliability
and portability.
The following discussion shows some important milestones in the development of Java.
Year Development
1990 Sun Microsystems decided to develop special software for electronic devices such as TV,
VCRs, Mobile, DVD etc. A team member of Sun Microsystems was starting to work on
this project.
1991 A green project team announced a new language named “Oak” based on Object oriented
programming concepts. This name was given by Mr. James Gosling who was leader of
this team.
1992 A green project team demonstrated the application of the new language.
1993 The Green project team developed Web applets using a new language that could run on
all types of computers connected to internet. This development becomes a very useful for
World wide web on the internet for converting text data into graphical form (Applet
form).
1994 The team developed a Web browser called “HotJava” to locate and run applet program
on internet. This Web browser demonstrated the powerful use of this language. That why
this language becomes a popular for the internet user.
1995 Oak was renamed to “JAVA”. Many popular Web browser companies such as Netscape,
Microsoft announced their support to java.
1996 Java becomes a leader for Internet programming.
Java Features:
Sun Microsystems describes Java with the following features.
1. Complied and Interpreted
2. Platform-Independent and Portable
3. Object Oriented
4. Robust and Secure
5. Distributed
6. Simple, Small and Familiar
7. Multithreaded and Interactive
8. High performance
9. Dynamic and Extensible
10. Platform-neutral Language
• Java Interpreter generates a machine code from the Bytecode. This will run a Java program.
From this we can say that Java is both a compiled and interpreted language.
2. Platform-Independent and Portable:
• Java program can be easily moved from one computer system to another, anywhere and anytime.
There are any changes and upgrades in operating system, processors and system resources will
not force any changes in Java program. This is the reason why Java becomes a popular language
for programming on internet which interconnects different kinds of computer systems
worldwide.
• Java generates a Bytecode instruction that can be executed on any machine. The size of the
primitive data types are machine independent.
3. Object Oriented:
• It is true object oriented programming language. Almost everything in java is an Object. All
program code and data reside within objects and classes. Java comes with an extensive set of
classes arranged in packages that can be used in our programs by inheritance.
4. Robust and Secure:
• It is a robust language. It provides a many safeguards to ensure reliable code. It has strict
compile time and Run time checking for data types. It provides the concepts of Exception
handling that captures series of errors and removed any risk of crashing the system.
• Java provides a security against viruses and misuse of computer resources. It is important to
provide security for a language that is used for programming on internet. There are possibilities
of viruses and misuse of resources is everywhere. The absence of pointers in Java, nobody can
direct access memory location without prior permissions. Java systems verify all memory access
and also ensure that no viruses are communicated with an applet.
5. Distributed:
• Java is a distributed programming language. It has ability to share both data and programs. Java
application can open and access remote object on internet as easily as they can do in local
system.
6. Simple, Small and Familiar:
• Java is small and simple language. Java does not include so many features of C and C++
language. It means that some sources of unreliable code are not part of java. For
• Example, java does not use pointers, preprocessors, header file Goto statement and so many
others.
• Java is familiar to the existing programmers. The java was designed based on C and C++
languages. Therefore, it is familiar to the existing programmers.
7. Multithreaded and Interactive:
• Java performance is impressive due to the use of intermediate bytecodes. Java speed is
comparable to the same as C\C++. It reduces overheads during runtime. The overall execution
speed of Java program increases, due to multithreaded programming.
9. Dynamic and Extensible:
• Java is a Dynamic language. It supports the dynamic linking in new class libraries, methods and
object. Java can determine the type of class through query, making possible to either dynamically
link or abort the program, depending on the response.
• Java is extensible language. Java programs supports functions written in other languages such as
C and C++. These functions are known as native methods. They are linked dynamically at
runtime.
10. Platform-neutral Language:
• It is most important feature of a java program. Programs developed in Java can be executed
anywhere on any system. It does not depend on any particular hardware or operating system.
All language compilers translate source code into machine code for a specific computer. Java compiler
is also does the same thing but slightly differently. Java compiler converts the source code into
bytecodes for a machine. This machine is called the Java Virtual Machine (JVM). JVM exist only
inside the computer memory and does all major functions of a real computer.
The following figure shows the process of compiling a java program into bytecodes which is also
referred to as virtual machine code.
Documentation section
Suggested
Package statement
Import statements
Class definitions
1. Documentation section:
• The documentation section consists of a set of comment lines giving the names of the program,
the author and other details.
Java supports three types of comments:
A. Single line comment : It begins with // and ends at the end of the line.
B. Multiline comment : It begins with /* and ends with */.
C. Documentation comment : It begins with /** and ends with */. It is used for generating
documents automatically.
2. Package statement:
• The package statement is the first statement in a java file. This statement declares a name of the
package. The package statement is optional. E.g. package student ;
3. Import statement:
• This will contains number of import statements. It is similar to the #include statement in C\C++
language. It is an optional statement. The import statement must be written before any class
declarations.
E.g. import java.lang.Math ;
• It imports the class math and this class can be directly used in program.
4. Interface statement:
• The interface statement is used for achieving the multiple inheritances in Java. It is an optional
statement. It is same as a class and contains group of methods.
5. Class definitions:
• A java program may contain multiple class definitions. The class definition contains the
declarations of multiple classes. Classes are the elements of a java program.
• These classes are used to map the object of real world problems. The number of classes depends
on the complexity of the problem.
6. Main method class:
• Every java program must contain one main method class which contains main function. The
execution starts with opening curly brace “{“and ends with a closing curly brace “}”of main()
function.
Comments line
• The first line is the comment lines starting with ‘//’ character. Java supports both single line and
multiple line comments available in C++.
Class declaration
• Every class definitions in java begins with an opening curly brace “{“ and end with matching
closing curly brace “}”. This is similar to C++ class construct except semicolon at closing brace.
The main method
• Public :
o It is an access specifier. It means that main() method is accessible to all other classes.
• Static :
o It declares that the main() method belongs to the entire class and not a part of any object
of the class. The main() method must always declared as static since the interpreter uses
this method before any objects are created.
• Void :
o It means that main() method does not return any value.
• String args[ ] :
o All parameters to a method are declared inside a pair of parentheses. String args[ ]
declares a parameter name args, which contains an array of object of the class String.
The output line
{
System.out.println( “Good Morning”) ;
}
}
Now, save this program in a file as test.java. This file is known as source file.
2. Compiling the program:
• This command compiles test.java and creates a new file test.class. The test.class contains the
bytecodes of the program.
3. Running the program:
Java token:
The smallest individual units in a Java program are known as token. OR The character together makes
special symbols or word known as token.
Java language includes five types of tokens and they are:
1. Reserved keywords
2. Identifiers
3. Literals
4. Operators
5. Separators
1. Keywords
• Keywords are essential part of language definition. They implement specific features of the
language.
• All keywords are written in lower case letters. Java language has reserved 60 words as keywords.
The keyword has specific meaning in language, so we can not use them as name of variable,
class, method and so on. Java does not use many of the C and C++ keyword. Java adds new 27
keywords that are not in C and C++.
2. Identifiers:
• Identifiers are programmer-designed tokens. They are used for naming classes, methods,
variables, objects, labels, packages and interfaces in a Java program.
• A literal in java represents constants values to be stored in variables. A Java language has five
types of literals. They are:
1. Integer literal
2. Floating point literal
3. Character literal
4. String literal
5. Boolean literal
4. Operators:
• "An operator is a symbol that tells the computer to perform certain mathematical or logical
manipulations"
• Separators are symbols used to indicate where groups of code are divide and arranged. The
following are list of separators with their functions.
Name Uses
Constant:
"A constant is a fixed value that can be unchanged during program execution.”
Types of constant:
Java support several types of constant as shown below.
• Numeric Constants
o Integer Constants
o Real Constants
• Character Constants
o Single character constants
o String constants
Numeric Constants:
Integer Constants:
An integer constant is a sequence of digits. There are three types of integer, namely decimal octal and
hexadecimal.
• Exponential Notation: It is useful in representing numbers whose magnitudes are very large or
small. It consists of a mantissa and an exponent.
The general form is
mantissa e exponent
Character Constant:
Single Character Constant:
• The characters may be letters, numbers, special characters and blank space.
Valid Example:
"Hello" "F.Y.B.CA." “2004” “?....” “ 1 + 2"
Variable:
A Variable is an identifier whose value can be changed during program execution.
Rules for writing variable names:
Variable names may consist of letters, digits, underscore (_) and dollar character with the following
rules.
1. They must not begin with a digit.
2. It is case-sensitive. It means lower case and uppercase are different. E.g. the variable name Total
and total both are different.
3. It should not be a keyword.
4. White space (Blank space) is not allowed.
5. It can be of any length.
Some examples
average, height, total_height, classStrength.
Primitive Non-Primitive
Primitive:
Integer data type:
Java supports four types of integers. They are byte, short, int and long. All of these are
signed integers. It means that the value of a variable is either negative or positive. Java does not
support unsigned integers.
The following table shows the size and range of integer data types in java.
The float data type represents single-precision numbers while double is double-precision
numbers.
The following table shows the size and range of floating-point data types in java.
Declaration of variables:
A variable can be used to store a value of any data type.
The general form variable declaration is
data type variable1, variable2, . . . . . . VariableN ;
Here, data type is any valid data type of java such as int, short, float, char etc. and variable1,
variable2,…….VariableN are any valid variable names.
Two or more variable names are separated by comma. A declaration statement must end with a
semicolon.
Examples of declaration of variables:
byte b1;
int a, b, total;
char c1, c2, gender;
Assignment statement:
• A simple method of giving a value to a variable is by using assignment statement. The general
form of this is:
variableName = value ;
• For example:
total = 50 ;
gender = ‘M’;
• It is possible to assign single value to multiple variables by a single statement as shown below.
a = b = c = 0;
• It is possible to assign a value to a variable at the time of its declaration. The general form of this
is:
data type variableName = value ;
• For example:
int a=0;
char gender = ‘M’;
• The process of giving initial value to variable at the time of its declaration is known as the
initialization. The variables are not initialize at declaration are automatically initialized by its
default value.
• For example:
int a, b=5; //Here, variable ‘a’ is initialize with zero.
Read statement:
• The following java program demonstrates that how to read a data from the keyboard.
//To print a square of a number.
import java.io.*;
public class square
{
public static void main(String args[]) throws IOException
{
DataInputStream in = new DataInputStream(System.in);
int a,b;
System.out.print("Enter any number: ");
a = Integer.parseInt(in.readLine());
b = a * a;
System.out.println("Square of a given number "+a+" is "+b);
}
}
Output:
Enter any number: 4
Square of a given number 4 is 16
• The readLine() is a method of DataInputStream class and is used to read the input from the
keyboard as a string. This value then converted into integer by using parseInt() method of Integer
class.
Scope of Variables:
Java variables have three categories.
1. Instance variable
2. Class variable
3. Local variable
Instance variable:
• It is declared inside a class. It is created when the object of a class created. It takes different
values for each object. It is accessed by using object.
Example: class student
{
int s_no, s_marks ;
}
• The class student contains two instance variables of integer data type, s_no and s_marks. The
following statement creates an object of the above class.
student s1 = new student();
• Now, the instances variables s_no and s_marks are used in a program by s1.s_no and s1.s_marks
respectively.
Class variable:
• Definition: A static variables declared in a class is known as class variable. It is also known as
static variable.
• It is global to a class and only one memory location is created for each class variable. It is used
when we want to have a variable common to all instance of a class. It is accessed by using name
of the class.
//Example of static variable.
//Write a Java program to count the number of object created in a program.
import java.io.*;
class square
{
static int count;
square()
{
count=count+1;
}
}
public class ObjectCount
{
public static void main(String[] args) throws IOException
{
Output:
Total number of object is: 3
• In above program, the variable ‘count’ is declared as a static variable in a class square. Each time
object of a class ‘square’ is created, its
Local variable:
• Definition: A variable declared and used inside a method is known as local variable.
• A variable declared inside a method is only visible to that method. Some variables are declared
in a program block that is defined between opening and closing curly brace. They are only
visible to that block only.
//Program for local variable.
class test
{
public static void square()
{
int a=5,b;
b=a*a;
System.out.println("Square :"+b);
}
public static void main(String args[])
{
square();
}
}
• In above java program, variables ‘a’ and ‘b’ both are local variables for a square function. These
two variables can not use in main() method otherwise it give an error.
Type casting:
• It is process to convert value of a variable from one data type to another. The general form of
type casting is
Data-type varibale1 = (data-type) variable2 ;
Example:
int m = 50;
• byte n = (byte) m ; In above example, the conversion is done from integer to byte. This is a
conversion from larger data type to smaller data type. There is possibility of data loss in the
conversion. This type of conversion is known as narrowing.
Automatic conversion
• Java does the conversion of one data type to another data type for some data types automatically
which is known as automatic conversion.
Example:
int m = 50;
long n = (long) m ;
• In above example, the conversion is done from integer to long. This is a conversion from smaller
data type to larger data type. There is no possibility of data loss in the conversion. This type of
conversion is known as widening or promotion.
Default values
In java, every variable has a default value. The following table shows default values for various data
types.
Type of variable Default value
Byte 0 (Zero)
short 0
Int 0
Long 0L
float 0.0f
double 0.0d
boolean false
reference null
Operators
"An operator is a symbol that tells the computer to perform certain mathematical or logical
manipulations”. Java operators can be classified into a number of categories. They include
1. Arithmetic Operator
2. Relational Operator
3. Logical Operator
4. Assignment Operator
5. Increment and Decrement Operator
6. Conditional Operator
7. Bitwise Operator
8. Special Operator
1. Arithmetic Operator:
• Java provides all the basic arithmetic operators. These can operate on any built-in numeric data
type of Java. It can not operate on Boolean data type of Java. Java has both unary and binary
arithmetic operators. The arithmetic operators and their meaning are shown below:
Operator Meaning
* Multiplication
/ Division
% Modulo division
• Integer Arithmetic: When both the operands in a single arithmetic expression (such as a + b)
are integers, the expression is called integer expression, and the operation is called integer
arithmetic. Integer arithmetic always results an integer value.
Example: If a & b are integer & its value is a = 14 and b=4 then we have the following
Results:
a -b results 10, a + b results 18; a*b results 56, a/b results 3 (decimal part truncated) and a
% b results 2 (remainder).
• Real Arithmetic: An arithmetic operation involving only real operands is called real arithmetic.
Example: If a, b and c are floats then we will have
a = 20.5, b=6.4
then a+b becomes 26.9, a-b becomes 14.1, a*b becomes 131.2 and a/b becomes 3.20313.
Java also support modulo division on float type variable. So, a%b becomes 1.3.
• Mixed-Mode Arithmetic: When one of the operand is real and the other is integer the
expression is called Mixed-mode arithmetic expression.
If either operand is of the real type, then only the real operation is performed and the result is
always a real number. Thus 15/10.0 gives 1.5 while 15/10 gives 1.
2. Relational Operator:
• A relation operator is used to make comparisons between two expressions.Java language
supports six relational operators. These operators and their meaning are shown below.
Operator Meaning
== Is equal to
!= Is not equal to
3. Logical Operator:
Logical operators are useful in combining one or more conditions. Java language has the
following three logical operators.
Operator Meaning
&& Logical AND(True only if all conditions are true, otherwise false)
4. Assignment Operator(=):
• Assignment operators are used to assign the result of an expression to a variable. The general
form of assignment operator is
variable = expression;
• Example:
A += 1; same as A = A + 1;
B+= 1; same as B= B+ 1;
A += B + 3; same as A = A + (B + 3);
A *= B; same as A = A * B;
A /= B; same as A = A / B;
• These operators increase or decrease the value of a variable by 1. The operator ++ adds 1 to the
operand and -- subtract 1 from the operand.
• Syntax:
Prefix Postfix
++VariableName VariableName++
--VariableName VariableName--
• When used a prefix, the value of a variable is incremented/ decremented before used in
expression. But when used as a postfix, its value is first used in expression and then the value is
incremented/ decremented.
Example:
[1] A=5 [2] int a = 0, b = 10:
A++ a = ++b; a = b++;
The value of a is 6. The value of a becomes 11 & The Value of a becomes10 and
b is 11. b is 11.
6. Conditional Operator
• It is also known as Ternary Operator.
• If it is non-zero (true), then the expression exp2 is evaluated and becomes the value of the
expression.
• If it is zero (false), then the expression exp3 is evaluated and becomes the value of the
expression.
Example: A = 10;
B = 15;
X = (A>B) ? A : B;
• In this example, X will be assigned the value of B. This can be achieved using the if...else
statements as follows.
if ( A > B)
X=A;
else
X = B;
7. Special Operator
• Java support some special operators such as
A. instanceof operator
B. dot operator
A. instanceof operator:
• The instanceof operator 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. It is used
to check whether an object belongs to a particular class or not.
Example: person instanceof student
• is true if the object person belongs to the class student, otherwise it is false.
B. Dot operator:
• It is used to access the instance variable and method of class objects. It is also used to
access classes and sub-packages from a package.
Example:
person1.age //Reference to the variable age.
person1.salary() // Reference to the method salary.
Decision making
Introduction
When a program breaks the sequential flow and jumps to another part of the block, it is called
branching. When the branching is based on a particular condition, it is known as conditional
branching. If branching takes place without decision, it is known as unconditional branching.
Branching statement:
It alters (changes) sequential execution of program statements. They are
1. if statement
1.1 if statement
1.2 if…else statement
1.3 Nested if…else statement
1.4 Else if ladder
2. switch statement
1.1. if statement:
It is decision making statement. It is used to control the sequence of the execution of statements.
Syntax:
if ( condition )
{
Statement-1;
}
Description: Initially condition is evaluated. Statement-1 is executed only if condition is true.
Example:
import java.io.*;
class t
{
public static void main(String args[]) throws IOException
{
int age;
BufferedReader in=new BufferedReader (new InputStreamReader(System.in));
import java.io.*;
class t
{
public static void main(String args[]) throws IOException
{
int a, b;
BufferedReader in = new BufferedReader ( new InputStreamReader(System.in));
System.out.print("Enter a : ") ;
a=Integer.parseInt(in.readLine()) ;
System.out.print("Enter b : ") ;
b=Integer.parseInt(in.readLine()) ;
if ( a > b )
System.out.println("Given number a="+a+" is maximum") ;
else
System.out.println("Given number b="+b+" is maximum") ;
}
}
Output:
Enter a : 54
Enter b : 25
Given number a = 54 is maximum
1.3. Nested if…else statement: one if…else statement written inside another if…else statement is
known as nested if ... else statement.
Syntax:
if ( condition-1 )
{
if ( condition-2)
{
Statement-1;
}
else
{
Statement-2;
}
}
else
{
Statement-3;
}
next_statement ;
Description:
Initially condition-1 is evaluated.
• If condition-1 is true then it tests the condtion-2. If the condition-2 is true then statement-1 is
executed otherwise statement-2 is executed. The control passes to the next_statement following
the if…else statement.
• If the condition-1 is false then statement-3 will be executed.
Example: Write a Java program to read a number and check whether it is zero or positive or negative
number using nested if…else statement.
import java.io.*;
public class NestedIf
{
public static void main(String args[]) throws IOException
{
int a;
BufferedReader in = new BufferedReader (new InputStreamReader(System.in));
System.out.print("Enter a:");
SVICA / BCA Sem: IV / US04MABCA01 - Object Oriented Programming-I Page 29
UNIT-I Introduction
a=Integer.parseInt(in.readLine());
if ( a>=0 )
if( a>0 )
System.out.println("a="+a+" is Positive.");
else
System.out.println("a="+a+" is Zero.");
else
System.out.println("a="+a+" is Negative.");
}
}
Output:
Enter a : 10
a = 10 is Positive.
Statement-3;
}
else
{
Statement;
}
Description:
Initially the condition-1 is tested.
Example: Write a java program to read a number and print its corresponding color name using
following data using else if ladder.
Color code Name of a color
1 Red
2 Green
3 Blue
4 Black
import java.io.*;
public class ElseIfLadder
{
public static void main(String args[]) throws IOException
{
int a;
BufferedReader in = new BufferedReader (new InputStreamReader(System.in));
System.out.print("Enter a color code:");
a=Integer.parseInt(in.readLine());
if ( a= =1 )
System.out.println("Red color");
else if ( a= =2 )
System.out.println("Green color");
else if ( a= =3 )
System.out.println(" Blue color");
else
System.out.println("Black color");
}
}
Output:
Enter a color code : 3
Blue color
2. switch statement:
It is a multi-way decision making statement the allows choosing of a statement ( or a group of
statements) among several alternatives.
Syntax:
switch ( expression )
{
case value1 : statement1;
break;
case value2 : statement2;
break;
:
:
default : statement;
}
Next_statement ;
Description: Initially expression is solved. Control transfer to the statements following the case whose
value is equal to the value of the expression. The default part is optional in switch statement.
Example: Write a java program to read a number and print its corresponding color name using
following data using switch statement.
Color code Name of a color
1 Red
2 Green
3 Blue
import java.io.*;
public class Switch1
{
public static void main(String args[]) throws IOException
{
int a;
BufferedReader in = new BufferedReader (new InputStreamReader(System.in));
System.out.print("Enter a color code:");
a=Integer.parseInt(in.readLine());
switch( a )
{
case 1 : System.out.println("Red color"); break;
case 2 : System.out.println("Green color"); break;
case 3 : System.out.println("Blue color"); break;
default : System.out.println("Wrong choice.");
}
}
SVICA / BCA Sem: IV / US04MABCA01 - Object Oriented Programming-I Page 33
UNIT-I Introduction
}
Output:
Enter a color code : 3
Blue color
Looping statements:
It is also known as Iteration statements. There are three looping statements in Java.
They are
1. while loop
2. do…while loop
3. for loop
The condition can be any Boolean expression. The body of loop will be executed as long as the
condition is true.
Description: Initially condition is tested.
• If the condition is true then the body of loop is executed and the execution continues as long
as it remains true.
• If the condition is false then loop is terminated and next_statement is executed.
{
public static void main(String args[]) throws IOException
{
DataInputStream in = new DataInputStream(System.in);
int i, n;
System.out.print("Enter any positive number:");
n = Integer.parseInt(in.readLine());
i=1;
while(i<=n)
{
System.out.print(i+", ");
i=i+1;
}
}
}
Output:
Enter any positive number: 3
1, 2, 3,
2. do… while:
Syntax:
do
{
body of loop
} while ( condition ) ;
next_statement ;
Description: Initially body of loop is executed and then condition is evaluated. The body of loop is
executed as long as the condition remains true. The loop is terminating when condition becomes false.
3. for loop:
The for loop is useful while executing a statement a fixed number of times.
Syntax:
for(initialization ; condition ; updation)
{
body of loop
}
next_statement ;
Description: The initialization part is executed only once. Next the condition is evaluated.
• If the condition is false then the next statement after for loop is executed.
• If the condition is true then after executing the body of loop and then update part is executed.
The condition is evaluated once again and the whole process is repeated as long as the condition
is true.
Example: Write a Java program to display 1 to N number using for loop.
//To print 1,2,3,....N using for loop
import java.io.*;
public class for1
{
public static void main(String args[]) throws IOException
{
DataInputStream in = new DataInputStream(System.in);
int i,n;
System.out.print("Enter any positive number :");
n = Integer.parseInt(in.readLine());
for( i=1 ; i<=n ; i++ ) System.out.print(i+", ");
}
}
Output:
Enter any positive number : 3
1, 2, 3,
Jumps in Loop:
Sometime, when executing a loop it becomes desirable to leave the loop or skip a part of the loop. This
will be done by jumping statement in the loop.
There are two ways to jump in a loop.
1. Jumping out of a loop ( break statement)
2. Skipping a part of a loop ( continue statement )
1. break statement:
Syntax:
break ;
Description: A break statement terminates the execution of loop and the control is transferred to the
statement immediately following the loop.
A break statement is very useful in switch statement.
Example: Write a Java program to display square of the given number and use 0(zero) for exit.
import java.io.*;
public class break1
{
public static void main(String args[]) throws IOException
{
DataInputStream in = new DataInputStream(System.in);
int n;
while(true)
{
System.out.print("Enter any number :");
n = Integer.parseInt(in.readLine());
if (n= =0 ) break;
System.out.println("Square of "+n+" is "+n*n);
}
}
}
Output:
Enter any number : 3
Square of 3 is 9
Enter any number : 7
Square of 7 is 49
Enter any number : 0
2. continue statement:
Syntax:
continue ;
Description: A continue statement skips the remaining statement in the loop and control transfer to the
condition.
Example: Write a Java program to display sum of only positive numbers.
import java.io.*;
public class continue1
{
public static void main(String args[]) throws IOException
{
DataInputStream in = new DataInputStream(System.in);
int n,s=0;
while(true)
{
Arrays:
• An array is collection of same data type that is referred by a common name.
• An array is a group of like-typed variables that are referred to by a common name.
• Arraysof any type can be created and may have one or more dimensions.
• A specific elementin an array is accessed by its index.
• Arrays offer a convenient means of groupingrelated information.
Types of an array:
It can be
• One-dimensional array
• Two-dimensional array
• Multi-dimensional array
One-dimensional array:
Creating a one-dimensional array:
Initialization of an array:
An array can be initialized when they are declared.
Syntax:
datatype arrayname [ ] = {List of values separated by comma} ;
Here, datatype is any fundamental datatype of Java such as int, char, float etc. arrayname is a
valid identifier that gives name of an array.
There is no need to write size of an array. There is no need to use new operator.
Example:
int age[ ] = {10, 20, 30, 40, 50};
Here, size of an array is 5. A value of age[0] is 10, age[1] is 20 and so on.If you try to access
elements outside the range of the array, you will cause a run-time error.
Multidimensional Arrays:
In Java, multidimensional arrays are actually arrays of arrays. These, as you might expect, look
and act like regular multidimensional arrays. However, as you will see, there are a couple of subtle
differences. To declare a multidimensional array variable, specify each additional index using mother set
of square brackets. For example, the following declares a two-dimensional array variable called twoD.
Example:
int twoD[][] = new int[4][5];
The following program numbers each element in the array from left to right, top tobottom, and then
displays these values:
Example:
// Demonstrate a two-dimensional array.
class TwoDArray
{
public static void main(String args[])
{
int twoD[][]= new int[4][5];
int i, j, k = 0;
SVICA / BCA Sem: IV / US04MABCA01 - Object Oriented Programming-I Page 42
UNIT-I Introduction