Java Unit-1
Java Unit-1
1,0
Machine language
Assembly Language
Procedure-Oriented
Object-Oriented Programming
C is a structured programming became very popular and was the main technique of the
.
1980s. Structured programming was a powerful tool that enabled programmers to write moderately
complex programs fairly easily. However, as the programs grew later, even the structured approach
failed to show the desired results in terms of bug-free, easy to maintain and reusable programs.
Object oriented programming (OOP) is an approach to program organisation and development that
attempts to eliminate some of the drawbacks in pop and introducing the new concepts. It is a new way
of organizing and developing programs.
Procedure Oriented Programming (POP):-
Conventional programming, using high level languages such as COBOL, FORTRAN and C is
commonly known as procedure-oriented programming. In the procedure-oriented approach, the
problem is viewed as a sequence of things to be done such as reading, calculating and printing.
A number of functions are written to accomplish these tasks.
The primary focus is on functions, the below figure explains the technique of hierarchical
decomposition has been used to specifies the task to be completed for solving a problem.
Main Program
Function-4 Function-5
Method
Metho
Dat
a
Metho Metho
d d
Person
Object
Name
Data
BasicPay
Salary()
Methods
Tax()
When a program is executed the objects interact by sending message to one another. Each object
contains data and code to manipulate the data. A class is thus a collection of objects of similar
type. For example mango, apple, orange are the members of the class fruit. Classes are user
defined data types and behave like the built-in types of programming language.
Fruit *mango
Will create an object mango belonging to the class fruit.
Abstraction refers to the act of representing essential features 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, weight, cost and methods that operate on these methods.
3) Inheritance:- Inheritance is the process by which objects of one class acquire the
properties of objects of another class. Inheritance supports the concepts of hierarchical
classification.
For example the bird robin is a part of the class flying bird, which is again a part of the class bird.
As illustrated in the below figure.
Bird
Attribut
es:
Feather
s Lay
Flying
N
Bird
Attributes on
: Fly
ing
Bir
d
Attr
Robin Swallo Pengui Kiwi
w n
Attributes Attributes Attributes Attributes
: : : :
Shape
Draw()
Fig d. Polymorphism
In the above figure, a single function name can be used to handle different number and different types
of arguments. Polymorphism plays an important role in allowing objects having different internal
structure to share the same external interfaces.
5. 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 the code associated with a given procedure call, it will be executed until the
time of the call at run time. It is associated with polymorphism and inheritance.
6. Message Communication:
An oop consists of a set of objects that communicate with each other. The process of programming
in an object oriented language.
Therefore, involves the following basic steps:
Obj
ect1
Obj
Obj ect2
ect5
Obj Obj
ect4 ect3
A message for an object is request for execution of a procedure and therefore we will invoke a
method in the receiving object that generates the desired result as shown in the below figure.
Method()
What is java:-
Java is a general purpose; object oriented programming language developed by sun Microsystems
of USA in 1991. Originally called Oak by James Gosling, one of the inventors of the language.
Java was designed for the development of software for consumer electronic devices like TVs,
VCRs, toasters and such other electronic machines.
The goal of the java team to develop the language is a simple, portable and highly reliable. The
Patrick Newton discovered that the existing languages like c and c++ had limitations in terms of
both reliability and portability. However, they modeled their new language java on c and c++ but
removed a number of features of c and c++ that were considered as sources of problems and thus
made java a really simple, reliable, portable and powerful language.
Java Milestones:
Year Development
1990 Sun Microsystems decided to develop special software
that could be used to manipulate consumer electronic devices.
1991 The team announced a new language named “oak”
1992 using hand-held devices with a tiny touch-sensitive screen.
1993 The World Wide Web
1994 The team developed a web browser called “HotJava” 1995
Oak was renamed “java”.
1996 Sun Releases java development kit 1.0
1997 Sun Releases java development kit 1.1(JDK1.1)
1998 Sun Releases Software Development kit (SDK1.2)
1999 Sun Releases J2SE (Java 2 Standard Enterprise) and J2EE (Java 2
Enterprise Edition).
2000 J2SE with SDK 1.3 was released.
2002 J2SE with SDK 1.4 was released.
2004 J2SE with JDK 5.0 was released. This is known as J2SE5.0
Features of java:-
Sun Microsystems officially describes java with the following features.
i) Compiled and interpreted
ii) Platform independent and portable
iii) Object oriented
iv) Robust and Secure
v) Distributed
vi) Simple, small and familiar
vii) Multithreaded and interactive
viii) High performance
ix) Dynamic and Extensible
x) JDBC RowSet
i) Compiled and Interpreted:
Usually a computer language is either compiled or interpreted. Java combines both these
approaches. Thus making a two-stage system. First java compiler translates source code into byte
code instructions. Byte codes are not machine instructions and therefore in the second stage java
interpreter generates machine code that can be directly executed by the machine that is running
the java program. We can say that java is both compiled and interpreted language.
ii) Platform Independent and Portable:
java is a platform independent and portable language. Java programs can be easily moved from
one computer system to another, anywhere and anytime. Changes and upgrades in operating
systems, processors and system resources will not force any changes in java programs.
Java ensures portability in two ways. First java compiler generates byte code instructions
that can be implemented on any machine. Secondly the sizes of the primitive data types are
machine independent.
iii) Object oriented:
Java is a true object-oriented language. Almost everything in java is
an object. All program code and data reside within objects and classes. The object model in java
is simple and easy to extend.
iv) Robust and Secure:
Java is a robust and secured language. It provides many safe guards
to ensure reliable code. It has strict compile time and run time checking for data types. It is designed
as a garbage-collected relieving the programmers virtually all memory management problems.
Java also incorporates the concept of exception handling mechanism which captures the
error and eliminated any risk of crashing the system.
Security becomes an important issues for a language that is used for programming on internet.
Threat of viruses and abuse of resources are everywhere. Java was provided the security from
viruses.
v) Distributed:
Java is designed as a distributed language for crating applications on networks. It has the ability to
share both data and programs. Java applications can open and access remote objects and internet
has easily in a local system. This enables multiple programmers at multiple remote locations to
collaborate and work together on a single project.
vi) Simple, Small and familiar:
Java is a small and simple language. Many features of c and c++ that are either redundant or
sources of unreliable code are not a part of java. For example java does not use pointers, pre-
processor header files, goto statement and many others. It also eliminates operator overloading
and multiple inheritance.
Familiarity is another striking feature of java. Java uses many constructs of c and c++ and
therefore java code is same as c++ code. In fact java is a simplified version of c++.
C++
java
c
Java
Source
code
Java
Compiler
Java Java
Enable Interprete
Output Outpu
t
Fig.a) Two ways of using java
Applets are small java programs developed for internet applications. An applet located on a distant
computer (server) can be downloaded via internet and executed on a local computer using java
enabled browser.
Standalone programs can read and write files and perform certain operations that applets cannot
do. An applet can only run with in a web browser.
Simple java program:-
The best way to learn a new language is to write a few simple example programs and execute
them. We begin with a many simple program that prints a line of text as output.
Example:-
class sampleone {
public static void main(String args[]) { System.out.println(“java is
better than c++”);
}
}
Class declaration:
The first line “class sampleone” declares a class which is an object oriented construct. As stated
earlier java is a true object oriented programming and therefore everything must be placed inside
a class. Class is a keyword and declares that a new class definition follows. Sampleone is a java
identifier that specifies the name of the class to be defined. A class name is same as the variable
name.
Opening Braces:
Every class definitions in java begins with an opening brace “{“ and ends with a matching closing
brace “}”. This is similar to c++ class construct.
The Main Line:
The third line
public static void main(String args[])
defines a method name main. Conceptually this is similar to the main() function in c and c++.
Every java application program must include the main method. This is the starting point for the
interpreter to begin the execution of the program. A java application can have many number of
classes but only one of them must include the main method.
Note: Java applets will not use the main method at all.
The main line contains a number of keywords public, static and void.
Public:
The keyword public is an access Specifier that declares the main method as unprotected and
therefore making it accessible to all other classes.
Static:
The main must always be declared as static since the interpreter uses this method before any
objects are created.
Void:
The type modifier void states that the main method does not return any value but simply prints
some text to the screen.
String args[]:
Here, String args[] declares a parameter named args, which contains an array of objects of the class
type String.
The Output Line:
The only executable statement in the program is
System.out.println(“java is better than c++.”);
This is similar to the printf() statement of c or cout<<construct of c++. Since java is a true object
oriented language, every method must be part of an object. The println() method is a member of
the out object, which is a static data member of System class. This line prints the string. Java is
better than c++.
Java program structure:-
A java program may contain many classes of which only one class defines a main
method. Classes contain data members and methods that operate on the data
members of the class. Methods may contain data type declarations and executable
statements. To write a, java program we first define classes and then put them
together. A java program may contain one or more sections as shown in the below
figure.
Documentation Section Suggested
Package Statement Optional
Import Statement Optional
Interface Statement Optional
Class Definition Optional
Java Tokens:-
A java program is basically a collection of classes. A class is defined as a set of declaration
statements and methods containing executable statements. Most statements contain expressions
which describes the actions carried out on data. The smallest individual units in a program are
known as tokens. The compiler recognizes them for building up expressions and statements.
Tokens
Variable Section
Declaration
Statement
Expressions
& statements
Tokens
Method2
Java Compiler
Byte code
Operating System
Compiler Interpreter
Use
r
Fig(c): Layers of Interaction for java program.
Constants in Java:-Constants in java refers to fixed value that does not change during the
execution of a java program. Java supports several types of constants as shown in the below figure.
Java Constants
Mantissa e exponent
The mantissa is either a real number expressed in decimal notation or an integer. The exponent is
an integer with an optional plus or minus sign.
Single character constants:-
A character, number and symbol are enclosed within a single quotation marks are known as single
character constant.
Examples of single character constants are „G‟,‟K‟,‟1‟,‟6‟,‟;‟,‟@‟,etc.
String constants:-
A group of characters are enclosed within a double quotation marks are known as the string
constant.
Examples of string constants are “suresh”,”163”,”INDIA”,etc.
Backslash character constants:-
Java supports some special backslash character constants that are used in output methods. For
example the symbol „\n‟ stands for new line character. A list of such back slash character
constants is given in below table.
Constants Meaning
‘\n’ newline
‘\\’ backslash
Primitive Non-Primitive
Floating point
float double
Variables are separated by commas. A declaration statement must end with a semicolon (;).
Some valid declarations are: int
count;
float x,y;
double pi;
byte b;
char c1,c2,c3;
Length=3;
Height=5;
Gender=‟F‟;
We can also string assignment expression as shown below.
X=Y=Z=6;
It is also possible to assign a value to its variable at the time of its declaration. This takes
the form.
For example:
int a=6; long
L=500;
float bc=0.52; char
gender=‟F‟;
The process of giving initial values to variables is known as the initialization.
//demonstrate for variable initialization import java.io.*;
class assignment
{
public static void main(String k[])
{
byte b=10; //variable initialization short s=125;
int i=100;
long l=12345L; float f=12.56F;
double d=12.56;
System.out.println(“Varible initialization is:”);
System.out.println(“b:”+b+”s:”+s+”i:”+i+”l:”+l+”f:”+f+”d:”+d);
Read Statement:-
We may also give values to variables interactively through the keyboard using the “nextType()”
method.
//demonstrate for giving the values to variable from the keyboard.
import java.io.*;
import java.util.Scanner; class keyboard
{
public static void main(String k[])
{
Scanner obj=new Scanner(System.in);
byte b; //variable declaration
short s;
int i;
long l;
float f;
double d;
System.out.println(“Enter byte value:”);
b=obj.nextByte();
System.out.println(“Enter short value:”);
s=obj.nextShort();
System.out.println(“Enter int value:”);
i=obj.nextInt();
System.out.println(“Enter Long value:”);
l=obj.nextLong();
System.out.println(“Enter Float value:”);
f=obj.nextFloat();
System.out.println(“Enter Double value:”);
d=obj.nextDouble();
System.out.println(“b:”+b+”s:”+s+”i:”+i+”l:”+l+”f:”+f+”d:”+d);
}
}
Java Variables:-
Variable is name of reserved area allocated in memory. The value of a variable can change its
value in the execution time. Java variables are classified into three types:
1. Local Variables: A variable which is declared inside the method is called local variable.
2. Class Variables (Static Variables): Class variables also known as static variables are
declared with the static keyword in a class, but outside a method, constructor or a block.
3. Instance Variables (Non-static Variables): A variable which is declared inside the class but
outside the method, is called instance variable. It is not declared as static.
Symbolic Constants:-
We often use certain unique constants in a program. These constants may appear repeatedly in a
number of places in the program. One example of such constant is 3.142, representing the
mathematical value of the constant “pi”. Another example is the total number of students whose
mark sheets are analyzed by a test analysis program. The number of students says 50 may be used
for calculating the class total, class average, standard deviation etc.
A symbolic constant is declared as follows:
Type Casting:-
To convert the one type variable into another type of variable is called as type casting. We often
encountered situations where there is a need to store a value of one type into a variable of another
type.
In such situations we must cast the value to be stored by proceeding it with the type name in
parenthesis.
Java supports the two types of casting. They are
i) implicit or automatic or narrowing type casting
ii) explicit or winding type casting
i) implicit or automatic or narrowing type casting:-
To convert the small type into largest type is called as implicit or automatic or narrowing type
casting. Java does the conversion of the assigned value automatically this is known as automatic
type conversion. Automatic type conversion is possible only if the destination type has enough
precision to store the source value.
For example „int‟ is large enough to hold a byte value.
byte b=100;
int i=b; //automatic type conversion long
l=i;
float f=l;
double d=f;
ii) Explicit or winding type casting:-
To convert largest type into smallest type is called as Explicit or winding type casting.
The syntax is:
type variable1=(type)variable2;
The process of converting one data type to another data type is called as type casting.
Example:-
double d=100.501;
float f=(float)d;
long l=(long)f;
int i=(int)l;
byte b=(int)i;
Casting into a smaller type may result in a loss of data.
The below table shows which are guarantee to result in no loss of information.
Casts those results in no loss of information:-
From To
byte short, char, int, long, float, double.
Short int, long, float,double.
Char int, long, float,double
int long, float, double
long float,double
float double
import java.io.*;
class typecasting{
public static void main(String
k[]){ byte b=75;
int a=b; //automatic type casting
double d=100.501;
float f=(float)d; short
s=(short)f;
System.out.println(“b:”+b+””+”a:”+a+””+”d:”+d+””+”f:”+f+””+”s:”+s);
}}
Q7) Explain getting values of variables?
A computer program is written to manipulate a given set of data and to display or print the results.
Java supports two output methods that can be used to send the results on the screen.
* Print() method // print and wait
* Println() method //print a line and move to next line.
The print() method sends information into a buffer. This buffer is not flushed until a new line
character is sent. The print() method prints output on one line until a new line character is
encounter able.
For example the statements
System.out.print(“hello”);
System.out.print(“java!”);
Will display the words hellojava! On one line and waits for displaying further information
on the same line.
The println() method takes the information provided and displays it on a line followed by a
line feed.
This means that the statements
System.out.println(“hello”);
System.out.println(“java”);
Will produce the following output Hello
Java!
Operators and Expressions
An operator is a symbol that tells to the computer to perform mathematical or logical
expressions.
An operator is a symbol that is used for to operate the two operands. For example we can take an
expression a+b.
Where „a‟ and „b‟ are the two operands And „+‟ is
an operator.
Java is a rich set in operators. Java supports a various types of operators. They are
i) Arithmetical operators
ii) Relational operators
iii) Logical operators
iv) Bitwise operators
v) Assignment operators
vi) Increment and decrement operators
vii) Conditional operator
viii) Special operators
i) Arithmetical operators:-
Arithmetical operators to perform the arithmetical calculations such as addition, subtraction,
multiplication, division and modulo division.
Arithmetical operators are the +,-,*,/ and %. The below table explains the arithmetical operators.
+ Addition 10+20 30
_ Subtraction 20-10 10
* Multiplication 10*20 200
/ Division 10/2 5
% Modulo Division 10%2 0
Note:-
The division operator(/) returns the quotient value and modulo division returns the
remainder value.
Arithmetical operators are the three types namely
a) Integer arithmetic
b) Real arithmetic
c) Mixed mode arithmetic
Integer arithmetic operators both operands are the integer values. The result will produce is an
integer value.
Example:- 12+13;
Real arithmetic operators are the both operands are floating point values. The result will produce on
real values.
Example:- 14.13+0.23;
Mixed mode arithmetic operators are the one value is integer and another one is the real value the
result will produce real value.
Example:- 9.1+46;
//demonstrate for arithmetical operators
class arithmetical
{
int a=10+20;
int b=15-10;
int c=a*b;
doule d=12.50;
double e=d+c;
int f=a/b;
int g=a%b;
System.out.println(“a=”+a);
System.out.println(“b=”+b);
System.out.println(“c=”+c);
System.out.println(“d=”+d);
System.out.println(“e=”+e);
System.out.println(“f=”+f);
System.out.println(“g=”+g);
}
}
ii) Relational Operators:-
Relational operators compare the two values depending on their relationship. If their relationship
is true then the return value is „true‟. If their relationship is false then the return value is „false‟. The
relational operators are <,>,<=,>=,== and !=. The below table explains the relational operators.
|| Logical OR (10<20)||(10>30) 1
The logical Boolean operators &&,|| are used when we want to combine two or more relations.
The logical ! operator inverts the Boolean state: ! true= false and ! false=true. The following
table shows the effect of each logical operation.
A B A&&B A||B
T T T T
T F F T
F T F T
F F F F
The logical AND (&&) operator returns the true when both expressions are true, otherwise false.
The logical OR (||) operator returns the false when both expressions are false, otherwise true.
The logical NOT (!) operator is reverse the given expression.
//demonstrate for the logical operators
class logical
{
public static void main(String k[])
{
int a=10,b=20,c=30;
System.out.println(“The Logical Operators are:”);
System.out.println(“Logical AND=”+(a<b)&&(a<c));
System.out.println(“Logical OR=”+(a<b)||(a>c));
System.out.println(“Logical AND=”+(!(a<b)));
}
}
iv) Bitwise Operators:-
The bitwise operators to manipulate the data in a bit level. Java defines several bitwise
operators which can be applied to the integer types long, int, short, char and byte.
These operators act upon the individual bits of their operands.
Operator Meaning
In the following table, operators with the highest precedence appear at the top of the table;
those with the lowest appear at the bottom. Within an expression, higher precedence operators will
be evaluated first.
Entry
Test True
Condition
False
Statement-block
Statement-X
• If the test expression is true then the true block statement is executed. Otherwise
the false block statements are executed.
• In either case, either true block or false block will be executed, not both.
• In both the cases the control is transferred subsequently to the statement-x,
• The below diagram explains the if - else statement.
Entry
Statement-X
if(testcondition-1)
{
if(testcondition-2)
{
Statement-1;
}
else
{
Statement-2;
}
}
else
{
Statement-3;
}
Statement-X
If a test condition-1 is false then the statement-3 will be executed otherwise it continues to
perform second test.If condition-2 is true then the statement-1 will be executed otherwise
the statement-2 will be executed and then the control is transferred to the statement-x.
• The below diagram explains the nested if-else statement
Entry
False True
Test
Condition-1?
False True
Test
Statement-3 Condition-2?
Statement-2 Statement-1
Statement-X
if (condition1)
{
Statement-1;
}
else if(condition2)
{
Statement-2;
}
else if (condition 3)
{
Statement-3;
}
else if (condition n)
{
Statement-n;
}
else
{
default –statement;
}
Statement - x;
This construct is known as the else if ladder. The conditions are evaluated from the top down
words.
• As soon as the true conditions are found, the statement associated with it is executed and
the control is transferred to the statement – x.
• When all the n-conditions become false then the final else containing default statement
will be executed.
• The below figure shows the logic of execution of else – if ladder statement.
F
Con
-
1
T F
Con
-
Statement-1 2
Statement-2 T Con F
-
3
Statement-
3 T F
Con
-
n
Statement-n Default-
statement
Statement-x
Entry
Switch
Expressio
n
Expression=Value1 Block-1
Expression=Value2 Block-2
Statement-X
Entry
False
Fig(a) Entry Controlled Loop Fig(b) Exit Controlled Loop.
• A looping process in general would include the following three steps.
i. Initializing the variables
ii. Test the condition for execution
iii. Increment or decrement
• The java language provides for three constructs for performing loop operations.
They are
➢ While loop
➢ Do-while loop
➢ For-loop
While loop:-
• The while loop is an entry controlled loop statement.
• The while loop is java most fundamental looping statement.
• It repeats a statements or block while its controlling expression is true
• The general form of while is
Initialization;
While (test condition)
{
Body of the loop
}
• The condition may be any Boolean expression. The body of the loop will be executed as
long as the condition expression is true.
• When the condition becomes false then the control exit from the loop and control passes
to the next line of code immediately following the loop
• The body of the loop may have one or more statements. The brasses are needed only
if the body contains two or more statements.
• The flow chart explains the while loop.
Initialization
Test False
Condition
True
Body of the Loop
Incr/Decr
Initialization
True Test
Condition
?
False
Exit
Process of do-while loop construct
//demonstrate do while
class dowhile
{
do
{
System.out.println (“x=”+x); //body of the loop x--;
}
}
}
For loop:-
• For loop is another entry controlled loop that provides a more consist loop control
structure.
• For loop provides specific locations to contain an initialization statement, test condition
and an increase / decrease statement in a single line.
• So this loop is specially designed to perform a repetitive action. With a counter which
is initialized and increased on each iteration.
• The general form of the for loop is
for ( initialization; test condition; increment/decrement)
{
Body of the loop;
}
• The execution of the for statement is as follows :
→Initialization of the control variables is done first, using the assignment statement such
as i=1 and count=0.
The variables I & count are known as loop control variables
→The value of the control variable is tested using the test condition. The test condition is a
relational expression such as i<10 that determines ------------------------------------ loop will exit.
If the condition is true the body of the loop is executed otherwise the loop is terminated
and execution continues with the statement that immediately follows the loop
→When the body of the loop is executed, the control is transferred to the for statement after
revaluating to the last statement in the loop. Now the control variable is incremented using an
assignment statement such as i=i+1; and the new value of the control variable is again tested, if the
condition is satisfied, the body of the loop will again executed.
→This process continues till the value of the control fails to satisfy the test condition.
Initialization
Test
False
Conditio
n?
True
Body of the loop
Increment/Decrement
Exit
//demonstrate for loop
import java.io.*;
class for loop
{
public static void main ( String k[ ])
{
int sum=0;
for (int i=0; i<10; i++)
{
System.out.println (“i:”+i);
sum=sum+i;
}
System.out.println (“sum:”+sum);
}
}
Nested – for loop:-
• Java supports the nested for loop. A loop contains another for loop is called as the nested
for loop i.e., one for statement with in another for statement is called in java.
• We have used this concept similarly for loops. The general form of the nested for loop is
for(int i=0; i<10; i++)
{
for(int j=0; j<5; j++)
{
Body of the loop; inner for loop Outer for Loop
}
}
• In the nested for loop the counter variable or the outer for loop is checked. It the condition
is true, and then the inner for loop is executed.
• The inner for loop is executed until the certain condition is satisfied. If a condition false
then control back to the outer or statement.
• In the outer for loop the value is updated and checks the test condition. If a condition is
true, then the inner for loop is executed. This process is repeatedly as long as test condition
is true of the outer for loop. Otherwise the outer for loop is an exit.
• Example for the nested for loop
import java.io.*;
class nested{
public static void main (String k[]){ for(int
i=0; i<10; i++)
{
System.out.println(“i:”+i); for
(int j=0; j<=i, j++)
{
System.out.println(“j:”+j);
}
}
}}
Enhanced for loop:-
The enhanced for loop is also called for each loop.
• The enhanced for loop is an extended feature introduced with the J2SE 5.0 release
• This feature helps us to retrieve the array of elements efficiently rather than using array
indexed.
• They can also use this feature to eliminate the iterators in a for loop and to retrieve the
elements for a collection
• The enhanced for loop takes the following for
(type Identifier: expression)
{
// statement;
}
• Where type represents the data type or object
• Identifiers refer to the name of the variable and expression is an array name.
//demonstrate enhanced for loop import
java.io.*;
import java .util.*;
class enhancedfor{
public static void main (String k[ ]){
String states[ ]={“AP”,”TS”,”TM”,”MP”,”UP”};
for (int i=0; i<5; i++)
{
System.out.println(“Normal for Loop:states:”+ states[i]);
}
for(String i: states)
{
System.out.println(“Enhanced for loop:states:”+i);
}
}
}
Jump statements in Java?
Loops perform a set of operations repeatedly until the control variable fails they satisfy
the test condition.
• The number of times a loop is repeated is decided in advanced and the test condition. Is
written to achieve this.
• Sometimes, when executing a loop it becomes desirable to skip a part of the loop or to
leave the loop as soon as certain condition occurs.
• Java permits a jump from one statement to the end or beginning of a loop as well as a jump
out of a loop.
• Java supports two jump statements.
• They are 1.Break
2.Continue;
Using break:-
• The break statement is used to break the condition if the condition is true.
• It is used inside any conditional loop 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
→Third it can be used as a civilized form of go to
Condition Break
?
Remaining Loop
//demonstrate continue
import java.io.*; class
continue loop{
public static void main(String k[ ]){ for
(int i=0; i<10; i++)
{
System.out.println (i+” “); if (
i%2==0)
continue;
System.out.println(“ “);
}
}
}
Classes, objects and methods
Introduction:- Java is a true objected oriented language and therefore the structure of all java
programs is classes.
• Anything we wish to represent in a java program must be encapsulated in a class that
defines the state and behaviour of the basic program components known as objects
• Classes create objects and objects use methods to communicate between them.
Class:- A class is a collection of members that provide a convenient method for packing
together a group of logically related data items and functions that work on them. In java the data
items are called fields and the functions are called methods.
Defining a class:-
• A class is a user defined data type with a template that serves to define its properties.
• Once the class type has been defined, we can create “variables” of that type using
declarations that are similar to the basic type declaration.
• In java, these variables are termed as instances of classes which are the actual objects.
• The basic form of a class definition is
• class classname [extends super classname]
{
[Fields declaration;]
[methods declaration;]
}
• Everything inside the square brackets is optional.
• Class name and super class name are any valid java identifier.
• The keywords extends indicates that the properties of the super class name class are
extended to the class name class.
Fields declaration:-
• Data is encapsulated in a class by placing data fields inside the body of the class definition.
• These variables are called instance variables because they are created whenever an
object of the class is instantiated.
• We can declare the instance variables exactly the same way as we declare the local
variables.
Example :-
class Rectangle
{
int length;
int width;
}
• The class rectangle contains two integer type instance variables.
• Remember these variables are only declared and therefore no storage space has been
created in the memory
• Instance variables are also known as member variables
Method declaration:-
• A class with only data fields has no life.
• Methods are necessary to manipulate the data.
• Methods are declared inside the class but immediately after the declaration of instance
variables.
• The general form of a method declaration is
type methodname(parameter list)
{
Method body ;
}
• The type specifies type of value, the method would return.
• The method name must be valid identifier or otherwise void.
• Void means the function should not return any value
• The parameter list is always enclosed within the parenthesis.
• The body is actually describes the operations performed on the data.
• Let us consider the rectangle class again and add a method getdata( ) to it.
class Rectangle
{
int
length;
int
width;
void getdata(int x, int y) //method declaration
{
length =
x; width
= y;
}
}
Method declaration has four basic parts.
→The name of the method (methodname)
→The type of the value the method returns (type)
→A list of parameters (parameter list)
→The body of the method
Creating objects:-
• An object in java is essentially a block o memory that contains space to store all the instance
variables.
• Creating an object is also referred to as instantiating object.
• Objects in java are created using the new operator. The new operator creates an object of
the specified class and returns a reference to that object.
• Here is an example of creating an object of type rectangle
Rectangle rectl; //a declare the object
rectl = new Rectangle(); // instantiate the object.
• The first statement declares a variable to hold the object reference and the second one
actually assigns the object reference to the variable.
• The variable rectl is now an object of the rectangle class as shown in the below figure.
Action Statement Result
Rectangle rect1; rect1
Declare Null
rect1 is a reference to
Rectangle object
a rectangle object.
Fig(a):creating object reference
• Both statements can be combined into one as shown in the below
rectangle rectl = new Rectangle ();
• The method Rectangle() is the default constructor of the class”.
• We can create any number of objects of Rectangle
Eg :- Rectangle rect1 = new Rectangle();
Rectangle rect2 = new Rectangle();
• It is important to understand that each object has its own copy of the instance
variables of its classes.
R1
•
Rectangle Object
•
R2
Both R1,R2 refer to the same object
• It is also possible to create two one more reference t the same object as shown below.
Rectangle R1= new rectangle ();
Rectangle R2 = R1;
Accessing class members:-Now that we have created objects, each containing its own set of
variables, we should assign values to these variables in order to use them in our program.
• Remember all variables must be assigned values before they are used.
• Since we are outside the class, we con not access the instance variables and the methods
directly.
• To do this I we must use the concerned object and the dot operator as shown in the below.
Objectname.variablename = value;
Objectname.methodname(parameter list);
• Here object name is the name of the object, variable name is the name of the instance
variable inside the object that we wish to access
• Method name is the method that we wish to call and parameter list is a comma separated
list of actual a values that must match in type and member with the parameter list of the
method name declare in the class.
• The instance variables of the rectangle class may be assigned values as follows.
rect1.length = 15;
rect1.width =10;
rect2.lenght=20;
rect2.breadth=12;
• Now that the objects rectl and rect2 store different values as shown below
rect1
rect1.length 15
rect2.width 10
rect2
rect2.leangth 20
rect2.width 12
Rules/Properties/Characteristics of a Constructor:
▪ Constructor name must be similar to name of the class.
▪ Constructor should not return any value even void also (if we write the return type for the
constructor then that constructor will be treated as ordinary method).
▪ Constructors should not be static since constructors will be called each and every time
whenever an object is creating.
▪ Constructor should not be private provided an object of one class is created in another class
(constructor can be private provided an object of one class created in the same class).
▪ Constructors will not be inherited at all.
▪ Constructors are called automatically whenever an object is creating.
Static members:-
1) Java static variable
If you declare any variable as static, it is known as a static variable.
o The static variable can be used to refer to the common property of all objects (which is not
unique for each object), for example, the company name of employees, college name of
students, etc.
o The static variable gets memory only once in the class area at the time of class loading.
rollno = r;
name = n;
}
//method to display the values
void display ()
{
System.out.println(rollno+" "+name+" "+college);
}
}
//Test class to show the values of objects
public class TestStaticVariable1
{
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
s1.display();
s2.display();
}
}
2) Java static method
If you apply static keyword with any method, it is known as static method.
o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance of a class.
o A static method can access static data member and can change the value of it.
Example of static method
//Java Program to demonstrate the use of a static method.
class Student
{
int rollno; String name;
static String college = "ITS";
//static method to change the value of static variable
static void change()
{
college = "BBDIT";
}
//constructor to initialize the variable
Student(int r, String n)
{
rollno = r; name = n;
}
//method to display values
void display()
{
System.out.println(rollno+" "+name+" "+college);
}
}
//Test class to create and display the values of object
public class TestStaticMethod
{
public static void main(String args[])
{
Student.change();//calling change method
//creating objects
Student s1 = new Student(111,"Karan");
e=null;
By assigning a reference to another:
Employee e1=new Employee(); Employee
e2=new Employee();
e1=e2;//now the first object referred by e1 is available for garbage collection
1) By anonymous object:
new Employee();
finalize() method
The finalize() method is invoked each time before the object is garbage collected. This method can
be used to perform cleanup processing. This method is defined in Object class as:
protected void finalize()
{
gc() method
The gc() method is used to invoke the garbage collector to perform cleanup processing.
The gc() is found in System and Runtime classes.
public static void gc(){}
Simple Example of garbage collection in java
{
public void finalize()
{
System.out.println("object is garbage collected");
Array:-
• An array is a group of contiguous or related data items that share a common name.
• For instance we can define an array name salary to represent a set of salaries of a group of
employees
• A particular value is indicated by writing a number called index number or subscript in the
brackets after the array name
• For example salary [10] represent the salary of 10th employee
Advantages:
1) Array can store multiple values of same data type.
2) All the elements in array are accessible by using single name (array name). It overcomes
the name conflict problem.
3) It is a capable of storing many elements at a time.
4) The memory locations of elements in the array are sequential.
5) Sorting and searching becomes easy.
Disadvantages:
1) Memory wastage will be there.
2) To delete an element in array. We need to traverse throughout an array.
3) The size of the array is fixed while declaration itself.
4) The size can‟t be increased / decreased dynamically.
How to create an array:-
• Like any other variable, array must be declared and created in the computer memory before
they are used.
• Creation of an array involves three steps
I. Declaring the array
II. Creating memory locations
III. Putting-values into the memory locations(initialization)
Declaration of arrays:-
• Arrays in java may be declared in two forms.
Form1
Type array name [ ];
Form 2
Type [ ] array name;
Examples:-
int number [ ]; float
average [ ]; int [ ]
counter; float [ ]
marks;
• Remember we do not enter the size of the array in declaration
• Array name is an any valid java identifier
Creation of Arrays:-
• After declaring an array, we need to create it in the memory
• Java allows us to create arrays using new operator only as shown below.
Example:-
number = new int [5];
average = new float [ 10 ];
• These lines create necessary memory locations for the arrays number and average and
designate them as int and float respectively
• Now the variable number refers to an array of 5 integers and average refers to an
array of 10 floating point values.
• It is also possible to combine the two steps declaration and creation into one as shown
below.
int number [ ]= new int [5];
• The below figure shows the creation of an array in the memory.
Statement Result
int number[ ]; number
• Points no where
number=new int[5]; number
•
number[0]
number[1]
number[2]
number[3]
number[4]
Example:-
int number[ ] = {10,20,30,40,50};
• The array initialize is a list of values separated by comma and surrounded by
curly braces.
• The compiler allocates enough space for all the elements specified in the list that no size
is given
Array length:-
• In Java all arrays store the allocated size in a variable named length. We can obtain the
length of the array using a length
▪ Example:- int a[size]=a. length;
• This information will be useful in the manipulation of arrays when their sizes are not
down (or) given.
Types of arrays:-
• Java supports the two types of arrays mainly. The two dimensional array supports the arrays
of arrays is called multidimensional array or variable size array. They are
I. Single dimensional array
II. Two dimensional array
III. Variable size array.
1. Single (or) one dimensional array:-
A list of items can be given one variable name using only one subscript. Such a variable is called
a single subscripted variable or a one dimensional array.
The below form shows the single dimensional array:
Type array name[ ] = new type [size];
Example:-
int number [ ] = new int [5];
//demnonstrate for single Dimensional array.
class singled
{
public state void main (String args[ ])
{
int temp=0;
int number[ ] = {35,50,85, 25,15
};
int n=number.length;
//display array elements
for (int i=0; i<n; i++)
{
System.out.println (“ ”+number[i];
}
//sorting
for(int i=0; i<n; i++)
{
for (int j=i+1; j < n; j++)
{
if(number [i] < number[ j] )
{
temp= number[i];
number[i] = number [ j ]
number[ j ] = temp;
}
}
}
//sorting elements are
for (int i=0; i<n; i++)
{
Systems.out.println(number[i]);
}
}
}
2. Two dimensional arrays:-
• A list of items can be given one variable name using two subscripts or two indexes is called
two dimensional array.
• A two dimensional array a table of values will may have to be stored.
• For creating two dimensional arrays. We must follow the same steps as that of simple
arrays.
• We may create a two dimensional array like this.
int ARRAY[ ][ ];
ARRAY = new int [3] [4];
(or)
int ARRAY[ ][ ] = new int[3][4];
• This creates a table that can store 12 integer values, 3 across & 4down. The first index
selects the row and second index selects the columns with in that row as shown in below.
Column0 Column1 Column2 Column3
X[0] X[0][1]
1][3]
X[1] X[
X[2]
X[2][2]
Fig(c)Variable size array
COMMAND LINE ARGUMENTS:
A command-line argument is an information that directly follows the program's name on the
command line when it is executed. To access the command-line arguments inside a Java program is
quite easy. They are stored as strings in the String array passed to main( ).
Example
The following program displays all of the command-line arguments
public class CommandLine {
i<args.length; i++) {
System.out.println("args[" + i + "]: " + args[i]);
Inheritance:-
Introduction:-
Reusability is yet another aspect of oop paradigm. It is always nice if we could reuse something
that already exists rather than creating the same all over again.
• Java supports this concept.java classes can be reused in several ways.
• This is basically conveyed creating new classes, reusing the properties of existing ones.
Inheritance:-
❖ The mechanism of deriving a new class from an old one is called as inheritance.
❖ The old class is known as the base class or super class or parent class and the new class is
called the sub class or derived class or child class.
❖ The inheritance allows sub-classes to inherit all the variable and methods of their parent
classes.
Types of inheritance:-
Inheritance may take different forms
i. Single inheritance (only one super class)
ii. Multiple inheritance (several super classes)
iii. Hierarchical inheritance (one super class, many sub class)
iv. Multilevel inheritance (derived from a derived class)
These forms of inheritance are shown in the below figure.
A Base/Super/Parent A
B Derived/Sub/Child B C D
B
C
• The class A serves as a base class for the derived class B class A
//super class
{
}
class B extends A // subclass.
{
}
//demonstrate for single inheritance import
java.io.*;
class Room
{
int length;
int breadth;
Room (int x, int y)
{
length=x;
breadth=y;
}
int area()
{
return (length*breadth);
}
}
class Bedroom extends Room
{
int height;
Bedroom (int x , int y, int z)
{
super (x,y); //send x and y values to super class height=z;
}
int volume()
{
return(length*breadth*height);
}
}
class sidemo
{
public static void main(Sting args[])
{ Bedroom b=new Bedroom (10,15,20);
int a=b.area();
int v=b.volume();
System.out.println (“area=”+a);
System.out.println (“volume=”+v);
}
}
Multiple inheritances:-
• A sub class has the several super classes is called as the multiple as the multiple
inheritance.
A B
• Java does not directly implement multiple inheritances. However this concept is
implemented using a secondary inheritance path in the form of interface
Multilevel inheritance:-
• A common requirement in object oriented programming is the use of a derived class
as a super class is called multilevel inheritance.
• Java supports this concept and uses it extensively in building its class library.
• This concept allows us to build a chain of classes as shown in below figure
• The class A serves as base class for the derived class B. which in turn serves as a base
class for the derived class C
• The chain ABC is known inheritance path
• A derived class with multilevel base classes is declared as follows.
Class A
{
}
Class B extend A // first level
{
}
Class C extends B //second level
{
}
• This process may be extended to any number of levels.
• The class C can inherit the member of both A and B as in the below figure.
Class C members
Class B members
Class A members
Hierarchical inheritance:-
• In an inheritance a super class has many sub classes is called as hierarchical inheritance.
• In hierarchical inheritance the sub classes can access the all properties of the super class
• The below figure shows the hierarchical inheritance.
B C D
Fig(a) : Hierarchical inheritance
• Many programming problems can be cast into a hierarchy where certain features of
one level are shared by many others below the level.
• As an example for an hierarchical classification of account for in a commercial
bank
• This is possible because all the accounts possess certain common features as show below
figure.
Account
Savings Current
Fixed-Deposit
• If at all a parents class method is redefined under the child class with the same name, same
arguments and same return type is called as method overriding
• Example program for the method overriding
// demonstrate for method overriding
class A
{
int x;
A(int x) // constructor
{
this.x=x;
}
void display()
{
System.out.print(“super:x”=+x);
}
}
class B extends A
{
int y;
B(int x, int y)//child class constructor
{
Super (x);
this.y=y;
}
void display()
{
System.out.println(“super:x”+x);
System.out.println(“super:y”+y);
}
}
class method
{
public static void main (sting args[])
{
B b=new B(10,15);
b.display();
}
}
final variables, final methods and final class:-
Final variables and methods:-
• All method and variables can be overriding by default in subclasses.
• If we wish to prevent the subclasses from overriding the member of the subclass.
We can declare then as final using the keyword final as a modifier
Example :-
final int SIZE=100;
final void display ()
{
}
• Making a method final ensure that the functionality defined in this method will never be
altered in anyway.
Example:-
class Bike
{
final void run()
{
System.out.println("running");
}
}
class Honda extends Bike
{
void run()
{
System.out.println("running safely with 100kmph");
}
public static void main(String args[])
{
Honda honda= new Honda(); honda.run();
}
}
}
final class B extends some class
{
}
• Any attempt to inherit these classes will cause an error and the compiler will not allowed
it .Declaring a class final .prevent any unwanted extension to the class
Abstract class:-
• A class which contain the abstract keyword in its declaration is known as abstract class
• Abstract class may or may not contain methods i.e., methods without body and methods
end with a semicolon (;).
• Example: public void get ();
• But, if a class has at least one abstract method then the class must be declared
abstract.
• If a class is declared abstract cannot be instantiated
• To use an abstract class, provide implementation to the abstract method in it
Abstract method:-
• If you want a class contain a particular method but you want the actual implemental of that
method to be determined by child classes, we can declare the method in the parent class as
abstract.
• Abstract keyword is used to declare the method as abstract
• We have to place the abstract keyword before the method name in the method
declaration
• An abstract method contains a method signature but no method body
• Instead of curly braces an abstract method we have a semicolon() at the end
• Example program for abstract class & method
// demonstrate for abstract classes and method abstract
class shape
{
abstract void draw();
}
class rectangle extends shape
{
void draw()
{
System.out.println (“draw rectangle”);
}
}
class circle extend shape
{
void draw()
{
System.out.println(“Draw circle”)
}
}
class abstracttest
{
public static void main (String k[]){ Shape
s=new circle( );
s.draw( );
}
}