Introduction To Java
Introduction To Java
java programming
bsc cs
INTRODUCTION TO JAVA
1.1 Overview Of Java
Java is a OOPS based programming language.Java was designed to be easy for the
professional programmer to learn and use effectively.If you already understand the basic
concepts of OOPS, learning Java will be even easier. The ability to create robust programs
was given high priority in the design of Java.In a well written Java program, all run-time
errors can and should be managed by your program. Java enables the creation of crossplatform programs by compiling into an intermediate representation called Java bytecode.
This code can be interpreted on any system that provides a Jav a Virtual Machine.
Module1
I.
II.
III.
IV.
V.
VI.
VII.
VIII.
IX.
X.
XI.
java programming
bsc cs
Simple
Secure
Portable
Object-oriented
Robust
Multithreaded
Architecture-neutral
Interpreted
High performance
Distributed
Dynamic
Simple
Java is a simple programming Language .Java was designed to be easy for the professional
programmer to learn and use effectively. Java inherits the C/C++ syntax and many of the
object-oriented features of C++.So most programmers have little trouble learning java. Also,
some of the more confusing concepts from C++ (like pointers, multiple inheritance) are either
left out of java or implemented in a cleaner, more approachable manner. Automatic garbage
collection has been added.
Object-Oriented
Java is a true object oriented language. The object-oriented facilities of Java are essentially
those of C++.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
we can use in our program by inheritance. The object model in java is simple and easy to
extend. The object model in Java is simple and easy to extend.
Robust
Java is a robust anguage.it provides many safeguards to ensure reliable code. java is a strictly
typed language, it checks your code at compile time. However, it also checks your code at run
time. It also incorporates the concepts of exception handling which captures runtime errors
and eliminates any risk of crashing system
Architecture Neutral
Java compiler generates an architecture-neutral object file format, which makes the compiled
code to be executable on many processors, with the presence of Java runtime system. The
Java compiler does this by generating byte code instructions which is not depend on any
particular computer architecture. Rather, they are designed to be both easy to interpret on
any machine and easily translated into native machine code. Their goal while developing
java was write once; run anywhere, anytime, forever.
Platform independent and portable: 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 virtual Machine (JVM) on whichever platform it is being run. Being architectural-
Module1
java programming
bsc cs
neutral and having no implementation dependent aspects of the specification makes Java
portable.
Secure: With Java's secure feature, it enables to develop virus-free, tamper-free systems.
Absence of pointers in java ensures that program cannot gain access to memory locations
without proper authorization.
Multithreaded
Java was designed to meet the real-world requirement of creating interactive, networked
programs. To accomplish this, Java supports multithreaded programming, which allows
you to write programs that do many things simultaneously. This means that we need not wait
for the application to finish one task before beginning another. The Java run-time system
comes with an elegant yet sophisticated solution for multiprocess synchronization that
enables you to construct smoothly running interactive systems.
Module1
java programming
bsc cs
Java can be used to create two types of programs: applications and applets. An
application is a program that runs on your computer, under the operating system of
that computer. Applets are small programs developed for internet applications. An
applet located on a distance computer(server) can be downloaded via internet and executed
on a local computer(client) using java compatible web browser. We can develop applets for
doing everything from simple animated graphics to complex games and utilities. An applet is
downloaded on demand without further interaction with user .If the user clicks on a link that
contains applet, the applet will be automatically downloaded and run in browser. An applet is
actually a tiny java program, dynamically downloaded across the network, just like an image,
sound file, or video clip.
Bytecode
The details of JVM will differ from platform to platform, but all understand the same java
Bytecode.
Module1
java programming
bsc cs
II.
III.
IV.
V.
Simple program
Class example
5
Module1
java programming
bsc cs
{
/* this is a multi
Line comment*/
Public static void main(String args[])
{system.out.println(This is a simple java program);
}
}
Class declaration
By convention, class names begin with a capital letter and capitalize the first letter of each
static
void
main(String args[])
When a class member is preceded by public, then that member may be accessed by code
made.
The keyword void simply tells the compiler that main( ) does not return a value.
String args[] - declares a parameter named args which is an array of instances of class string.
Module1
java programming
bsc cs
This line outputs the string This is a simple Java program. followed by a new line on the
screen.
Compiling
The Java compiler requires that a source file. use the .java filename extension.
-c:\>javac example.java
Creates example.class- bytecode
To run c:>java example
Java program contains many classes of which only one class defines main
method
Documentation section
This section contains set of comment lines
Package statement
This statement declares package name and informs the compiler that classes defined here
belongs to this package.
7
Module1
java programming
bsc cs
Import statement
Similar to #include
Example
Import student.test
Instruct interpreter to load test class contained in package student
Interface statement
Class definitions
Keywords
continue
if
private
throw
goto
Package
Synchronized
assert
default
this
Boolean
Implements
do
protected
break
Double
Import
Instanceof
return
byte
public
throws
else
Case
Transient
try
extends
switch
int
short
Finally
Strictfp
catch
volatile
final
static
void
Char
Interface
long
native
class
float
super
While
Const
for
new
Module1
java programming
bsc cs
Data types
Integers : This group includes byte, short, int, and long , which are for whole-valued signed
numbers.
Floating-point numbers : this group includes float and double, which represent numbers with
fractional precision.
characters : This group includes char, which represents symbols in a character set, like
letters and numbers.
Boolean : This group includes Boolean, which is a special type for representing true / false
values.
integers
Java defines 4 integer types: byte, short, int, and long. All of these are signed, positive
and negative values.
The width and ranges of these integer types vary widely, as shown in this table:
Floating-point types
Floating-point numbers, also known as real numbers, are used when evaluating expressions
that require fractional precision .
Module1
java programming
bsc cs
There are two kinds of floating-point types, float and double, which represents single and
double-precision numbers, respectively.
characters
Java has a primitive type , called Boolean, for logical values.It can have only one of two
possible values, true or false
Reference variables are created using defined constructors of the classes. They are used to
access objects. These variables are declared to be of a specific type that cannot be changed.
type.
Example: Animal animal = new Animal("giraffe");
If the two types are compatible, then java will perform the conversion
automatically.
10
Module1
java programming
bsc cs
However, not all types are compatible, and thus, not all type conversions are
implicitly allowed. for instance, there is no automatic conversion defined from double to
byte.
To do so, you must use a cast, which performs an explicit conversion between
incompatible types.
When one type data is assigned to another type of variable, an automatic type
conversion will take place if the following two conditions are met:
The two types are compatible
The destination type is larger than the source type
If you want to assign an int value to a byte variable then this conversion will not be
To create a conversion between two incompatible types, you must use a cast.
If the integer's value is larger than the range of a byte, it will be reduced modulo bytes
range.
int a;
byte b;
//
b=( byte) a;
variables
Module1
java programming
bsc cs
Int d=3;.
Identifiers
Identifiers are used for class names, method names, and variable names.
An identifier may be any descriptive sequence of uppercase and lowercase letters, numbers
identifier.
Instance names(object identifier)-names given to the objects are called object identifiers
Data identifiers and method identifiers-any local or global variable names that is given
for a method of a class is called method names or method identifier .names for a attribute are
Integer Literals
.Any whole number value is an integer literal.
eg:1,4,43.
These all are decimal values, that means they are describing base 10 number.
There are other two bases which can be used in integer literals.
They are hexadecimal and octal.
An octal digit ranges from 0-7, while a hexadecimal digit ranges from 0-15A through F are
substituted for 10 through 15.
An octal value is represented with a leading 0.
Hexadecimal digit is represented by leading 0x.
Floating Point Literals
Floating point numbers represent a decimal value with a fractional component.
They can be expressed in either scientific or standard notation .
12
Module1
java programming
bsc cs
Standard notation has a whole number component followed by a decimal point followed by a
fractional component
eg:3.5788S
scientific notation uses a standard floating point number plus a suffix that specifies a power of
negative.
Eg:65760.23E-2.
Floating Point Literals in java default to double precision. To specify a float literal F or f should
Boolean Literals
The values true and false are also treated as literals in Java programming.
When we assign a value to a boolean variable, we can only use these two values.
Unlike C, we can't presume that the value of 1 is equivalent to true and 0 is equivalent to false
in Java. We have to use the values true and false to represent a Boolean value.
Eg:boolean chosen = true;
Character Literals
Characters in Java corresponds to Unicode character set.
They are 16-bit values that can be converted into integers and manipulated with the integer
Meaning
New line
Tab
Backspace
Carriage return
Form feed
Backslash
\'
\"
\ddd
\uxxxx
constant)
String Literals
13
Module1
java programming
bsc cs
String literals are specified by enclosing a sequence of characters between a pair of double
quotes.
Examples are HelloWorld, two\nlines.
The escape sequence and octal/hexadecimal notations that were defined for character literals
Arithmetic Operators
Increment & Decrement Operators
Assignment operators
Bitwise Operators
Relational Operators
Logical Operators
Arithmetic Operators
Java has five operators for basic arithmetic
Assume integer variable A holds 10 and variable B holds 20, then:
Operator
+
description
Addition - Adds values on
example
A + B will give 30
hand operand
Multiplication - Multiplies
operator
Division - Divides left hand
B / A will give 2
operand
Modulus Divides left hand
B % A will give 0
Module1
java programming
bsc cs
remainder
Increment & Decrement Operator
The increment operator increases its operand by one, The decrement operator decrement its
operand by one,
a = a + 1;
a++; or ++a;
a = a - 1;
a--; or --a;
In prefix operator precede the operand or post fix operator follow the operand.
In prefix operand incremented or decremented before the value is obtained for the use in
expression
In postfix operand the previous value is obtained for the use in expression and then the
operand is modified.
Bitwise Operator
Assume integer variable A holds 60 and variable B holds 13, then:
Truth table
A B
A|B
A&B
A^B
~A
0 0
0
1
0
1
1
Module1
java programming
bsc cs
by num
The Right Shift (arithmetic shift)
The right shift operator, >>, shifts all of the bits in a value to the right a specified
number of times. Its general form is shown here:
value >> num
Here, num specifies the number of positions to right-shift the value in value. That is, the >>
moves all of the bits in the specified value to the right the number of bit positions specified by
num.
Eg:
00100011
35
>> 2
00001000
When you are shifting right, the top (leftmost) bits exposed by the right shift are
filled in with the previous contents of the top bit. This is called sign extension and serves to
preserve the sign of negative numbers when you shift them right. For example, 8 >> 1 is 4,
which, in binary, is
Eg:
11111000
>>1
11111100
16
Module1
java programming
bsc cs
Relational Operators
Let a=10 and b=20
<=
Checks if the value of left operand is less than or equal to the value of
(A <= B) is true
Output
. a == b =false
a != b =true
a > b =false
a < b =true
b >= a =true
b <= a =false
Logical Operators
binary logical operators combine two boolean values to form a resultant boolean value.
Operator
Result
||
OR
&&
AND
A | |B
A && B
A^B
!A
17
Module1
java programming
False
False
False
True
False
False
True
True
True
True
True
True
False
False
False
True
True
False
False
True
bsc cs
True
False
True
False
Assignment Operator
The assignment operator is the single equal sign, =. The assignment operator
works in Java much as it does in any other computer language. It has this general form:
var = expression;
Here, the type of var must be compatible with the type of expression it allows you to create a
chain of assignments.
Eg:
int x, y, z;
x = y = z = 100;
This fragment sets the variables x, y, and z to 100 using a single statement. This
works because the = is an operator that yields the value of the right-hand expression. Thus,
the value of z = 100 is 100, which is then assigned to y, which in turn is assigned to x.
Shorthand assignment operators
18
Module1
java programming
bsc cs
The ? Operator
Java includes a special ternary (three-way) operator that can replace certain types of if-thenelse statements. This operator is the ?, and it works in Java much like it does in C, C++. The ?
has this general
form:
19
Module1
java programming
bsc cs
CONTROL STATEMENTS
Control statements cause the flow of execution to advance and branch based on
changes to the state of a program. Javas program control statements can be put into the
following categories: selection, iteration, and jump. Selection statements allow your
program to choose different paths of execution based upon the outcome of an expression or
the state of a variable. Iteration statements enable program execution to repeat one or more
statements (that is, iteration statements form loops). Jump statements allow your program to
execute in a nonlinear fashion.
Selection Statements
Java supports two selection statements: if and switch. These statements allow you to
control the flow of your programs execution based upon conditions known only during run
time.
if statement
The if statement is Javas conditional branch statement. It can be used to route
program execution through two different paths. Here is the general form of the if statement:
if (condition) statement1
[Else statement2;]
Here, each statement may be a single statement or a compound statement enclosed
20
Module1
java programming
bsc cs
incurly braces (that is, a block). The condition is any expression that returns a boolean value.
The else clause is optional. Here if the condition is true, then statement1 is executed.
Otherwise,statement2 (if it exists) is executed. In no case will both statements be executed.
For example, consider the following:
eg:
if(a >b)
system.out.println(a is grater) ;
else
system.out.println(b is grater) ;
Here, if a is less than b, then a is set to zero. Otherwise, b is set to zero. In no case are they
both set to zero.
Nested ifs
A nested if is an if statement that is the target of another if or else. Nested ifs are
very
common in programming. When you nest ifs, the main thing to remember is that an else
statement always refers to the nearest if statement that is within the same block as the else
and
that is not already associated with an else.
eg:
if(a>b) {
if(a>c) system.out.println(a is grater) ;
}
Else if(b>c) system.out.println(b is grater) ;
Else
system.out.println(c is grater) ;
The if-else-if Ladder
A common programming construct that is based upon a sequence of nested ifs is
the if-else-if ladder. General Format is:
if(condition1)
statementblock1;
else if(condition2)
statementblock2;
else if(condition3)
statementblock3;
...
else
statementn;
The if statements are executed from the top down. As soon as one of the
conditions controlling the if is true, the statement associated with that if is executed, and the
21
Module1
java programming
bsc cs
rest of the ladder is bypassed. If none of the conditions is true, then the final else statement
will be executed. The final else acts as a default condition; that is, if all other conditional tests
fail, then the last else statement is performed. If there is no final else and all other conditions
are false, then no action will take place.
if (avg>90)
System.out.println("a+");
else
if ((avg>80)&&(avg<=90))
System.out.println("a");
elseif((avg>70)&&(avg<=80))
System.out.println("b");
elseif((avg>60)&&(avg<=70))
System.out.println("c");
elseif((avg>50)&&(avg<=60))
System.out.println("d");
else
System.out.println("failed");
}
switch statement
The switch statement in Java provides a convenient method for branching a
program based on a number of conditions. As such, it often provides a better alternative than
a large series of if-else-if statements. Here is the general form of a switch statement:
switch (expression) {
case value1:
statement sequence1
break;
case value2:
statement sequence2
break;
...
case valueN:
statement sequenceN
break;
default:
default statement sequence
}
22
Module1
java programming
bsc cs
The expression must be of type byte, short, int, or char. Each of the values
specified in the case statements must be of a type compatible with the expression. Each
case value must be a unique literal (that is, it must be a constant, not a variable). Duplicate
case values are not allowed. In switch the value of the expression is compared with each of
the literal values in the case statements. If a match is found, the code sequence following
that case statement is executed. If none of the constants matches the value of the
expression, then the default statement is executed. However, the default statement is
optional. If no case matches and no default is present, then no further action is taken. The
break statement is used inside the switch to terminate a statement sequence. When a break
statement is encountered, execution branches to the first line of code that follows the entire
switch statement.
Eg:
switch(i) {
case 0:
System.out.println("i is zero.");
break;
case 1:
System.out.println("i is one.");
break;
case 2:
System.out.println("i is two.");
break;
case 3:
System.out.println("i is three.");
break;
default:
System.out.println("i is greater than 3.");
}
There are three important features of the switch statement to note:
The switch differs from the if in that switch can only test for equality, whereas if can
evaluate any type of Boolean expression. That is, the switch looks only for a match between
the value of the expression and one of its case constants.
No two case constants in the same switch can have identical values. Of course, a switch
statement enclosed by an outer switch can have case constants in common.
A switch statement is usually more efficient than a set of nested ifs.
Iteration Statements
Javas iteration statements are for, while, and do-while. These statements
create what we commonly call loops. As you probably know, a loop repeatedly executes the
23
Module1
java programming
bsc cs
same set of instructions until a termination condition is met. Java has a loop to fit any
programming need.
elements required to perform iteration loops, which requires
1. a control variable (or loop counter)
2. the initial value of the control variable
3. the increment (or decrement) by which the control variable is modified each time through
the loop (also known as each iteration of the loop)
4. the loop-continuation condition that determines if looping should continue.
while statement
The while loop is Javas most fundamental looping statement. It repeats a
statement or block while its controlling expression is true. Here is its general form:
while(condition)
{
// body of loop
}
The condition can be any boolean expression. The body of the loop will be
executed as long as the conditional expression is true. When condition becomes false, control
passes to the next line of code immediately following the loop. The curly braces are
unnecessary if only a single statement is being repeated.
eg
import java.util.Scanner;
class digit
{
public static void main(String args[ ])
{
Scanner input = new Scanner( System.in );
int r=0,num=0,s=0;
try
{
System.out.println("enter an integer");
num= input.nextInt();
}catch(Exception e){ }
while(num>0)
{
r=num%10;
s=s+r;
num=num/10;
24
Module1
java programming
bsc cs
}
System.out.println("s="+s);
}
}
do-while statement
If the conditional expression controlling a while loop is initially false, then the body of the loop
will not be executed at all. However, sometimes it is desirable to execute the body of a while
loop at least once, even if the conditional expression is false to begin with. In other words,
there are times when you would like to test the termination expression at the end of the loop
rather than at the beginning. Fortunately, Java supplies a loop that does just that: the dowhile. The do-while loop always executes its body at least once, because its conditional
expression is at the bottom of the loop. Its general form is:
do
{
// body of loop
}
while (condition);
Each iteration of the do-while loop first executes the body of the loop and then
evaluates the conditional expression. If this expression is true, the loop will repeat. Otherwise,
the loop terminates. As with all of Javas loops, condition must be a Boolean expression.
Example
public class DoWhileTest {
public static void main( String[] args )
{
int i = 1;
do {
System.out.printf( "%d ", i);
++i;
} while ( i <= 10 );
}
}
output:
1 2 3 4 5 6 7 8 9 10
for statement
The general form of the for statement is:
for(initialization; condition; iteration)
{
25
Module1
java programming
bsc cs
// body
}
If only one statement is being repeated, there is no need for the curly braces. In
for loop, when the loop first starts, the initialization portion of the loop is executed. Generally,
this is an expression that sets the value of the loop control variable, which acts as a counter
that controls the loop. The initialization expression is executed only once. Next, condition is
evaluated. This must be a Boolean expression. It usually tests the loop control variable
against a target value. If this expression is true, then the body of the loop is executed. If it is
false, the loop terminates. Next, the iteration portion of the loop is executed. This is usually an
expression that increments or decrements the loop control variable. The loop then iterates,
first evaluating the conditional expression, then executing the body of the loop, and then
executing the iteration expression with each pass. This process repeats until the controlling
expression is false.
public class Forex {
public static void main( String[] args )
{
for ( int i = 1; i <= 10; i++ )
System.out.printf( "%d ", i );
}
}
o/p
1 2 3 4 5 6 7 8 9 10
Declaring Loop Control Variables Inside the for Loop
Often the variable that controls a for loop is only needed for the purposes of the loop
and is not used elsewhere. In that case, it is possible to declare the variable inside the
initialization portion of the for statement.
When you declare a variable inside a for loop the scope of that variable is limited
to the for loop Outside the for loop, the variable will cease to exist. If you need to use the
loop control variable elsewhere in your program, you need to declare it outside the for loop.
Some for Loop Variations
There will be times when you will want to include more than one statement in the
initialization and iteration portions of the for loop
Eg: for(a=1, b=4; a<b; a++, b--)
In this example, the initialization portion sets the values of both a and b. The two commaseparated statements in the iteration portion are executed each time the loop repeats.
The condition controlling the for can be any Boolean expression. For example, consider
the following fragment:
26
Module1
java programming
bsc cs
for.
You can intentionally create an infinite loop(a loop that never terminates) if you leave all
three parts of the for empty.
Eg: for( ; ; )
{
// ...
}
This loop will run forever, because there is no condition under which it will terminate.
Nested Loops
Like all other programming languages, Java allows loops to be nested. The placing of one
loop inside the body of another loop is called nesting. When you "nest" two loops, the outer
loop takes control of the number of complete repetitions of the inner loop.
Eg: for (int i=1; i<=9; i++)
{
System.out.println();
for (int j=1; j<=i; j++)
{
System.out.print(j);
}
}
For each
General form
For(type itr-var : collection)statement block
itr-var specifies name of an iteration variable that will receive the elements from a collection
one at a time beginning to end.
With each iteration, the next element in the collection is retrieved and stored in itr-var
27
Module1
java programming
Class ForEach {
public static void main(String args[]) {
int nums[]={1,2,3,4,5,6,7.8.9.10};
int sum=0;
//use of for each style for to display & sum of values
bsc cs
for(int x:nums) {
System.out,println(value is+x);
sum+=x;}
system.out.prinln(summation:+sum);} }
With each pass through the loop.x is automatically given a value equal to the next element in
nums
Jump Statements
Java supports three jump statements: break, continue, and return. These statements
transfer control to another part of your program.
break statement
In Java, the break statement has three uses. First, it terminates a statement sequence in
a switch statement. Second, it can be used to exit a loop.
Using break to Exit a Loop
By using break, you can force immediate termination of a loop, bypassing the
conditional expression and remaining code in the body of the loop. When a break statement
is encountered inside a loop, the loop is terminated and program control resumes at the next
statement following the loop.
Eg: for(int i=0; i<100; i++)
{
if(i == 10) break ; // terminate loop if i is 10
System.out.println("i: " + i);
}
Here although the for loop is designed to run from 0 to 99, the break statement causes it to
terminate early, when i equals 10.When used inside a set of nested loops, the break
statement will only break out of their
innermost loop.
continue statement
Sometimes it is useful to force an early iteration of a loop. That is, you might want to
continue running the loop, but stop processing the remainder of the code in its body for this
particular iteration. This is, in effect, a goto just past the body of the loop, to the loops end.
28
Module1
java programming
bsc cs
The continue statement performs such an action. In while and do-while loops, a continue
statement causes control to be transferred directly to the conditional expression that controls
the loop. In a for loop, control goes first to the iteration portion of the for statement and then
to the conditional expression. For all three loops, any intermediate code is bypassed.
Eg:
public class ContinueTest
{ public static void main( String[] args )
{
for ( int count = 1; count <= 10; count++ )
{ if ( count == 5 ) continue;
System.out.printf( "%d ", count );
}
System.out.println( "\nUsed continue to skip printing 5" );
}
}
1 2 3 4 6 7 8 9 10
Used continue to skip printing 5
return statement
The last control statement is return. The return statement is used to explicitly
return from a method. That is, it causes program control to transfer back to the caller of the
method.
At any time in a method the return statement can be used to cause execution to
branch back to the caller of the method. Thus, the return statement immediately terminates
the method in which it is executed.
Arrays
An array is group of like typed variable that are referred to by common name.
Arrays offer a convenient means of grouping related information.
Arrays of any type can be created and may have one or more dimensions .
A specific element in an array is accessed by its index.
The first element in every array has index zero and is sometimes called the zeroth element.
Thus, the elements of array c are c[0], c[1], c[2] and so on.
An index must be a nonnegative integer. A program can use an expression as an index.
Creating arrays
There are different ways to create a single dimensional array.
We can declare one-dimensional array and directly store elements at the time of
declaration
29
Module1
java programming
bsc cs
holds that array. An array whose size is equal to the number of elements you've included will
be automatically created for you.
Another way of creating one-dimensional array is by declaring the array first and then
allocating memory by using new operator.
General form:
type var-name[ ] ;
var-name = new type[size];
here Type can be any base typei.e data type of each element. Size specifies number of
elements in the array.
30
Module1
java programming
bsc cs
Column 1
Column 2
Column 3
31
Module1
java programming
A[0]
A[0][1]
A[0][2]
A[0][3]
[0]
A[1]
A[1][1]
A[1][2]
A[1][3]
[0]
A[2]
A[2][1]
A[2][2]
A[2][3]
bsc cs
Column
index
Row
index
[0]
Example program
import java.io.*;
class matrix
{
public static void main(String args[ ])throws IOException
{
int m,n;
int a[ ][ ]=new int[5][5];
DataInputStream in=new DataInputStream(System.in);
System.out.println("enter the size of matrix");
m=Integer .parseInt(in.readLine());
n=Integer .parseInt(in.readLine());
System.out.println("enter elmnts");
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
a[i][j]=Integer.parseInt(in.readLine());
}
}
for(int i=0;i<m;i++)
{
System.out.print("\n");
for(int j=0;j<n;j++)
{
System.out.print(" "+a[i][j]);
}
}
}}
When you allocate dimensions manually, you do not need to allocate the
32
Module1
same
java programming
number
of
elements
for
each
dimension.
bsc cs
As
stated
earlier,
since
multidimensional arrays are actually arrays of arrays, the length of each array is under
your control.
Eg: int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];
It is possible to initialize multidimensional arrays. To do so, simply enclose each
dimensions initializer within its own set of curly braces.
Eg:double m[]4[] = {
{ 0,1, 2, 3 },
{ 4, 5, 6, 7 },
Class Fundamentals
Everything in OOP is considered as Classes and Object and
you wish to implement in a Java program must be encapsulated within a class. Classes
provide a convenient way for packing together a group of logically related data items and
functions that work on them
Prime importance is given to Data
A class is declared
by use of the class keyword. The general form of a class definition is shown:
class classname {
type instance-variable1;
type instance-variable2;
...
type instance-variableN;
}
type methodname1(parameter-list)
{ `
body of method
type methodname2(parameter-list)
{
33
Module1
java programming
bsc cs
body of method
}
type methodnameN(parameter-list)
body of method }
The data, or variables, defined within a class are called instance variables. They are
called instance variables because each instance of the class (that is, each object of the class)
contains its own copy of these variables. Thus, the data for one object is separate and
unique from the data for another. In most classes, the instance variables are acted upon and
accessed by the methods defined for that class.. Collectively, the methods and variables
defined within a class are called members of the class. No method definition can put
outside class.
Sample class
class rectangle
{
int length, breadth;
void getData(int x, int y)
{
length = x;
breadth = y;
}
int rectArea()
{
int area = length * breadth;
}
}
Creating Objects
Class _var is the variable name .classname is the name of class.The followed
Module1
java programming
bsc cs
r1
Eg: r1.getData(10,20);
r1.length=45;
Rectangle r2=r1;
r2
Methods in Classes
Classes usually consist of two things: instance variables and methods.
This is the general form of a method:
type name(parameter-list)
{
// body of method
}
Here type specifies the type of data returned by the method. This can be any
valid type, including class types that you create. If the method does not return a value, its
return type must be void. The name of the method is specified by name. This can be any
legal identifier other than those already used by other items within the current scope. The
parameter-list is a sequence of type and identifier pairs separated by commas. Parameters
are essentially variables that receive the value of the arguments passed to the method
when it is called. If the method has no parameters, then the parameter list will be
empty.Methods that have a return type other than void, return a value to the calling
routine using the following form of the return statement:
return
The type of data returned by the method must be compatible with the return
type specified by the method. Also the variable receiving the value returned by a method
35
Module1
must
java programming
also
be
compatible
with
the
return
bsc cs
type
specified
for
the
method
36
Module1
java programming
bsc cs
constructors
once defined, automatically called immediately after the object is created before the
Matching constructor function will invoke each time when an instance is created
if is a constructor not explicitly defines for a class, a default constructor will be created.
Once parameterized constructors are there, all object creation is required to use proper
number of parameters
Default constructor is required to use, if you want to initialize object without parameter
Class Box
{double width;
double height;
37
Module1
java programming
bsc cs
Double depth;
Box()
{widt h=10;height=10;depth=10;}
Box(double w,double h, double d)
{width=w;
Height=h;
depth=d;
}
double volume()
{return width*height*depth;
}
}
Class BoxDemo
{
public static void main(String args[])
{
double vol1,vol2;
box box1=new Box();
vol1=box1.volume();
Box box2=new Box(10,20,15);
Vol2=box2.volume();
System.out.println("Volume is " + vol1);
System.out.println("Volume is " + vol2);
}
}
this Keyword
When we use formal variables or local variables having the same name of instance
Module1
java programming
bsc cs
for eg. an object is holding some non java resource such as file handle or character
font, then we might want to make sure these resource are freed before an object is destroyed.
to handle such situations, java provides a mechanism called finalization.
To add a finalizer to a class, we need to simply define finalize() method. Inside the
finalize method we can specify those actions that must be performed before an object is
destroyed.
class
. Inside the finalize( ) method you will specify those actions that must be
on the object.
Module1
java programming
bsc cs
There are two types of nested classes: static and non-static. A static nested
class is one which has the static modifier applied. Because it is static, it must access the
members of its enclosing class through an object. That is, it cannot refer to members of
its enclosing class directly.
The most important type of nested class is the inner class. An inner class is a
non-static nested class. It has access to all of the variables and methods of its outer
class and may refer to them directly in the same way that other non-static members of
the outer class do. Thus, an inner class is fully within the scope of its enclosing class.
It is a way of logically grouping classes that are only used in one place.
It increases encapsulation.
Logical grouping of classesIf a class is useful to only one other class, then it is logical to embed it
in that class and keep the two together. Nesting such "helper classes" makes their package more
streamlined.
Increased encapsulationConsider two top-level classes, A and B, where B needs access to members
of A that would otherwise be declared private. By hiding class B within class A, A's members can be
declared private and B can access them. In addition, B itself can be hidden from the outside world.
More readable, maintainable codeNesting small classes within top-level classes places the code
closer to where it is used.
The following program illustrates a static nested class.
class Outer
{
int outer_v=10;
void test()
{
System.out.println("Outer");
}
static class Inner
{
void display()
{
40
Module1
java programming
bsc cs
41
Module1
java programming
bsc cs
inner.display();
}
}
//access protected method from other
//package
System.out.println (Though I abused"+
multiple inheritance, I still use it);
}
}//end of class Inner
void deriv()
{
Inner i = new Inner();
i.showInner();
}
42