Unit-1 java
Unit-1 java
CO4I
Chapter-1
1. Classes
}
void display()
{
System.out.println(“Name=”+name);
System.out.println(“Age=”+age);
}
2. Objects
Objects are basic run time entities in object oriented system. They may represent a place, a bank
account, a table of data or any item that the program must handle.
Objects are variables of class.
Objects are generally used to access members (data and methods) of class.
Eg. Person p =new Person()
Here p is an object of Person class
3. Data abstraction
Data abstraction refers to act of representing essential features without including background
details or explanations.
Classes use the concept of abstraction and are defined as the list abstraction attribute such as size,
weight and cost and function to operate on this attribute. They encapsulate all essential properties
of objects that they are to be created since the class used the concept of data abstraction they are
1
Java Programming Notes
CO4I
known as abstract data types(ADT).
4. Data encapsulation
Data encapsulation means wrapping of data and functions into a single unit. It is most striking
feature of class. The data is not accessible to the outside world and only functions which are
wrapped in the class can access it.
Thus insulation of data from direct access from program is called data hiding.
5. Inheritence
Inheritence is the process by which object of one class can acquire the properties of the objects of
other classes. Inheritence means one class of object inherits the data and behavoiur(methods)
from another class .
The old is refered as a base class and new one is called as derived class. The new class has
combined features of both the classes.
6. Polymorphism
7. Dynamic binding
Binding refers to the linking of a procedure call to the Procedure definition (code) to be executed
in response to the call.
Binding is classified as static binding and dynamic binding.
Static binding means that the code associated with given procedure call is known at compile time.
Dynamic binding means that the code associated with given procedure call is not known until the
time of the call at run time.
Dynamic binding associated with polymorphism and inheritance.
8. Message Passing
Message passing involves specifying the name of object, the name of the method and the
information to be sent.
Example:.
p.accept(“abc”,18);
2
Java Programming Notes
CO4I
OOP emphasis on data rather than procedure.
Programs are divided into objects.
Objects are characterized by functions or data structure that operates on data.
Functions that operates on the data of an object are tied together in the data structure.
Data is hidden and cannot be accessed by external functions.
Objects may communicate with each other through functions.
New data and functions can be easily added whenever necessary.
Follows bottom-up approach in program design.
2. Java Features:
1. Compiler/Interpreter
Java Source Code (.java file) is compiled to byte codes(.class file) that are interpreted by a Java
virtual machines (JVM) .
This provides portability to any machine for which a virtual machine has been written.
The two steps of compilation and interpretation allow for extensive code checking and improved
security.
Java source code Java Compiler Byte code Interpreter Machine code
(.java file) (javac) (.class file) (java)
2. Platform Independence
Java byte code achieves the Write-Once-Run-Anywhere approach so running on different
platforms is possible. As we know java is both compiler & interpreter based language. Once the
java code also known as source code is compiled, it gets converted to Byte Code which is
portable & can be easily executed on all operating systems. Byte code generated is basically
represented in hexa decimal format in .class file. This .class file contains bytecode which is
executed JVM(Java virtual machine) which is a runtime environment for java. Now this .class file
can be run in any environment with the help of JVM and JVM convert bytecode into native
code.
Java Virtual Machine like its real counter part, executes the program and generate output. To
execute any code, JVM utilizes different components. JVM is divided into several components
like the stack, the garbage-collected heap, the registers and the method area.
3
Java Programming Notes
CO4I
Above fig. shows that JVM for different operating system is different.The JVM must translate the
bytecode into machine language, and since the machine language depends on the operating
system being used, it is clear that the JVM is platform (operating system) dependent – in other
words, the JVM is not platform independent.
3. Object Oriented
Supports all the concepts of object oriented programming language like object classes,
polymorphism etc.
Java is pure object oriented Language – Each and every code in java comes under a class,
including main().
Following is the example shows that even main function is comes under a class:
class Demo
{
public static void main(String args[])
{
System.out.println(“hello”);
}
}
5.Dynamic Binding
4
Java Programming Notes
CO4I
o The linking of data and methods to where they are located, is done at run-time.New
classes can be loaded while a program is running. Linking is done on the fly.
o Even if libraries are recompiled, there is no need to recompile code that uses classes in
those libraries.
6. Good Performance
o Interpretation of bytecodes slowed performance in early versions, but advanced virtual
machines with adaptive and just-in-time compilation and other techniques now typically
provide performance up to 50% to 100% the speed of C++ programs.
7. Threading
o Lightweight processes, called threads, can easily be added to perform multiprocessing.
o Can take advantage of multiprocessors where available
o Good for multimedia displays.
8. Built-in Networking
o Java was designed with networking in mind and comes with many classes to develop
sophisticated Internet communications.
3. History of Java
Java language developed by SUN MICROSYSTEM. Its initial purpose was o handle consumer electronic
devices. The team which was working on java is named as “Green team” which headed by James
Gosling.
1991-: In 1991 they developed a new language and gave the name of "oak".
1992-: In 1992 they demonstrate the application of new language to handle consumer electronic devices.
1993-: WWW came into existence to handle computer on internet.
1994-: Developed web browser to support web applets.
1995-: Name "OaK" is replaced by java.
1996-:onwards it is knows as object oriented language.
5
Java Programming Notes
CO4I
Every variable and method is declared
within a class and forms part of that class
7 Java does not have template classes C++ has template classes
8 Java has replaced the destructor function C++ has the destructor function
with a finalize( )function
9 There are no header files in Java C++ includes header files in program
Documentation section:
This section is not compiled by java compiler. In this section only title of program is written for
understanding of programmer.Title of program can be single line or multiline.
Package /statement:
This statement is used by programmer whenever they want to create a package. Package is collection of
classes and interface. Statement is written as
package Packagename;
Import Statement:
This statement is used to include java packages or user defined packages in to your program. For example
to include java input output package user can use following statement.
import java.io.*;
Interface Statement:
Interface statement is added to program when we want to achieve multiple inheritance. Statement is
written as
6
Java Programming Notes
CO4I
interface interfacename;
Class Definition:
As java is pure object oriented so each and every code will comes under a class .which consist of main
method. The syntax of main method is as follows:
These dynamic networked programs create problems in terms of security and portability. Java
effectively handles these problems. Introducing a new form of program known as Applet does
this.
Java Applets
Java communicates with Web page through a special tag called <APPLET>. An applet as a
special program that is transmitted over the network or Internet. It automatically get executed by
Java – compatible Web Browser.
An applet is said to an “Intelligent Program” because the applet tends to react to the user input
and changes its status dynamically.
Java takes care of major issues related with security and portability of any program code over
Internet.
7
Java Programming Notes
CO4I
Security becomes an important issue for a language which is used for programming on Internet.
Java system not only verifies all memory access but also ensure that no viruses are communicated
with an applet and also ensure that programs cannot gain access to memory locations without
proper authorization.
Java supports the feature portability. Java programs can be easily moved from one computer
system to another ,anywhere and any time. This is the reason why Java has become a popular
language for programming on Internet which interconnects different kind of systems worldwide.
Java ensures portability in two ways.
1. Java compiler generates byte-code instructions that can be implemented on any machine.
2. The size of the primitive data types is machine independent.
7. Constants
In java constants, refer to fixed values that do not change during the execution of a program. Java
supports several types of constants listed below and shown below:
Integer constants
An integer constants means the sequence of digits. There are three types of integers,
1. Decimal Integer: Decimal integers consists of a set of digits,0 through 9,preceded by an
optional minus sign.
Ex:325,-978,45673
Embedded spaces, commas, and non-digits characters are not allowed between digits.
Ex:15 78,$657-,#47 is illegal number.
2. Octal Integer: An octal integer constant consists of any combination of digits from the set 0
through 7, with al leading 0.
Ex:027, 0, 0231, 0341
8
Java Programming Notes
CO4I
3. Hexadecimal Integer: A sequence of digits preceded by 0x or ox is considered a hexadecimal
integer(hex integer).They may also include alphabet A through F or a through f.A letter A
through F represents the number 1 through 15. Ex:0X4 ,0X15, 0xabed.
Real Constant:
Integers numbers are insufficient to represents quantities that vary continuously, such as distance
Heights, temperature, prices, and so on. Numbers having fractional parts like 17.548 represents
these quantities. Such numbers are called real(or floating point) constants.
Examples: 1.9783, 0 0047
The real number constant can comprise of four parts:
A whole number.
A decimal point.
A fractional part.
An exponent part.
These numbers are shown in decimal notation, having a whole number followed by a decimal
point and the fractional part, which is an integer. For example: 0.035, 111.98
A real number may also be expressed as in exponential (or scientific) notation. For example, the
value 215.65 may be written as 2.1565e2 in exponential notation. E2 means multiply by 10^2.
The general form is: mantissa e exponent.
Example: 0.65e4, 15e-5, 2.6e+6 56.E4
Character constant:
A single character constant or character constant contains a single character enclosed within a pair of
single quote marks. Examples are ‘7’, ‘A’,’*’,’’. The character constant ‘7’ is not the same as the number
7. The last constant is blank space.
String constant:
A string constant is a sequence of character enclosed between double quotes in which the character may
be alphabets, digits, special characters and blank spaces.
Examples: “WELCOME”,”@june”,”abhishek”,”!NIDHI!”
Backslash:
The backslash character constant are used with output statements for getting more effects like tab, new
line, single quote etc. Java support some special backslash character constants. A list of such backslash
character constant is given following table. Each one of them represents one character, although they
consist of two character. These characters combinations are known as escape sequences.
Constant Meaning
‘\b’ Back space
‘\f’ Form feed
‘\n’ New line
‘\r’ Carriage return
9
Java Programming Notes
CO4I
‘\t’ Horizontal tab
‘\” Single quote
‘\ “” Double quote
‘\ \’ Backslash
8. Symbolic Constants
Symbolic constants refer to the variable name having value which cannot be modified. For example
pi=3.14 now the pi can be used instead of 3.14.For the convention symbolic names are written in
CAPITALS to distinguish from other variable names. After declaration of symbolic constants, they
should not be reassigned any other value. Symbolic constants cannot be declared inside a method. They
should be used only as class data members in the beginning of the class.
Syntax:
Final datatype symbolic_name=value;
Example
class Circle
{
final double PI=3.14f; //Symbolic constant
int radius;
void accept(int r)
{
radius=r;
}
void display()
{
double area=PI*radius*radius;
System.out.println("Radius is :"+radius);
System.out.println("Area of circle is :"+area);
}
public static void main(String args[])
{
Circle c=new Circle();
c.accept(5);
c.display();
}
}
Output:
Radius is : 5
Area of circle is :78.50000262260437
9.Variable its rules and naming conventions
A variable is an identifier that denotes a storage location used to store a data value or A variable is a basic
unit of storage. Unlike constants that remain unchanged during the execution if the program. A variable
may take different values at different times during the execution of the program.
10
Java Programming Notes
CO4I
A variable name can be chosen by the programmer in a meaningful way so as to reflect data stored in it.
For example: radius, squ, total_height, classStreangth. A variable names may consist of alphabates, digits,
the underscore (-) and dollar ($) characters.
10.Dynamic Initialization
Java allows its programmers to initialize a variable at run time also. Initializing a variable at run time is
called dynamic initialization.
class DynamicInit
{
public static void main(String args[])
{
double a = 3.0, b = 4.0;
// c is dynamically initialized
double c = Math.sqrt(a * a + b * b);
System.out.print("C=" + c);
}
}
Output:
11
Java Programming Notes
CO4I
C=5.0
11.Date types and its storage
In java every variable has a data type. Datatypes specifies the size and types of data that can be stored.
Data types
Primitive Non-Primitive
The eight primitive data types supported by the java programming language are:
1. byte: The byte data type is an 8-bit signed two’s complement integer. It has a maximum value of
-128 and a maximum value of 127(inclusive).
2. short: The short data type is 16-bit singed two’s complement integer. It has a maximum value of
-32,768 and a maximum value of 32,767(inclusive).
3. int: The int data type is 32-bit singed two’s complement integer. It has a maximum value of -
2,147,483,648 and a maximum value of 2,147,483,647(inclusive).
4. long: The long data type is 64-bit singed two’s complement integer. It has a maximum value of -
9,223,372,036,854,775,808 anda maximum value of 9,223,372,036,854,775,808
(inclusive).Use this data type when you need a range of values wider than those provided
by int.
5. float: The float data type is a single-precision 32-byte IEEE 754 Floating point.
6. double: The float data type is a double-precision 64-byte IEEE 754 Floating point.
7. boolean: The Boolean data type has only two possible values. true and false.Use this data type
for simple flags that track true/false conditions.
8. char: The char data type is single 16-bit Unicode character. It has a maximum value of ‘\
u0000’(or 0) and a maximum value of ‘\uffff’(or 65,535 inclusive).
12
Java Programming Notes
CO4I
6 Double 8
7 char 2
Java variables are actually classified into three categories and their scope is defined according their
category. The types of Java Variables are as follows:
Instances are declared inside the class. Instance variables are created when the objects are instantiated
(created) and those are associated with the objects .They take different values for each object.
Class variables are declared inside the class and global to the class and belong to the entire set of
object and that class creates. Only one memory location is created for each class variable.
Local variables declared and used inside the methods. They are not available outside of the method
definition. Local variables can be declared inside the program blocks that are defined between the
opening ({) and closing braces (}). These variables are visible to the program only. When the
program control leaves block, all the variables in the block will cease to exit.
13
Java Programming Notes
CO4I
Example:
}
void show()
{
count++;
System.out.println("count="+count);
}
void display()
{
System.out.println("Name="+name);
System.out.println("Age="+age);
}
public static void main(String args[])
{
Sample s1=new Sample();
Sample s2=new Sample();
s1.accept("abc",10);
s1.display();
s1.show();
s2.accept("xyz",20);
s2.display();
s2.show();
}
}
Output:
Name=abc
Age=10
count=1
Name=xyz
Age=20
count=2
14
Java Programming Notes
CO4I
13.Type Conversion
In some cases we might want to assign value of one type to variable of another type. If both the source
and destination types are compatible, then java performs the conversion implicitly(automatically).
Examples of compatible types are int, long, short and byte. Also float and double are compatible with
each other while char and boolean are not compatible with each other.
Implicit conversion is also called as coercion. Java automatically converts from one type to another only
when the following two conditions are satisfied:
When the above two conditions are satisfied, java performs an implicit conversion. This is also known as
“Widening Conversion”.
int x=60;
long n= x;
here int can be auto converted to long since the size of long is 64, where as size of int is 32. Similarly a
byte can be auto converted or implicitly converted to int.int can also be implicitly converted to float and
double. 19 specific conversions on primitive types are called the widening primitive conversions:
In widening primitive conversion there is no losing of information about the magnitude of a numeric
value.
Explicit conversion also called as casting. Type casting occurs when there is a need to store a value of one
data type into a variable of another type. Casting is necessary when a method returns a type different than
one require. Type casting refers to changing an entity of one datat ype into another. This is important for
the type conversion in developing any application. If you will store a int value into a byte variable
directly, this will be illegal operation. For storing your calculated int value in a byte variable you will
have to change the type of resultant data which has to be stored .It is possible to cast a value to be stored
by proceeding it with the type name in paranthesis.
15
Java Programming Notes
CO4I
The syntax is
DataType variable1=(DataType)variable2;
Examples are:
int x=60;
byte n=(byte)x;
This is also known as “narrowing conversion” ,which may result in loss of information.22
specific conversions on primitive types are called the narrowing primitive conversions:
Byte Zero(byte 0)
Short Zero(short 0)
Int Zero:0
Long Zero:0L
Float 0.0f
Double 0.0d
16
Java Programming Notes
CO4I
Boolean False
Reference Null
- Subtraction - Subtracts right hand operand from left hand operand A - B will give -10
* Multiplication - Multiplies values on either side of the operator A * B will give 200
/ Division - Divides left hand operand by right hand operand B / A will give 2
Modulus - Divides left hand operand by right hand operand and returns
% B % A will give 0
remainder
The following simple example program demonstrates the arithmetic operators. Write following Java program in
Test.java file and compile and run this program:
17
Java Programming Notes
CO4I
a + b = 30
a - b = -10
a * b = 200
b/a=2
b%a=0
c%a=5
a++ = 10
b-- = 11
d++ = 25
++d = 27
Operato
Description Example
r
Checks if the values of two operands are equal or not, if yes then (A == B) is
==
condition becomes true. not true.
Checks if the values of two operands are equal or not, if values are not (A != B) is
!=
equal then condition becomes true. true.
Checks if the value of left operand is greater than the value of right (A > B) is not
>
operand, if yes then condition becomes true. true.
Checks if the value of left operand is less than the value of right (A < B) is
<
operand, if yes then condition becomes true. true.
Checks if the value of left operand is greater than or equal to the value (A >= B) is
>=
of right operand, if yes then condition becomes true. not true.
Checks if the value of left operand is less than or equal to the value of (A <= B) is
<=
right operand, if yes then condition becomes true. true.
18
Java Programming Notes
CO4I
Example:
public class Sample
{
}
}
Output:
a < b = true
c > b = true
c <= d = true
c >= d = true
c == d = true
The following table lists the bitwise operators: Assume integer variable A holds 60 and variable B holds
13 then:
Operato
Description Example
r
Binary AND Operator copies a bit to the result if (A & B) will give 12 which is 0000
&
it exists in both operands. 1100
| Binary OR Operator copies a bit if it exists in (A | B) will give 61 which is 0011
19
Java Programming Notes
CO4I
Example:
}
}
Output:
a & b = 20
a | b = 60
a << 2 = 240
a >> 2 = 15
a >>> 2 = 15
20
Java Programming Notes
CO4I
The Logical Operators:
The following table lists the logical operators: Assume Boolean variables A holds true and variable B
holds false, then:
Operato
Description Example
r
Called Logical AND operator. If both the operands are non-zero, then
&& (A && B) is false.
the condition becomes true.
Called Logical OR Operator. If any of the two operands are non-zero,
|| (A || B) is true.
then the condition becomes true.
Called Logical NOT Operator. Use to reverses the logical state of its
! operand. If a condition is true then Logical NOT operator will make !(A && B) is true.
false.
Example:
}
}
Output:
Operato
Description Example
r
= Simple assignment operator, Assigns values from right C = A + B will assign value of A +
21
Java Programming Notes
CO4I
Misc Operators
There are few other operators supported by Java Language.
Conditional Operator ( ? : )
Conditional operator is also known as the ternary operator. This operator consists of three operands and is
used to evaluate Boolean expressions. The goal of the operator is to decide which value should be
assigned to the variable. The operator is written as:
22
Java Programming Notes
CO4I
}
}
This would produce the following result:
Value of b is : 30
Value of b is : 20
instanceof Operator:
This operator is used only for object reference variables. The operator checks whether the object is of a
particular type(class type or interface type). instanceof operator is wriiten as:
If the object on the left side of the operator is an object of right side, then the result will be true.
Following is the example:
Dot operator:
Dot operator is used to access class members i.e. methods and data.
class Person
{
String name;
int age;
void display()
{
System.out.println(“Name=”+name);
System.out.println(“Age=”+age);
}
public static void main(String args[])
{
Person p=new Person()
p.name=”abc”;
p.age=”10”;
p.display();
23
Java Programming Notes
CO4I
}
}
This would produce the following result:
Name=abc
Age=10
Precedence Order
When two operators share an operand the operator with the higher precedence goes first. For example, 1 +
2 * 3 is treated as 1 + (2 * 3), whereas 1 * 2 + 3 is treated as (1 * 2) + 3 since multiplication has a higher
precedence than addition.
Associativity
When two operators with the same precedence the expression is evaluated according to its associativity.
For example x = y = z = 17 is treated as x = (y = (z = 17)), leaving all three variables with the value 17,
since the = operator has right-to-left associativity (and an assignment statement evaluates to the value on
the right hand side). On the other hand, 72 / 2 / 3 is treated as (72 / 2) / 3 since the / operator has left-to-
right associativity.
Following table is showing the associativity and precedence order of java operators.
More complex expressions can be built up by using operators to combine simpler expressions. Operators
include + for adding two numbers, > for comparing two values, and so on. When several operators appear
in an expression, there is a question of precedence, which determines how the operators are grouped for
evaluation. For example, in the expression "A + B * C", B*C is computed first and then the result is
added to A. We say that multiplication (*) has higher precedence than addition (+). If the default
precedence is not what you want, you can use parentheses to explicitly specify the grouping you want.
For example, you could use "(A + B) * C" if you want to add A to B first and then multiply the result by
C.
In general, the type of the expression on the right-hand side of an assignment statement must be the same
as the type of the variable on the left-hand side. However, in some cases, the computer will automatically
convert the value computed by the expression to match the type of the variable. Consider the list of
numeric types: byte, short, int, long, float, double. A value of a type that occurs earlier in this list can be
converted automatically to a value that occurs later. For example:
int A;
double X;
short B;
A = 17;
X = A; // OK; A is converted to a double
B = A; // illegal; no automatic conversion from int to short
In some cases, you might want to force a conversion that wouldn't be done automatically. For this, you
can use what is called a type cast. A type cast is indicated by putting a type name, in parentheses, in front
of the value you want to convert. For example,
int A;
short B;
A = 17;
B = (short)A; // OK; A is explicitly type cast to a value of type short
S.N Description
Method & Description
.
1 static double abs(datatype a) This method returns the absolute value of a mentioned data.
2 static double ceil(double a) This method returns the smallest (closest to negative infinity)
25
Java Programming Notes
CO4I
double value that is greater than or equal to the argument and
is equal to a mathematical integer.
This method returns Euler's number e raised to the power of
3 static double exp(double a)
a double value
This method returns the largest (closest to positive infinity)
4 static double floor(double a) double value that is less than or equal to the argument and is
equal to a mathematical integer
static double log(double a) This method returns the natural logarithm (base e) of a
5
double value.
static double max(double a, This method returns the greater of two double values
6
double b)
7 static float max(float a, float b) This method returns the greater of two float values
static int max(int a, int b) This method returns the greater of two int values.
8
static long max(long a, long b) This method returns the greater of two long values.
9
static double min(double a, This method returns the smaller of two double values.
10 double b)
static float min(float a, float b) This method returns the smaller of two float values.
11
static int min(int a, int b) This method returns the smaller of two int values.
12
static long min(long a, long b) This method returns the smaller of two long values.
13
static double pow(double a, This method returns the value of the first argument raised to
14 double b) the power of the second argument.
static long round(double/float a) This method returns the closest long to the argument.
15
This method returns the correctly rounded positive square
16 static double sqrt(double a) .
root of a double value
Example:
26
Java Programming Notes
CO4I
System.out.println("Maximum=" + Math.max(x, y));
}
}
This would produce the following result:
Ceil =2.0
Floor =1.0
Ceil =-2.0
Floor =-3.0
Power =100.0
Sqrt =4.0
Minimum=10.0
Maximum=16.0
Any statement may begin with a label. Such labels may noy be keywords, already
Labeled
declared as local variables or previously used labels in this module. Labels in java
Statement
are used as arguments of jump statements, which are later described in this list.
These specify how and when looping will take place. There are three types of
Iteration Statement
iteration statements: while do and for.
Jump statements pass control to the beginning or end of the current block,or at a
labelled statement.such labels must be in the same block,and continue labels must
Jump Statement
be in the iteration statement.the four types of jump statements are:
break,continue,return and throw.
Synchronization
These are used for handling issues with multi-threading.
Statement
Gaurding Guarding statements are used for safe handling of code that may cause exceptions
Statement (such as division by zero) these statements use keywords try, catch and finally.
27
Java Programming Notes
CO4I
JAVA STATEMENTS
CONTROL
STATEMENT
ITERATION STATEMENT
WHILE FOR
DO
28
Java Programming Notes
CO4I
Java environment includes a number of development tools, classes and methods. The development tools
are part of the system known as Java Development kit(JDK) and the classes and methods are part of the
Java Standard Library(JSL), also known as the Application Programming Interface(API).
The Java Development Kit comes with a collection of tools that are used for developing and running java
programs. They include:
1. appletviewer (for viewing Java applets):
A pre-created applet can be viewed using applet viewer. Enables us to run Java applets (without
actually using a Java-compatible browser). it has syntax:
c:\ appletviewer<URL of the .html file>
2. javac (java compiler):
A java program can be created by using any text editor and save file with extension .java. Java
compiler, which translates Java sourcecode to bytecode files that the interpreter can understand.
Or it converts the "java" file to a "class" file. it has following syntax:
c:\>javac filename.java
3. java (java interpreter):
The Java interpreter is used to execute a compiled java application (.class). Java interpreter,
which runs applets and applications by reading and interpreting bytecode files. The bytecode
created as a result of compilation is interpreted.
The syntax is (file extension is not needed);
c:\> java filename
4. javap (Java disassembler:
Java disassembler, which enables us to convert bytecode files into a program, description.
5. javah (for C header files):
Produces header files for uses with native methods.
6. javadoc (for creating HTML documents):
Creates HTML-format documentation from Java source code files.
7. jdb (java debugger):
Java debugger, which helps us to find errors in our programs.
These tools are applied to build and run application programs is illustrated in fig. The steps are listed
below
1. To create a Java program, we need to create a source code file using a text editor.
29
Java Programming Notes
CO4I
2. The source code is then compiled using the Java compiler Javac.
3. Then it is executed using the java interpreter java.
4. The Java debugger jdb is used to find errors, if any, in the source code.
5. A compiled Java program can be converted into a source code with the help of Java disassembler
javap.
Java API provides a large number of classes which are grouped into different packages according to
functionality. Following table shows the built in packages of java.
30
Java Programming Notes
CO4I
5 java.applet Classes for creating and implementing applets.
6 java.net Classes for networking. They include classes for communication with
local computers as well as with internet servers.
IF STATEMENTS:-
The if statement is a powerful decision makeing statement and is useful to control the flow of execution
of statement the if is the simplest one in decision statement. it is basically a two way decision statement
and is used in conjunction with an expression.
Syntax:-
if (condition)
{
//Statements ;
}
Example:-
class Abc
{
public static void main (String args[ ] )
{
int a=3, b=2 ;
if (a>b)
{
System.out.println (“a is greater”);
}
}
31
Java Programming Notes
CO4I
Flowchart :-
2) If else statement
To overcome from the drawback of if statement java supports If Else statement also.
Syntax:
if (condition)
{
//Statements 1;
}
else
{
//Statement 2 ;
}
a) If the condition is true then control transfer goes to the statement1 and it executes statement 1.
b) Otherwise (if condition is false) control transfer to the else part and else part executes statement 2.
Example:
class Abc
{
public static void main (String args[ ] )
{
int a=3, b=2 ;
if (a>b)
{
System.out.println (“a is greater”);
}
else
{
System.out.println(“b is greater”);
}
}
}
32
Java Programming Notes
CO4I
Flowchart:
3) Nested if statement
if (condition 1)
{
if (condition 2)
{
//Statement block 1;
}
else
{
//Statement block 2 ;
}
}
If condition 1 is true then control transfer to the inner if statement here, it again checks for condition 2 whether it is
true or false. If condition 2 is true is true then control transfer to the inner part of inner if statement. Otherwise (if
condition 2 is false) control transfer to out of loop of inner if statement. Otherwise (if condition 1 is false) control
transferred out of loop.
4) Else if ladder
When more than one condition arrived then we can use “if else if ladder” is used. Java supports if else if ladder on
the occasion of multiple condition.
Syntax:
if (condition 1)
{
//Statement 1 ;
}
else if (condition 2)
{
33
Java Programming Notes
CO4I
//Statement 2 ;
}
else
{
//Statement n ;
}
Working principle:-
1) In if-else-if ladder 1st of all if checks condition 1,if condition 1 is true then control transfer to the statement 1 and
it executes statement 1.
2) Otherwise (condition 1 id false) then, control transfer to the else part if part.
3) Now, It checks for condition 2 if it is true ctrl transfer to the statement 2 and executes statement 2.
4) Otherwise if(condition 2 is false) then, ctrl, transfer to the next else part.
5) Number of else if condition statements are depends on number of condition used.
6) If none of the condition is true then,ctrl directly transfer to the else part(by default)
Example
class Abc
{
public static void main (String args [])
{
int no=3;
if(no==1)
{
System.out.println(“one”);
}
else if (no==2)
{
System.out.println(“Two”);
}
else if(no==3)
{
System.out.println(“three”);
}
else
{
System.out.println(“Wrong choice”);
}
}
}
Java has a built-in multi way decision statement known as switch. It can be used instead of if, or nested
if...else. The complexity of the program increases as the number of alternatives increases when it is
designed with if...else for the multi path selection of decisions. This can be overcome with the switch
statement, as switch statement tests the value of a given variable (or expression) against a list of case
34
Java Programming Notes
CO4I
values and when a match is found, a block of statements associated with that case is executed. When the
switch is executed, the value of the expression is successively compared against the values value-1, value-
2. If a case is found whose value matches with the value of expression, then the block of statements that
follow the case are executed. The break statement at the end of each block signal the end of a particular
case and causes an exit from the switch statements & transferring the control to the statement following
switch.
Syntax:
switch(expression)
{
case value1:
block 1;
break;
case value2:
block 2;
break;
case value3:
block 3;
break;
.. .....
.......
default:
Default block;
break;
}
Example:
class test
{
public static void main(String args[])
{
int a,b,c;
a=10;
b=20;
char ch;
System.out.println("Enter your choice.a:add,b:sub,c:mul,d:div");
try
{
ch=(char) System.in.read();
switch(ch)
{
case 'a':
c=a+b;
System.out.println("Sum is"+c);
35
Java Programming Notes
CO4I
Break;
case 'b':
c=a-b;
System.out.println("Sub is"+c);
break;
case 'c':
c=a*b;
System.out.println("Mul is"+c);
break;
case 'd':
c=a/b;
System.out.println("Div is"+c);
break;
default:
System.out.println("Invalid choice");
}
catch(Exception e)
{}
}
}
Output:
Enter your choice.a:add,b:sub,c:mul,d:div
a
Sum is 30
It is possible to have a switch as part of the statement sequence of an outer switch. Even if the case
constants of the inner and outer switch contain common values, no conflicts will arise.
36
Java Programming Notes
CO4I
}
When the above code is compiled and executed, it produces the following result:
The for statement provides a compact way to iterate over a range of values. Programmers often refer to it
as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied.
The general form of the for statement can be expressed as follows:
When using this version of the for statement, keep in mind that:
The initialization expression initializes the loop; it's executed once, as the loop begins.
When the termination expression evaluates to false, the loop terminates.
The increment expression is invoked after each iteration through the loop; it is perfectly
acceptable for this expression to increment or decrement a value.
Example:
class ForDemo
{
public static void main(String[] args)
{
for(int i=1; i<=10; i++)
{
System.out.print("Count is: " + i +” “);
}
}
}
Output:
1 2 3 4 5 6 7 8 9 10
37
Java Programming Notes
CO4I
The basic for loop was extended in Java 5 to make iteration over arrays and other. This
newer for statement is called the enhanced for or for-each .
The for-each and equivalent for statements have these forms. The two basic equivalent forms are given,
depending one whether it is an array or an Iterable that is being traversed. In both cases an extra variable
is required, an index for the array and an iterator for the collection.
Syntax:
Example:
The while statement continually executes a block of statements while a particular condition is true. Its
syntax can be expressed as:
while (expression)
{
statement(s)
}
38
Java Programming Notes
CO4I
The while statement evaluates expression, which must return a boolean value. If the expression evaluates
to true, the while statement executes the statement(s) in the while block. The while statement continues
testing the expression and executing its block until the expression evaluates to false.
Example:
class WhileDemo
{
public static void main(String[] args)
{
int count = 1;
while (count < 11)
{
System.out.print("Count is: " + count +” “);
count++;
}
}
}
Output:
1 2 3 4 5 6 7 8 9 10
Do while Loop
The Java programming language also provides a do-while statement, which can be expressed as follows:
do
{
statement(s)
} while (expression);
The difference between do-while and while is that do-while evaluates its expression at the bottom of the
loop instead of the top. Therefore, the statements within the do block are always executed at least once, as
shown in the following DoWhileDemo program:
class DoWhileDemo
{
public static void main(String[] args)
{
int count = 1;
do
{
System.out.println("Count is: " + count);
count++;
} while (count < 11);
}
39
Java Programming Notes
CO4I
}
Output:
123456789
Nested Loop:
The placing of one loop inside the body of another loop is called nesting. When you "nest" two loops, the
outer loop takes control of the number of complete repetitions of the inner loop. While all types of loops
may be nested, the most commonly nested loops are for loops. Here we will see how nested loops are
used by taking the example of a pattern problem.
public class testFor
{
public static void main(String [] args)
{
for (int i=1; i<=9; i++)
{
for (int j=1; j<=i; j++)
{
System.out.print(j);
}
System.out.println();
}
}
}
Output:
1
12
123
1234
12345
123456
1234567
12345678
123456789
Break statement:
Early exit from a loop can done by using the break statement.
The break statement which is used in switch construct, can also be used within while,do or for
loops.
When the break statement is encountered inside a loop, the loop is immediately exited or
terminated and the program continues with the statement immediately following the loop.
In while and do loops, the break statement will terminate the control to go directly to next
statement after the loop.
40
Java Programming Notes
CO4I
In for loops, the break statement will terminate the control to go directly to next statement after
the loop.
The break statement has two forms: labeled and unlabeled. You can also use an unlabeled break to
terminate a for, while, or do-while loop, as shown in the following Break Demo program:
Example1:
41
Java Programming Notes
CO4I
else
System.out.println(num +" is not prime");
}
}
Output:
7 is prime
int flag=0;
for(int num=1;num<=20;num++)
{
for(int i=2;i< num-1;i++)
{
if(num % i==0)
{
flag=1;
break;
}
else
{
flag=0;
}
}
if(flag==0)
System.out.println(num +" is prime");
}
}
}
Output:
1 is prime
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
Continue statement:
The continue statement causes the loop to be continued with the next iteration after
skipping any statements in between.
42
Java Programming Notes
CO4I
Continue statement is used when it is necessary to skip a part of the body of the loop
under certain conditions.
The continue statement tells the compiler "skip or omit the statements mentioned and
continue with the next iteration."
In while and do loops, using the continue statement, the control to go directly to the test
condition and then continue the iteration process.
In the case of for loop, the increment section of the loop is executed before the test
condition is evaluated.
The continue statement skips the current iteration of a for, while , or do-while loop.
The unlabeled form skips to the end of the innermost loop's body and evaluates
the boolean expression that controls the loop.
Example1:
}
}
Output:
i=1
i=2
i=3
i=5
i=6
i=7
i=8
i=9
i=10
In java, It is possible to give label to a block of statements, which is valid java variable name. To give a
label to a loop, place it before the loop with a colon at the end
Example
43
Java Programming Notes
CO4I
LOOP1: for( )
{
...............
...............
}
An unlabeled break statement terminates the innermost switch, for, while, or do-while statement, but a
labeled break terminates an outer statement. The following program, BreakWithLabelDemo, is similar to
the previous program, but uses nested for loops to search for a value in a two-dimensional array. When
the value is found, a labeled break terminates the outer for loop (labeled "search"):
class BreakWithLabelDemo
{
public static void main(String[] args)
{
int a[][] = { { 32, 87, 3, 589 }, { 12, 1076, 2000, 8 }, { 622, 127, 77, 955 }};
int num = 12;
int i;
int j = 0;
boolean flag = false;
Found 12 at 1, 0
The last of the branching statements is the return statement. The return statement exits from the current
method, and control flow returns to where the method was invoked. The return statement has two forms:
one that returns a value, and one that doesn't. To return a value, simply put the value (or an expression
that calculates the value) after the return keyword.
44
Java Programming Notes
CO4I
return count;
The data type of the returned value must match the type of the method's declared return value. When a
method is declared void, use the form of return that doesn't return a value.
return;
45