CH-1 Java Introduction To Java Programming
CH-1 Java Introduction To Java Programming
Programming
Procedural Programming
It is a programming language that follows a step-by-step approach to break down a
task into a collection of variables and routines through a sequence of instructions.
During the execution of a program,one can call any given procedure at any point either
by other procedures or by itself.
Object-Oriented Programming
Object-Oriented Programming as programming model that follows the concept of
objects.
OOP treats data as a critical element in the program development and does not allow
it to flow freely around the system.
It ties data more closely to the functions that operate on it and protects it from
unintentional modification by other functions.
Basic Concepts of Object-Oriented Programming
1.Objects and Classes.
3.Inheritance.
4.Polymorphism.
Objects and Classes
Objects are the basic runtime entities in an object-oriented system.They may
represent a person,a place,a bank account that the program may handle.
Example:
Data Abstraction and Encapsulation
The wrapping up of data and methods into a single unit is known as encapsulation.
The data is not accessible to the outside world and only those methods,which are
wrapped in the class,can access it.This insulation of the data from direct access by
the program is called data hiding.
Abstraction refers to the act of representing essential features without including the
background details or explanations.
Inheritance
Inheritance is the process by which objects of one classacquire the properties of
objects of another class.Inheritance supports the concept of hierarchical
classification.
It focuses on the process and functions. It focuses on the data and classes.
3.Object-Oriented
5.Distributed.
10.Ease of Development
3.Bytecodes are not machine instructions and therefore the second stage,Java
interpreter generates machine code that can be directly executed by the machine that
is running the java program.
Changes and upgrades in operating system,processors and system resources will not
force any changes in the Java programs.
All program code and data reside within objects and classes.
Java applications can open and access remote objects on Internet as easily as they
can do in a local system.
Java does not use pointers ,preprocessor header files,goto statement and many
others.
To make the language look familiar to the existing programmers,it was modeled on
C and C++ code.
Multithreaded and Interactive
Multithreaded means handling multiple tasks simultaneously.
Java supports multithreaded programs.This means that we need not wait for the
application to finish one task before beginning another.
High Performance
Java performance is impressive for an interpreted language,mainly due to the use of
intermediate bytecode.
Memory utilization is reduced by sharing data in the shared archive among multiple
JVM processes.
Monitoring and Manageability
Java supports number of APIs such as JVM Monitoring and Management
API,Logging,Monitoring and Management Interface.
JVM Architecture
JVM is the core of the Java ecosystem, and makes it possible for Java-based software
programs to follow the "write once, run anywhere" approach. You can write Java code on
one machine, and run it on any other machine using the JVM.
Java uses a combination of both techniques i.e Compilation and Interpretation. Java code
is first compiled into byte code to generate a class file. This class file is then interpreted by
the Java Virtual Machine for the underlying platform. The same class file can be executed
on any version of JVM running on any platform and operating system.
The JVM consists of three distinct components:
1. Class Loader
2. Runtime Memory/Data Area
3. Execution Engine
Class Loader
● When you compile a .java source file, it is converted into byte code as a .class file.
When you try to use this class in your program, the class loader loads it into the main
memory.
● The first class to be loaded into memory is usually the class that contains the main()
method.
● There are three phases in the class loading process: loading, linking, and
initialization.
Runtime Memory/Data Area
Execution Engine
● Once the bytecode has been loaded into the main memory, and details are available
in the runtime data area, the next step is to run the program. The Execution Engine
handles this by executing the code present in each class.
● However, before executing the program, the bytecode needs to be converted into
machine language instructions. The JVM can use an interpreter or a JIT compiler for
the execution engine.
Understanding Working of Java
Java is a general-purpose,object oriented programming language.
1.Standalone applications.
2.Web applets.
Standalone applications are programs written in Java to carry out certain tasks on a
standard local computer.
Executing a standalone Java program involves two steps:
}
Class Declaration
The first line SampleOne declares a class,which is an object-oriented construct.
SampleOne is a Java identifier that specifies the name of the class to be defined.
The Main Line
The third line
public static void main(String args[])
Defines a method named main.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 any number of classes but only one of them must include a main method to initiate the
execution.
This 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 accessible to all other classes.
static:which declares this method as one that belongs to the entire class and not a part of any objects
of the class.The main method must always be declared as static since interpreter uses this method
before any objects are created.
void:The type modifier void states that the main method does not return any value.
The Output Line
The only executable statement in the program is
System.out. println(“Welcome to Java Programing”);
This is similar to the printf() statement in 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.
The method println always appends a newline character to the end of the string.This
means that any subsequent output will start on a new line.Every Java statement
must end with a semicolon.
Java Program Structure
Documentation Section
The documentation section comprises a set of comment lines giving the name of the
program,the author and other details,which the programmer would like to refer to at
a later stage.Comments must explain why and what of classes and how of
algorithms.
2.multiline comments(/*....*/)
3.documentation comment(/**.......*)
Package Statement
The first statement allowed in a Java file is a package statement.This statement
declares a package name and informs the compiler that the classes defined here
belong to this package.
Example:package student;
import java.io.*;
This statement instructs the interpreter to load the all classes contained in io package.
Using import statements,we can have access to classes that are part of other named packages.
Interface Statements
Class Definitions
A Java program may contain multiple class definitions.Classes are the primary and essential elements of a Java
program.The number of classes used depends on the complexity of the program.
Java standalone program requires a main method as it starting point.The main method creates objects of various classes
and establishes communication between them.On reaching the end of main,the program terminates and the control
passes back to the operating system.
Data Types
Every variable in Java has a data type.Data type specify size and types of values
that can be stored. Data types in Java
Floating-
Integer point Interface
Character Boolean
Integer Types:Integer types can hold whole numbers such as 123,-96 and 5639.
The size of the values that can be stored depends on the integer data type.Java
supports four types of integers.
Integer
Byte Long
Short INT
Floating PointTypes
Floating Point types to hold numbers containing fractional part such as 27.59.There
are two kinds of floating point storage in Java:
Floating Point
Float(Single-precision Double(double
Numbers) precision numbers)
Character Type
Boolean Type
Boolean type is used when we want to test a particular condition during the
execution of the program.There are only two values that a boolean type can
take:true or false.Boolean type is denoted by the keyword boolean and uses only one
bit of storage.
Declaration of Variables
In java,variables are the names of storage locations.After designing suitable variable
names,we must declare them to the compiler.Declaration does three things:
1.It tells the compiler what the variable name is.
2.It specifies what type of data the variable will hold.
3.The place of declaration decides the scope of the variable.
A variable must be declared before it is used in the program.Variable can be used to store
a value of any data type.
General Syntax:
type variable1,variable2…………………..variableN;
Examples:int count;
Float x,y;
Type Casting
Type casting is helpful in situations where there is a need to store a value of one
type into a variable of another type.If the two types are compatible,then Java will
perform the conversion automatically.
However,not all types are compatible,and thus not all type conversions are implicitly
allowed.For instance,there is no automatic conversion defined from double to byte.
To create a conversion between two incompatible types,you must use a cast.A cast is simply an
explicit type conversion.
Syntax is :
type variable1=(type)variable2;
Example:
int a;
byte b;
b=(byte)a;
Arrays
An array is a group of contiguous or related data items that share a common name.
For example,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 brackets after the array
name.
For example:salary[10];
Represents the salary of the 10th employee.The complete set of values is referred to as an array,the
individual values are called elements.
The ability to use a single name to represent a collection of items and to refer to an item by specifying the
item number enables us to develop concise and efficient programs.
Creating an Array
Arrays must be declared and created in the computer memory before they are used.
1.Declaring an array
1.type arrayname[];
2.type [] arrayname;
Example:
int number[ ];
int [ ] marks;
Creation of Arrays
After declaring an array,we need to create it in the memory.Java allows us to create
arrays using new operator.
Syntax:
arrayname=new type[size];
Example:
number=new int[5];
Initialization of Arrays
The final step is to put values into the array created.This process is known as
Initialization.
Syntax:
arrayname[subscript]=value;
Example:
number[0]=35;
number[1]=40;
Java creates arrays starting with the subscript of 0 and ends with a value one less than
the size specified.
We can also initialize arrays automatically in the same way as the ordinary variables
when they are declared as shown below:
Example:
The array initializer is a list of values separated by commas and surrounded by curly
braces.No arraysize is specified.The compiler allocates enough space for all the
elements specified in the list.
Two-dimensional Arrays
There are some situations where table of values will have to be stored.
Example:
int table[2][3]={0,0,0,1,1,1};
Initializes the elements of the first row to zero and the second row to one.The
initialization is done row to row.
Multidimensional Arrays
Java treats multidimensional array as “arrays of arrays”.
Example:
x[0]=new int[2];
x[1]=new int[4];
x[2]=new int[3];
Operators:
Java supports a rich set of operators.
An operator is a symbol that tells the computer to perform certain mathematical or logical
manipulations.
Java Operators are classified into a number of related categories:
1.Assignment Operators.
2.Comparison Operators.
3.Bitwise Operators.
4.Arithmetic Operators.
5.Shifting Operators.
Arithmetic Operators:
Arithmetic operators are used to construct mathematical expressions.
a-b a+b
a*b a/b
a%b -a*b
When both the operands in a single arithmetic expression such as a+b are integers,the expression is called an
Integer expression and the operation is called integer arithmetic.Integer arithmetic always yields an integer
value.
Real Arithmetic
Mixed-Mode Arithmetic:
When one of the operands is real and the other is integer,the expression is called a mixed-mode arithmetic
expression.
Example:
Java has a set of ‘shorthand’ assignment operators which are used in the form
v op=exp;
Example: x+=y;
Comparison Operators(Relational Operators)
We can compare two quantities and depending on their relation,take certain
decisions.
For example,we may compare the age of two persons or the price of two items.These
comparison are done with the help of relational operators.
== Is equal to
!= Is not equal to
Bitwise Operator
Bitwise operators are used for manipulating of data at values of bit level.
These operators are used for testing the bits, or shifting them to the right or left.
Operator Meaning
! Bitwise OR
^ Bitwise exclusive OR
~ One’s complement
The if-then statement is the most basic of all the control flow statements. It tells your program to execute a certain
section of code only if a particular test evaluates to true.
void applyBrakes() {
if (isMoving){
currentSpeed--;
}
The if-then-else Statement
The if-then-else statement provides a secondary path of execution when an "if" clause evaluates to false. You
could use an if-then-else statement in the applyBrakes method to take some action if the brakes are applied when
the bicycle is not in motion.
void applyBrakes() {
if (isMoving) {
currentSpeed--;
} else {
}
Switch Statement
The switch statement can have a number of possible execution paths. A switch works with the byte, short, char, and int primit ive data
types.
A built- in multiway decision statement known as switch,which tests the value of a given variable.
switch(expression)
case value-1:
block-1
break;
case value-2:
block-2
break;
---------------
----------------
default:
Default-block
break;
}
Decision Making and Looping
A computer is well suited to perform repetitive operations.It can do it tirelessly for
10,100 and even 10000 times.Every computer language must have features that
instruct a computer to perform such repetitive tasks.The process of repeatedly
executing a block of statements is known as looping.The statements in the block may
be executed any number of times from zero to infinite number.
In looping,a sequence of statements are executed until some conditions for the
termination of the loop are satisfied.A program loop therefore consists of two
segments,one known as the body of the loop and the other known as the control
statement.The control statements tests certain conditions and then directs the
repeated execution of the statements contained in the body of the loop.
Depending on the position of the control statement in the loop,a control structure may be
classified either as the entry-controlled loop or as exit-controlled loop.
In the entry-controlled loop,the control conditions are tested before the start of the loop
execution.If the conditions are not satisfied,then the body of the loop will not be executed.
In the case of an exit-controlled loop,the test is performed at the end of the body of the
loop and therefore the body is executed unconditionally for the first time.
A looping process,would include the following four steps:
1.Setting and initialization of a counter.
2.Execution of the statements in the loop.
3.Test for a specified condition for execution of the loop.
4.Incrementing the counter.
The Java language provides for three constructs for performing loop operations.
They are:
1.While construct.
2.do construct.
3.for construct.
While statement
The simplest of all the looping structures in Java is the while statement.The basic format of the while statement is
Initialization:
while(test condition){
Body of the loop
}
The while os an entry-controlled loop statement.The test condition is evaluated and if the condition is true,then the
body of the loop is executed.After execution of the body,the test condition is once again evaluated and if it is
true,the body is executed once again.This process of repeated execution of the body continues until the test
condition finally becomes false and the control is transferred out of the loop.On exit,the program continues with
the statement immediately after the body of the loop.
The body of the loop may have one or more statements.The braces are needed only if
the body contains two or more statements.However,it is a good practice to use braces
even if the body has only one statement.
2.do statement.
The while loop construct makes a test condition before the loop is
executed.Therefore,the body of the loop may not be executed at all if the condition is
not satisfied at the very first attempt.
One some occasions,it might be necessary to execute the body of the loop before the
test is performed.Such situations can be handled with the help of the do statement.
General Syntax:
Initialization;
do
{
Body of the loop
}while(test condition);
On reaching the do statement,the program proceeds to evaluate the body of the loop
first.At the end of the loop,the test condition in the while statement is evaluated.If the
condition is true,the program continues to evaluate the body of the loop once
again.This process continues as long as the condition is true.When the condition
becomes false,the loop will be terminated and the control goes to the statement that
appears immediately after the while statement.
Since the test condition is evaluated at the bottom of the loop,the do….while
construct provides an exit-controlled loop and therefore the body of the loop is
always executed at least once.
3.For statement.
The for loop is another entry-controlled loop that provides a more concise loop
control structure.The general form of the for loop is
for(initialization;test condition;incr/decr)
{
Body of the loop
}
The execution of the for statement is as follows:
1.Initialization of the control variables is done first,using assignment statements such as
i=1 or count =0.The variables i and count are known as loop-control variables.
2.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 when the loop will exit.If the
condition is true,the body of the loop is executed,otherwise the loop is terminated and the
execution continues with the statement that immediately follows the loop.
3.When the body of the loop is executed,the control is transferred back to the for
statement after evaluating the last statement in the loop.Now,the control variable is
incremented using an assignment using an assignment statement such as i=i+1 and the
new value of the control variable is again tested to see whether it satisfies the loop
condition.If the condition is satisfied,the body of the loop is again executed.This process
continues till the value of the control variable fails to satisfy the test condition.