unit1java
unit1java
Unit I
Introduction to Java Programming
Unit 1: Introduction To Java Programming
1.1 Introduction:
Java is a high-level, third generation programming language, like C, FORTRAN,
Smalltalk, Perl, and many others. .
Java language is called as an Object-Oriented Programming language .
Java is first programming language which is not attached with any particular
hardware or operating system. Program developed in Java can be executed anywhere
and on any system.
1. Object
Objects are important runtime entities in object oriented method. They may characterize a
location, a bank account, and a table of data or any entry that the program must handle.
For example:
Object: STUDENT
DATA
Name
Address
Marks
METHODS
Total()
Average()
Each object holds data and code to operate the data. Object can interact without having to
identify the details of each other‘s data or code.
2. Classes
A class is a set of objects with similar properties (attributes), common behaviour
(operations), and common link to other objects. The complete set of data and code of an object
can be made a user defined data type with the help of class.
The objects are variable of type class. A class is a collection of objects of similar type.
Classes are user defined data types and work like the build in type of the programming language.
Once the class has been defined, we can make any number of objects belonging to that class.
Each object is related with the data of type class with which they are formed.
The classification of objects into various classes is based on its properties (States) and
behaviour (methods).
For example:Vehicle
Vehicle
Car
MH-01 1234
COST=4,00 COLOUR=R
,000 ed
Fig.1.2 Representation of class
In above example, we will create an objects MH-01 1234 belonging to the class car. The objects
develop their distinctiveness from the difference in their attribute value and relationships to other
objects.
3. Data Abstraction
Data abstraction refers to the act of representing important description without including
the background details or explanations.
Classes use the concept of abstraction and are defined as a list of abstract attributes such as size,
cost and functions operate on these attributes. They summarize all the important properties of the
objects that are to be created.
Classes use the concepts of data abstraction and it is called as Abstract Data Type (ADT).
Data Encapsulation means wrapping of data and functions into a single unit (i.e. class). It
is most useful feature of class. The data is not easy to get to the outside world and only those
functions which are enclosed in the class can access it.
These functions provide the boundary between Object‘s data and program. This insulation of
data from direct access by the program is called as Data hiding.
For example:
Data, process/Functions
Information in Information out
Fig1.3: Encapsulation
5. Inheritance
Inheritance is the process by which objects of one class can get the properties of objects
of another class. Inheritance means one class of objects inherits the data and behaviours from
another class. Inheritance maintains the hierarchical classification in which a class inherits from
its parents.
Inheritance provides the important feature of OOP that is reusability. That means we can include
additional characteristics to an existing class without modification. This is possible deriving a
new class from existing one.
In other words, it is property of object-oriented systems that allow objects to be built from other
objects. Inheritance allows openly taking help of the commonality of objects when constructing
new classes. Inheritance is a relationship between classes where one class is the parent class of
another (derived) class. The derived class holds the properties and behaviour of base class in
addition to the properties and behaviour of derived class.
For Example:
Fig.1.4 Inheritance
6. Polymorphism
(Poly means - many and morph means - form). Polymorphism means the ability to take more
than one form. Polymorphism plays a main role in allocate objects having different internal
structures to share the same external interface. This means that a general class of operations may
be accessed in the same manner even though specific activities associated with each operation
may differ. Polymorphism is broadly used in implementing inheritance.
It means objects that can take on or assume many different forms. Polymorphism means that the
same operations may behave differently on different classes. Polymorphism allows us to write
generic, reusable code more easily, because we can specify general instructions and delegate the
implementation detail to the objects involved.
For Example:
In a pay roll system, manager, office staff and production worker objects all will respond to the
compute payroll message, but the real operations performed are object particular.
Fig.1.5 Polymorphism
7. Dynamic Binding
Binding refers to the linking of a procedure call to the code to be executed in response to the call.
Dynamic binding means that the code related with a given procedure call is not known until the
time of the call at run time. Dynamic binding is associated polymorphism and inheritance.
2. Platform Independent and portable : Java supports the feature portability. Java programs
can be easily moved from one computer system to another and anywhere. Changes and upgrades
in operating systems, processors and system resources will not force any alteration in Java
programs. Java certifies portability in two ways. First way is, Java compiler generates the
bytecode and that can be executed on any machine. Second way is, size of primitive data types
are machine independent.
4. Robust and secure :-Java is a most strong language which provides many securities to make
certain reliable code. It is design as garbage –collected language, which helps the programmers
virtually from all memory management problems. Java also includes the concept of exception
handling, which detain serious errors and reduces all kind of threat of crashing the system.
Security is an important feature of Java and this is the strong reason that programmer use this
language for programming on Internet. The absence of pointers in Java ensures that programs
cannot get right of entry to memory location without proper approval.
6. Simple and small :-Java is very small and simple language. Java does not use pointer and
header files, goto statements, etc. It eliminates operator overloading and multiple inheritance.
9. Dynamic and Extensible :-Java is also dynamic language. Java is capable of dynamically
linking in new class, libraries, methods and objects. Java can also establish the type of class
through the query building it possible to either dynamically link or abort the program, depending
As we know that all programming language compilers convert the source code to machine
code.Same job done by Java Compiler to run a Java program, but the difference is that Java
compiler convert the source code into Intermediate code is called as bytecode. This machine is
called the Java Virtual machine and it exits only inside the computer memory.
Following figure shows the process of compilation.
Java Object Framework act as the intermediary between the user programs and the virtual
machine which in turn act as the intermediary between the operating system and the Java Object
Framework.
b) java(Java Interpreter)
As we learn that, we can use any text editor for writing program and then save that
program with ―.java‖ extension. Java compiler convert the source code or program in bytecode
and interpreter convert ―.java‖ file in ―.class‖ file.
Syntax:
C:\java filename
If my filename is abc.java then the syntax will be
C:\java abc
class FirstProgram
{
public static void main(String args[ ])
{
System.out.println(“This is my first program”);
}
}
The file must be named - FirstProgram.java to equivalent the class name containing the main
method.
Java is case sensitive. This program defines a class called - FirstProgram.
Above explanation is about how to write program and now we have to learn where to write
program and how to compile and run the program.
For this reason, the next explanation is showing the steps.
A data type is a scheme for representing values. An example is int which is the Integer, a data
type.
Values are not just numbers, but any manner of data that a computer can process.
The data type defines the kind of data that is represented by a variable.
As with the keyword class, Java data types are case sensitive.
There are two types of data types
primitive data type
non-primitive data type
In primitive data types, there are two categories :-
Numeric means Integer, Floating points
Non-numeric means Character and Boolean
In non-primitive types, there are three categories
classes
arrays
interface
Following table shows the datatypes with their size and ranges.
1.10 Variables:
Variables are labels that express a particular position in memory and connect it with a data type.
A variable is a named memory location that may be assigned a value by your program. The value
of a variable may be changed during the execution of the program.
The first way to declare a variable: This specifies its data type, and reserves memory for it. It
assigns zero to primitive types and null to objects.
dataType variableName;
The first way to declare two variables: all of the same data type, reserves memory for each.
dataType variableNameOne, variableNameTwo;
The second way to declare two variables: both of the same data type, reserves memory, and puts
an initial value in each variable.
dataType variableNameI = initialValueI, variableNameII=initialValueII;
Variable name:
Use only the characters ‘a‘ through ‘z‘, ‘A‘ through ‘Z‘, ‘0‘ through ‘9‘, character ‘‗‘,
and character ‘$‘.
A name cannot include the space character.
Do not begin with a digit.
A name can be of any realistic length.
Upper and lower case count as different characters.
A name cannot be a reserved word (keyword).
A name must not previously be in utilized in this block of the program.
Let’s see a program that shows how a variable is declared and how it is assigned a value. In
addition, the program also illustrates some new aspects of console output. As the comments at
the top of the program state, you should call this file Example2.java.
/*
Here is another short example.
Call this file "Example2.java".
*/
class Example2
{
public static void main(String args[])
{
int num; // this declares a variable called num
num = 100; // this assigns num the value 100
System.out.println("This is num: " + num);
num = num * 2;
System.out.print("The value of num * 2 is ");
System.out.println(num);
}
}
When you run this program, you will see the following output:
Unit 1: Introduction to Java Programming Page 13
This is num: 100
The value of num * 2 is 200
The first new line in the program is shown here:
num = 100; // this assigns num the value 100 assigns to num the value 100. In Java, the
assignment operator is a single equal sign.
The next line of code outputs the value of num preceded by the string "This is num:"
System.out.println("This is num: " + num);
In this statement, the plus sign causes the value of num to be appended to the string that
precedes it, and then the resulting string is output. (Actually, num is first converted from an
integer into its string equivalent and then concatenated with the string that precedes it.
This process is described in detail later in this book.) This approach can be generalized.
Using the + operator, you can string together as many items as you want within a single println(
) statement.
The next line of code assigns num the value of num times 2. Like most other languages, Java
uses the * operator to indicate multiplication. After this line executes, num will contain the value
200.
Here are the next two lines in the program:
System.out.print("The value of num * 2 is ");
System.out.println(num);
Several new things are occurring here. First, the built-in method print( ) is used to display the
string "The value of num * 2 is ". This string is not followed by a newline. This means that when
the next output is generated, it will start on the same line. The print( ) method is just like
println( ), except that it does not output a newline character after each call. Both print( ) and
println( )
can be used to output values of any of Java's built-in types.
1.11 Constant:
Constant means fixed value which is not change at the time of execution of program. In Java,
there are two types of constant as follows:
Numeric Constants
Integer constant
Real constant
Character Constants
Character constant
String constant
Integer Constant:
b) Octal integer
It allows us any sequence of numbers or digits from 0 to 7 with leading 0 and it is called as Octal
integer.
For example:
011
00
0425
c) Hexadecimal integer
It allows the sequence which is preceded by 0X or 0x and it also allows alphabets from ‗A‘ to
‗F‘ or ‗a‘ to ‗f‘ (‗A‘ to ‗F‘ stands for the numbers ‗10‘ to ‗15‘) it is called as Hexadecimal
integer.
For example:
0x7
00X
0A2B
Real Constant
It allows us fractional data and it is also called as floating point constant.
It is used for percentage, height and so on.
For example:
0.0234
0.777
-1.23
Character Constant
It allows us single character within pair of single coute.
For example:
‘A‘
‘7‘
‘\‘
String Constant
It allows us the series of characters within pair of double coute.
For example:
“WELCOME”
“END OF PROGRAM”
“BYE …BYE”
“A”
Symbolic constant:
Syntax:
1.12 Comments:
The contents of a comment are ignored by the compiler. Instead, a comment describes or
explains the operation of the program to anyone who is reading its source code.
Java supports three styles of comments:-
1.Multiline comment:- This type of comment must begin with /* and end with */. Anything
between these two comment symbols is ignored by the compiler. As the name suggests, a
multiline comment may be several lines long.
For example the program begins with the following lines:
/*
This is a simple Java program.
Call this file "Example.java".
*/
This is a comment. In this case, the comment describes the program and reminds you that the
source file should be called Example.java.
2.Single line comment:- This is the second type of comment supported by Java. A single line
comment begins with a // and ends at the end of the line. As a general rule, programmers use
multiline comments for longer remarks and single-line comments for brief, line-by-line
descriptions.
Example of single line comment is shown here:
Wrapper class:
Each of Java's eight primitive data types has a class dedicated to it. These are known as wrapper
classes, because they "wrap" the primitive data type into an object of that class.
The wrapper classes are part of the java.lang package, which is imported by default into all Java
programs.
A wrapper class wraps (encloses) around a data type and gives it an object appearance.
Wherever, the data type is required as an object, this object can be used. Wrapper classes include
methods to unwrap the object and give back the data type.
The wrapper classes in java servers two primary purposes.
To provide mechanism to ‘wrap’ primitive values in an object so that primitives can do
activities reserved for the objects like being added to ArrayList, Hashset, HashMap etc.
collection.
To provide an assortment of utility functions for primitives like converting primitive types to
and from string objects, converting to various bases like binary, octal or hexadecimal, or
comparing various objects.
The following two statements illustrate the difference between a primitive data type and an
object of a wrapper class:
int x=25;
Integer y = new Integer(33);
The first statement declares an int variable named x and initializes it with the value 25. The
second statement instantiates an Integer object. The object is initialized with the value 33 and a
reference to the object is assigned to the object variable y.
Command line arguments are parameters that are supplied to the application program at the time
of invoking its execution. They must be supplied at the time of its execution following the file
name.
In the main () method, the args is confirmed as an array of string known as string objects. Any
argument provided in the command line at the time of program execution, are accepted to the
array args as its elements. Using index or subscripted entry can access the individual elements of
an array. The number of element in the array args can be getting with the length parameter.
For example:
class Add
{
public static void main(String args[])
{
int a=Integer.parseInt(args[0]);
int b=Integer.parseInt(args[1]);
int c=a+b;
System.out.println(“Addition is=”+c);
}
Output:
c:\javac Add.java
c:\java Add 5 2
7
A Java program is basically a set of classes. A class is defined by a set of declaration statements
and methods or functions. Most statements contain expressions, which express the actions
carried out on information or data. Smallest individual thing in a program are known as tokens.
The compiler recognizes them for building up expression and statements.
There are five types of token as follows:
Literals:
Literals in Java are a sequence of characters (digits, letters and other characters) that characterize
constant values to be stored in variables. Java language specifies five major types of literals are
as follows:
1. Integer literals
2. Floating point literals
3. Character literals
4. String literals
5. Boolean literals
Identifiers:
Identifiers are programmer-created tokens. They are used for naming classes, methods, variables,
objects, labels, packages and interfaces in a program. Java identifiers follow the following rules:
1. They can have alphabets, digits, and the underscore and dollar sign characters.
2. They must not start with a digit.
3. Uppercase and lowercase letters are individual.
4. They can be of any length.
Identifier must be meaningful, easily understandable and descriptive.
For example:
Private and local variables like “length”
Name of public methods and instance variables begin with lowercase letter like “addition”.
Keywords:
Keywords are important part of Java. Java language has reserved 50 words as keywords.
Keywords have specific meaning in Java. We cannot use them as variable, classes and method.
Following table shows keywords.
Arithmetic operators:
Arithmetic operators are used to make mathematical expressions and the working out as same in
algebra. Java provides the fundamental arithmetic operators. These can operate on built in data
type of Java.
Following table shows the details of operators.
class Avg1
{
public static void main(String args[])
{
int a=3;
int b=3;
int c=4;
int avg;
avg=a+b+c;
avg=avg/3;
System.out.println(“Avg of three numbers=”+avg);
}
}
Output:
Avg of three numbers=3
The Boolean logical operators shown here operate only on boolean operands. All of the binary
logical operators combine two boolean values to form a resultant boolean value.
Operator Result
& Logical AND
| Logical OR
^ Logical XOR (exclusive OR)
|| Short-circuit OR
&& Short-circuit AND
! Logical unary NOT
&= AND assignment
|= OR assignment
^= XOR assignment
== Equal to
!= Not equal to
?: Ternary if-then-else
class BoolLogic
{
public static void main(String args[])
{
boolean a = true;
boolean b = false;
boolean c = a | b;
boolean d = a & b;
boolean e = a ^ b;
boolean f = (!a & b) | (a & !b);
boolean g = !a;
System.out.println(" a = " + a);
System.out.println(" b = " + b);
System.out.println(" a|b = " + c);
System.out.println(" a&b = " + d);
System.out.println(" a^b = " + e);
System.out.println("!a&b|a&!b = " + f);
System.out.println(" !a = " + g);
}
}
After running this program, you will see that the same logical rules apply to Boolean values as
they did to bits. As you can see from the following output, the string representation of a Java
boolean value is one of the literal values true or false:
a = true
b = false
a|b = true
a&b = false
a^b = true
a&b|a&!b = true
Unit 1: Introduction to Java Programming Page 24
!a = false
Relational Operators:
When evaluation of two numbers is performed depending upon their relation, assured decisions
are made.
The value of relational expression is either true or false.
If A=7 and A < 10 is true while 10 < A is false.
Following table shows the details of operators.
Output:
a>b = false
a<b = true
a<=b = true
Assignment Operators:
Assignment Operators is used to assign the value of an expression to a variable and is also called
as Shorthand operators.
Variable_name binary_operator = expression
Following table show the use of assignment operators.
class Assoptr
{
public static void main (String args[])
{
int a = 10;
int b = 30;
int c = 30;
a+=1;
b-=3;
Output:
a = 11
b = 18
c = 310
Conditional Operators:
The character pair ?: is a ternary operator of Java, which is used to construct conditional
expressions of the following form:
Expression1 ? Expression3 : Expression3
The operator ? : works as follows:
Expression1 is evaluated if it is true then Expression3 is evaluated and becomes the value of the
conditional expression. If Expression1 is false then Expression3 is evaluated and its value
becomes the conditional expression.
For example:
A=3;
B=4;
C=(A<B)?A:B;
C=(3<4)?3:4;
C=4
Now the following program shows the use of operators.
class Coptr
{
public static void main (String args[])
{
int a = 10;
int b = 30;
int c;
c=(a>b)?a:b;
System.out.println("c = " +c);
c=(a<b)?a:b;
System.out.println("c = " +c);
}
}
Output:
Output:
Number is positive
The increment operator ++ adds 1 to a variable. Usually the variable is an integer type, but it can
be a floating point type. The two plus signs must not be split by any character. Usually they are
written immediately next to the variable.
Following table shows the use of operators.
class IncDecOp
{
public static void main(String args[])
{
int x=1;
int y=3;
Output:
3
4
4
1
Bit wise operator execute single bit of their operands. The bitwise logical operators are &, |, ^,
and ~.Bitwise operators are applied to each individual bit within each operand. Following table
shows bit wise operator:
Here is an example:
00101010 42
class MultByTwo
{
public static void main(String args[])
{
int i;
int num = 0xFFFFFFE;
for(i=0; i<4; i++)
{
num = num << 1;
System.out.println(num);
}
The starting value was carefully chosen so that after being shifted left 4 bit positions, it would
produce -32. As you can see, when a 1 bit is shifted into bit 31, the number is interpreted as
negative.
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.
The following code fragment shifts the value 32 to the right by two positions, resulting in a
being set to 8:
int a = 32;
a = a >> 2; // a now contains 8
When a value has bits that are "shifted off," those bits are lost. For example, the next code
fragment shifts the value 35 to the right two positions, which causes the two low order bits to be
lost, resulting again in a being set to 8.
int a = 35;
a = a >> 2; // a still contains 8
Separator:
Separators are symbols. It shows the separated code.They describe function of our code.
The evaluation process includes two left to right passes through the expression. During the first
pass, the high priority operators are applied as they are encountered.
During the second pass, the low priority operators are applied as they are encountered.
For example:
Z=A-B/3+C*3-1
Unit 1: Introduction to Java Programming Page 32
When A=10, B=13, C=3
First pass:
Z=10-(13/3) + (3*3)-1
Z=10-4+3-1
Second pass:
Z=6+3-1
Z=7
Answer is=7
Following table shows associativity of operators.
In Java, program is a set of statements and which are executed sequentially in order in which
they appear. In that statements, some calculation have need of executing with some conditions
and for that we have to provide control to that statements. In other words, Control statements are
used to provide the flow of execution with condition.
In java program, control structure is can divide in three parts:
Selection statement
Iteration statement
Jumps in statement
Selection statement :-
Selection statement is also called as Decision making statements because it provides the decision
making capabilities to the statements. In selection statement, there are two types:
if statement
switch statement
These two statements are allows you to control the flow of a program with their conditions.
if statement :- The “if statement” is also called as conditional branch statement. It is used
to program execution through two paths. The syntax of “if statement” is as follows:
Syntax:
if (condition)
{
Statement 1; Statement 2;
...
}
else
{
Statement 3;
Statement 4;
... }
Simple if statement:
Syntax:
If (condition)
{
Statement block;
}
Statement-a;
In statement block, there may be single statement or multiple statements. If the condition is true
then statement block will be executed. If the condition is false then statement block will omit and
statement-a will be executed.
import java.io.*;
class NumTest
{
public static void main (String[] args) throws IOException
{
int Result=11;
System.out.println("Number is"+Result);
if ( Result < 0 )
{
System.out.println("The number "+ Result +" is negative");
}
else
{
System.out.println("The number "+ Result +" is positive");
}
Output:
C:\MCA>java NumTest
Number is 11
The number 11 is positive
------- * ---------
Note: All conditional statements in Java require boolean values, and that's what the ==, <, >, <=,
and >= operators all return. A boolean is a value that is either true or false. If you need to set a
boolean variable in a Java program, you have to use the constants true and false. Boolean values
are no more integers than are string).
For example: write a program to check whether the number is divisible by 2 or not.
import java.io.*;
class divisorDemo
{
public static void main(String[] args)
{
int a =11;
if(a%2==0)
{
System.out.println(a +" is divisible by 2");
}
else
{
System.out.println(a+" is not divisible by 2");
}
}
}
Output:
C:\MCA>java divisorDemo
11 is not divisible by 2
Syntax:
if (condition1)
{
if(condition2)
{
Statement block1;
If the condition1 is true then it will be goes for condition2. If the condition2 is true then
statement block1 will be executed otherwise statement2 will be executed. If the condition1 is
false then statement block3 will be executed. In both cases the statement4 will always executed.
For example:Write a program to find out greatest number from three numbers.
class greatest
{
public static void main(String args[])
{
int a=10;
int b=20;
int c=3;
if(a>b)
{
if(a>c)
{
System.out.println("a is greater number");
}
else
{
System.out.println("c is greater number");
}
}
else
{
if(c>b)
{
System.out.println("c is greater number");
}
else
{
System.out.println("b is greater number");
}
Output:
C:\MCA>java greatest
b is greater number
switch statement:
In Java, switch statement check the value of given variable or statement against a list of case
values and when the match is found a statement-block of that case is executed. Switch statement
is also called as multiway decision statement.
Syntax:
import java.io.*;
class bankac
{
public static void main(String args[]) throws Exception
{
int bal=20000;
int ch=Integer.parseInt(args[0]);
System.out.println("Menu");
System.out.println("1:check balance");
System.out.println("2:withdraw amount... plz enter choice and amount");
switch(ch)
{
default:break;
}
}
}
Output:
C:\MCA>javac bankac.java
C:\MCA>java bankac 1
Menu
1:check balance
2:withdraw amount... plz enter choice and amount
3:deposit amount... plz enter choice and amount
4:exit
Balance is:20000
Menu
1:check balance
2:withdraw amount... plz enter choice and amount
3:deposit amount... plz enter choice and amount
Menu
1:check balance
2:withdraw amount... plz enter choice and amount
3:deposit amount... plz enter choice and amount
4:exit
Balance is22000
C:\MCA>java bankac 4
Menu
1:check balance
2:withdraw amount... plz enter choice and amount
3:deposit amount... plz enter choice and amount
4:exit
C:\MCA>java bankac
Iteration Statement:
The process of repeatedly executing a statements and is called as looping. The statements may be
executed multiple times (from zero to infinite number). If a loop executing continuous then it is
called as Infinite loop. Looping is also called as iterations. In Iteration statement, there are three
types of operation:
for loop
while loop
do-while loop
for loop :-
The for loop is entry controlled loop. It means that it provide a more concious loop control
structure.
Syntax:
for(initialization;condition;iteration)//iteration means increment/decrement
{
Statement block;
}
When the loop is starts, first part(i.e. initialization) is execute. It is just like a counter and
provides the initial value of loop. But the thing is, I nitialization is executed only once. The next
part( i.e. condition) is executed after the initialization. The important thing is, this part provide
For example:
import java.io.*;
class number
{
public static void main(String args[]) throws Exception
{
int i;
System.out.println("list of 1 to 10 numbers");
for(i=1;i<=10;i++)
{
System.out.println(i);
}
}
}
Output:
C:\MCA>javac number.java
C:\MCA>java number
list of 1 to 10 numbers
1
2
3
4
5
6
7
8
9
10
Here we declare i=1 and then it check the condition that if i<10 then only loop will be executed.
After first iteration the value of i will print and it will incremented by 1. Now the value of i=2
and again we have to check the condition and value of i will print and then increment I by 1 and
so on.
while loop:
The while loop is entry controlled loop statement. The condition is evaluated, if the condition is
true then the block of statements or statement block is executed otherwise the block of statement
is not executed.
While(condition)
{
Statement block;
}
import java.io.*;
class number
{
public static void main(String args[]) throws Exception
{
int i=1;
System.out.println("list of 1 to 10 numbers");
while(i<=10)
{
System.out.println(i);
i++;
}
}
}
Output:
C:\MCA>javac number.java
C:\MCA>java number
list of 1 to 10 numbers
1
2
3
4
5
6
7
8
9
10
do-while loop:
In do-while loop, first attempt of loop should be execute then it check the condition. The benefit
of do-while loop/statement is that we get entry in loop and then condition will check for very
first time. In while loop,condition will check first and if condition will not satisfied then the loop
will not execute.
In program,when we use the do-while loop, then in very first attempt, it allows us to get enter in
loop and execute that loop and then check the condition.
Following program show the use of do-while loop.
import java.io.*;
class number
{
public static void main(String args[]) throws Exception
{
int i=1;
System.out.println("list of 1 to 10 numbers");
do
{
System.out.println(i);
i++;
}while(i<=10);
}
}
Output:
list of 1 to 10 numbers
1
2
3
4
5
6
7
8
9
10
Jumps in statement:
Statements or loops perform a set of operations continually until the control variable will not
satisfy the condition. but if we want to break the loop when condition will satisfy then Java give
a permission to jump from one statement to end of loop or beginning of loop as well as jump out
Break:
In Java, the break statement has three uses.
First, as you have seen, it terminates a statement sequence in a switch statement. Second,
it can be used to exit a loop. Third, it can be used as a "civilized" form of goto.
When a break statement is encountered inside a loop, the loop is terminated and program
control resumes at the next statement following the loop.
Continue:
Continue statement is used to bring the control to the beginning of loop.
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.
Following statements shows the exiting from loop by using “break” statement.
do-while loop:
do
{
………………
………………
if(condition)
{
break;//exit from if loop and do-while loop
}
……………..
……………..
}
While(condition);
………..
………..
For loop:
for(…………)
{
……………
…………..
if(…………..)
break; ;//exit from if loop and for loop
……………
……………
}
While loop:
while(…………)
{
……………
…………..
if(…………..)
break; ;//exit from if loop and while loop
……………
……………
}
Following statements shows the continuing the loop by using “continue” statement.
do-while loop:
do
{
………………
………………
if(condition)
{
continue;//continue the do-while loop
}
……………..
……………..
}
While(condition);
………..
………..
For loop:
for(…………)
{
……………
…………..
if(…………..)
continue ;// continue the for loop
……………
……………
}
……………
…………..
While loop:
while(…………)
Labelled loop:
We can give label to a block of statements with any valid name.following example shows the use
of label, break and continue.
For example:
Import java.io.*;
class Demo
{
public static void main(String args[]) throws Exception
{
int j,i;
LOOP1: for(i=1;i<100;i++)
{
System.out.println(““);
if(i>=10)
{
break;
}
for(j=1;j<100;j++)
{
System.out.println(“$ ”);
Output:
$
$$
$$$
$$$$
$$$$$
$$$$$$
$$$$$$$
$$$$$$$$
$$$$$$$$$
End of program
1.17 Classes
Definition: A class is a collection of objects of similar type. Once a class is defined, any number
of objects can be produced which belong to that class.
Objects are instances of the Class. Classes and Objects are very much related to each other.
Without objects you can't use a class.
The general form of a class definition is shown here:
Class classname {
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list) {
// body of method
}
type methodname2(parameter-list) {
// body of method
}
// ...
type methodnameN(parameter-list) {
// body of method
}
}
class Demo
{
private int x,y,z;
public void input()
{
x=10;
y=15;
}
public void sum()
{
z=x+y;
}
public void print_data()
{
System.out.println(―Answer is =‖ +z);
}
public static void main(String args[])
{
Demo object=new Demo();
object.input();
object.sum();
object.print_data();
}
In program,
Demo object=new Demo();
object.input();
object.sum();
object.print_data();
class Demo
{
private int x,y,z;
public void input()
{
x=10;
y=15;
}
public void sum()
{
z=x+y;
}
public void print_data()
{
System.out.println(―Answer is =‖ +z);
}
}
class SumDemo
{
public static void main(String args[])
{
Demo object=new Demo();
object.input();
object.sum();
object.print_data();
}
}
class DotDemo
{
int x,y,z;
public void sum()
{
z=x+y;
}
public void show()
{
System.out.println("The Answer is "+z);
}
}
class Demo1
{
public static void main(String args[])
{
DotDemo object=new DotDemo();
DotDemo object2=new DotDemo();
object.x=10;
object.y=15;
object2.x=5;
object2.y=10;
object.sum();
object.show();
object2.sum();
object2.show();
}
}
output:
C:\cc>javac Demo1.java
C:\cc>java Demo1
The Answer is 25
The Answer is 15
Instance Variable
All variables are also known as instance variable. This is because of the fact that each instance
or object has its own copy of values for the variables. Hence other use of the ―dot” operator is
to initialize the value of variable for that instance.
class prg
{
int n,n2,sum;
public void take(int x,int y)
{
n=x;
n2=y;
}
public void sum()
{
sum=n+n2;
}
public void print()
{
System.out.println("The Sum is"+sum);
}
}
class prg1
{
public static void main(String args[])
{
prg obj=new prg();
obj.take(10,15);
obj.sum();
In Java it is possible to define two or more methods within the same class that share the
same name, as long as their parameter declarations are different. When this is the case,
the methods are said to be overloaded, and the process is referred to as method
overloading.
Method overloading is one of the ways that Java implements polymorphism
Method overloading means method name will be same but each method should be
different parameter list.
When an overloaded method is invoked, Java uses the type and/or number of arguments
as its guide to determine which version of the overloaded method to actually call. Thus,
overloaded methods must differ in the type and/or number of their parameters.
When Java encounters a call to an overloaded method, it simply executes the version of
the method whose parameters match the arguments used in the call.
class OverloadDemo
{
void test()
{
System.out.println("No parameters");
}
// Overload test for one integer parameter.
void test(int a)
{
System.out.println("a: " + a);
}
// Overload test for two integer parameters.
void test(int a, int b)
{
System.out.println("a and b: " + a + " " + b);
}
// overload test for a double parameter
double test(double a)
{
System.out.println("double a: " + a);
return a*a;
}
}
test( ) is overloaded four times. The first version takes no parameters, the second takes one
integer parameter, the third takes two integer parameters, and the fourth takes one double
parameter. The fact that the fourth version of test( ) also returns a value is of no consequence
relative to overloading, since return types do not play a role in overload resolution.
class para123
{
int n,n2,sum,mul;
public void take(int x,int y)
{
n=x;
n2=y;
}
public void sum()
{
sum=n+n2;
System.out.println("The Sum is"+sum);
}
public void take2(para123 obj)
{
n=obj.n;
Output:
C:\cc>javac DemoPara.java
C:\cc>java DemoPara
The Sum is10
Product is21
We have defined a method ―take2” that declares an object named obj as parameter. We
have passed ob to our method. The method ―take2‖ automatically gets 3,7 as values for n
and n2.
1.21 Constructors:-
Java allows objects to initialize themselves when they are created. This automatic
initialization is performed through the use of a constructor.
A constructor initializes an object immediately upon creation. It has the same name as the
class in which it resides and is syntactically similar to a method. Once defined, the
constructor is automatically called immediately after the object is created, before the new
operator completes.
Constructors look a little strange because they have no return type, not even void. This is
because the implicit return type of a class' constructor is the class type itself.
It is the constructor's job to initialize the internal state of an object so that the code
creating an instance will have a fully initialized, usable object immediately.
In a class hierarchy, constructors are called in order of derivation, from superclass to
subclass.Further, since super( ) must be the first statement executed in a subclass'
constructor, this order is the same whether or not super( ) is used.
If super( ) is not used, then the default or parameterless constructor of each superclass
will be executed. The following program illustrates when constructors are executed:
Both mybox1 and mybox2 were initialized by the Box( ) constructor when they were created.
Since the constructor gives all boxes the same dimensions, 10 by 10 by 10, both mybox1 and
mybox2 will have the same volume.
Parameterized constructor add parameters to the constructor. For example, the following version
of Box defines a parameterized constructor which sets the dimensions of a box as specified by
those parameters.
/* Here, Box uses a parameterized constructor to initialize the dimensions of a box.
class Box
{
double width;
double height;
double depth;
// This is the constructor for Box.
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
// compute and return volume
double volume()
{
return width * height * depth;
}
}
class BoxDemo7
{
public static void main(String args[])
{
// declare, allocate, and initialize Box objects
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
This version of Box( ) operates exactly like the earlier version. The use of this is redundant, but
perfectly correct. Inside Box( ), this will always refer to the invoking object.
Pass by Value-When we pass a data type like int, float or any other datatype to a method or
some constant values like(15,10). They are all passed by value. A copy of variable‘s value is
passed to the receiving method and hence any changes made to the values do not affect the actual
variables.
class Demopbv
{
int n,n2;
public void get(int x,int y)
{
x=x*x; //Changing the values of passed arguments
y=y*y; //Changing the values of passed arguments
}
}
Output:
C:\cc>javac Demo345.java
C:\cc>java Demo345
Initial Values of a & b 1 2
Final Values 1 2
Pass by Reference
Objects are always passed by reference. When we pass a value by reference, the reference
or the memory address of the variables is passed. Thus any changes made to the argument
causes a change in the values which we pass.
Demonstrating Pass by Reference---
class pass_by_ref
{
int n,n2;
public void get(int a,int b)
{
n=a;
n2=b;
}
public void doubleit(pass_by_ref temp)
{
temp.n=temp.n*2;
temp.n2=temp.n2*2;
}
}
class apply7
{
public static void main(String args[])
{
int x=5,y=10;
Definition: An abstract class is a class that is declared as abstract. It may or may not include
abstract methods. Abstract classes cannot be instantiated, but they can be subclass.
An abstract method is a method that is declared without an implementation (without braces, and
followed by a semicolon), like this:
If a class includes abstract methods, the class itself must be declared abstract, as in:
When an abstract class is subclass, the subclass usually provides implementations for all of the
abstract methods in its parent class. However, if it does not, the subclass must also be declared
abstract.
Abstract classes are those which can be used for creation of objects. However their methods and
constructors can be used by the child or extended class.
The need for abstract classes is that you can generalize the super class from which child classes
can share its methods. The subclass of an abstract class which can create an object is called as
"concrete class".
For example:
Abstract class A
{
abstract void method1();
void method2()
{
class B extends A
{
void method1()
{
System.out.println("B is execution of method1");
}
}
class demo
{
public static void main(String arg[])
{
B b=new B();
b.method1();
b.method2();
}
}
class data
{
int l;
int b;
data(int c, int d)
{
l=c;
b=d;
}
int area( )
{
return(l*b);
class dataDemo
{
public static void main(String args[])
{
data2 d1=new data2(10,20,30);
int area1=d1.area(); //superclass method
int volume1=d1.volume( );// subclass method
System.out.println("Area="+area1);
System.out.println("Volume="+volume1);
}
}
Output:
C:\cc>javac dataDemo.java
C:\cc>java dataDemo
Area=200
Volume=6000
"Is A" - is a subclass of a superclass (ex: extends) "Has A" - has a reference to (ex: variable, ref
to object).
Classes and packages are both means of encapsulating and containing the name space scope of
and methods. Packages act as containers for classes and other subordinate packages. Classes act
as containers for data and code. The class is Java's smallest unit of abstraction. Because of the
interplay between classes and packages,Java addresses four categories of visibility for class
members:
Subclasses in the same package
Class has only two possible access levels: default and public. When a class is declared as public,
it is accessible by any other code. If a class has default access, then it can only be accessed by
other code
within its same package.
If you need to do computation in order to initialize your static variables, you can declare a static
block which gets executed exactly once, when the class is first loaded. The following example
shows a class that has a static method, some static variables, and a static initialization block:
class UseStatic
{
static int a = 3;
static int b;
static void meth(int x)
{
System.out.println("x = " + x);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
static
{
System.out.println("Static block initialized.");
b = a * 4;
}
public static void main(String args[])
{
meth(42);
}
}
As soon as the UseStatic class is loaded, all of the static statements are run. First, a is set to 3,
then the static block executes (printing a message), and finally, b is initialized to a * 4 or 12.
Then main( ) is called, which calls meth( ), passing 42 to x. The three println( ) statements refer
to the two static variables a and b, as well as to the local variable x.
Note: It is illegal to refer to any instance variables inside of a static method.
A variable can be declared as final. Doing so prevents its contents from being modified. This
means that you must initialize a final variable when it is declared. (In this usage, final is similar
to const in C/C++.) For example:
final int FILE_NEW = 1;
final int FILE_OPEN = 2;
final int FILE_SAVE = 3;
final int FILE_SAVEAS = 4;
final int FILE_QUIT = 5;
Subsequent parts of your program can now use FILE_OPEN, etc., as if they were
constants, without fear that a value has been changed.
It is a common coding convention to choose all uppercase identifiers for final variables.
Variables declared as final do not occupy memory on a per-instance basis. Thus, a final
variable is essentially a constant.
The keyword final can also be applied to methods, but its meaning is substantially
different than when it is applied to variables.
1.28 Arrays:-
An important point can be made about arrays: they are implemented as objects. the size of an
array-that is, the number of elements that an array can hold-is found in its length instance
variable. All arrays have this variable, and it will always hold the size of the array.There are two
types of array:-
A one-dimensional array is, essentially, a list of like-typed variables. To create an array, you first
must create an array variable of the desired type. The general form of a onedimensional array
declaration is
type var-name[ ];
Here, type declares the base type of the array. The base type determines the data type of
each element that comprises the array.
Thus, the base type for the array determines what type of data the array will hold. For example,
the following declares an array named month_days with the type "array of int":
int month_days[];
2.Multidimensional array:-
This allocates a 4 by 5 array and assigns it to twoD. Internally this matrix is implemented as an
array of arrays of int.
When you allocate memory for a multidimensional array, you need only specify the memory for
the first (leftmost) dimension.
You can allocate the remaining dimensions separately. For example, this following code
allocates memory for the first dimension of twoD when it is declared. It allocates the second
dimension manually.
class Length
{
public static void main(String args[])
{
int a1[] = new int[10];
int a2[] = {3, 5, 7, 1, 8, 99, 44, -10};
int a3[] = {4, 3, 2, 1};
System.out.println("length of a1 is " + a1.length);
System.out.println("length of a2 is " + a2.length);
System.out.println("length of a3 is " + a3.length);
The value of length has nothing to do with the number of elements that are actually in use. It
only reflects the number of elements that the array is designed to hold.
1.29 Nested and Inner Classes
It is possible to define a class within another class; such classes are known as nested
classes.
The scope of a nested class is bounded by the scope of its enclosing class. Thus, if class B
is defined within class A, then B is known to A, but not outside of A.
A nested class has access to the members, including private members, of the class in
which it is nested. However, the enclosing class does not have access to the members of
the nested class.
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. Because of this restriction, static nested classes are seldom used.
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.
The following program illustrates how to define and use an inner class.
The class named Outer has one instance variable named outer_x, one instance method named
test( ),
and defines one inner class called Inner.
class InnerClassDemo
{
public static void main(String args[])
{
Outer outer = new Outer();
}
}
In the program, an inner class named Inner is defined within the scope of class Outer.
Therefore, any code in class Inner can directly access the variable outer_x.
An instance method named display( ) is defined inside Inner. This method displays
outer_x on the standard output stream.
The main( ) method of InnerClassDemo creates an instance of class Outer and invokes
its test() method. That method creates an instance of class Inner and the display( )
method is called.
It is important to realize that class Inner is known only within the scope of class Outer.
The Java compiler generates an error message if any code outside of class Outer
attempts to instantiate class Inner.
Generalizing, a nested class is no different than anyother program element: it is known
only within its enclosing scope.
1.30 Recursion
Java supports recursion. Recursion is the process of defining something in terms of itself.
As it relates to Java programming, recursion is the attribute that allows a method to call
itself. A method that calls itself is said to be recursive.
The classic example of recursion is the computation of the factorial of a number. The
factorial of a number N is the product of all the whole numbers between 1 and N. For
example, 3 factorial is 1 × 2 × 3, or 6. Here is how a factorial can be computed by use of
a recursive method:
class Recursion
{
public static void main(String args[])
{
Factorial f = new Factorial();
System.out.println("Factorial of 3 is " + f.fact(3));
System.out.println("Factorial of 4 is " + f.fact(4));
System.out.println("Factorial of 5 is " + f.fact(5));
}
}