Unit1 Java
Unit1 Java
Object Oriented Programming: The program is divided into number of small units called
object. The data and function are build around these objects. The data of the objects can be
accessed only by the functions associated with that object. The functions of one object can
access the functions of other object. In OOP the importance is given on data rather than
functions. The problems are divided into objects. Data and function are tied together. Data
hiding is possible. New data and functions can be easily loaded. Object can communicate
with each other using functions
Features
Emphasis is on data rather than the procedure.
Programs are divided into Objects.
Data structures are designed such that they characterize the objects.
Methods that operate on the data of an object are tied together in the data structure.
@Data hidden cannot be accessed by external functions.
Objects may communicate with each other through methods.
New data and methods can be easily added whenever necessary. @Follows bottom-up
approach in program design.
Object Oriented Programming is an approach that provides a way of modularizing by
creating partitioned memory area for both data and functions that can be used as
templates for creating copies of such modules on demand.
Basic concepts of OOP
Object:
An object is a software entity that combines a set of data with a set of
operations to manipulate the data.
An object is an instance of a class.
An object is known by a name and every object contains a state.
The state of is determined by the values of properties.
The state of an object can be changed by calling methods on it.
The sequence of states represent the behavior of the object.
Class:
A class is defined as the blue print of the object.
It serves as a plan or a template.
Description of a number of similar objects is also called a class.
A class is a user-defined data type.
A class contains two things i.e, properties and methods.
Encapsulation:
Encapsulation is one of the features of object-oriented methodology.
The process of binding the data and methods that operate on data into object to
hide them from the outside world is called as encapsulation.
Encapsulation is also known as data hiding. Data encapsulation is the striking
feature of a class.
Abstraction:
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 properties and
methods to operate on these properties.
Inheritance:
Inheritance is the way to adopt the characteristics of a class into another class.
Here we have two types of classes. One is base class(super class) and the other one is
derived class(sub class).
There exist a parent-child relationship among the classes.
A sub class inherits all the properties of a base class, in addition to this it can add its own
features.
Polymorphism:
Polymorphism means the ability to take more than one form.
An operation may exhibit different behavior in different instances.
The behavior depends up on the type of data used in the operation.
Consider the operation of addition for two numbers, the operation will generate sum, if the
operands were strings, then the operation will produce a third string by concatenation.
Dynamic Binding:
Binding refers to the linking of method call to the method.
Dynamic Binding means that the code associated with a method call is not known until the
time of the call at runtime.
It is associated with polymorphism and inheritance.
Message Passing:
An object oriented program consists of a set of objects that communicate with each other.
The process of programming in an object-oriented language involves the following basics.
a) Creating classes that define object and their behavior.
b) Creating object from class definitions.
c) Establishing communication between objects. Objects communicate with one-another by sending
and receiving information much the same way as people pass messages to one-another is called
message passing.
Message passing involves specifying the name of the object, the name of the
method(message) and the information to be sent. Consider the following example:
information<>message ; name<>Object ; salary<>Employee.salary(name); Employee
Benefits
1. Through inheritance we can eliminate redundant code and extend the use of
existing classes.
2. We can build programs from the standard working modules that communicate
with one another rather than having to start writing the code from scratch.
3. The principle of data hiding helps the programmer to build secure programs
that cannot be invaded by code in other parts of the program.
4. It is possible to have multiple objects to co-exist without any interference.
5. It is possible to map objects in the program domain to those objects in the
program.
6. It is easy to partition the work in a project based on objects.
7. The data centered design approach enables us to capture more details of a
model in an implementation.
8. Systems can be easily upgraded from small to large systems.
9. Message passing techniques for communication between objects make the
interface descriptive with external systems much simpler.
Applications
2. Platform Independent and portable: Java supports the feature portability. Java
programs can be easily moved from one computer system to another and anywhere.
Changes and upgrades in operating systems, processors and system resources will not
force any alteration in Java programs. This is reason why Java has become a trendy
language for programming on Internet which interconnects different kind of systems
worldwide. Java certifies portability in two ways. First way is, Java compiler generates
the bytecode and that can be executed on any machine. Second way is, size of
primitive data types are machine independent.
3. Object- oriented: Java is truly object-oriented language. In Java, almost everything is
an Object. All program code and data exist in objects and classes. Java comes with an
extensive set of classes; organize in packages that can be used in program by
Inheritance. The object model in Java is trouble-free and easy to enlarge.
4. Robust and secure: Java is a most strong language which provides many securities
to make certain reliable code. It is designed as garbage –collected language, which helps
the programmers virtually from all memory management problems. Java also includes
the concept of exception handling, which detain serious errors and reduces all kind of
threat of crashing the system. Security is an important feature of Java and this is the
strong reason that programmer use this language for programming on Internet. The
absence of pointers in Java ensures that programs cannot get right of entry to memory
location without proper approval.
5. Distributed: Java is called as Distributed language for construct applications on
networks which can contribute both data and programs. Java applications can open
and access remote objects on Internet easily. That means multiple programmers at
multiple remote locations to work together on single task.
6. Simple and small: Java is very small and simple language. Java does not use
pointer and header files, goto statements, etc. It eliminates operator overloading
and multiple inheritance.
The Java Development kit comes with a collection of tools that are used for
developing and running java programs. They include:
Applet Viewer: Enable us to run java applets (without actually using a java
compatible browser)
Java: Java interpreter, which runs applets and applications by reading and
interpreting byte code files
Javac: The java compiler, which translates java source code to byte code files
that interpret, can understand.
Javadoc: Creates HTML format documentation from java source code files
Javap: Java disassembler, which enables us to convert byte code files into program
description.
2. Web applets: Applets are small java programs developed for Internet applications.
An applet located on remote computer can be downloaded via Internet and executed
on a local computer using java enabled browser.
Stand alone programs can read and write files and perform certain operations that
applet cannot do. An applet can only run within a web browser.
Simple Java Program
This program defines a class called ―FirstProgram. A class is an object oriented
term. It is designed to perform a specific task. A Java class is defined by its class
name, an open curly brace, a list of methods and fields, and a close curly brace.
The line ―public static void main (String [] args) - shows where the program
will start running. The word main means that this is the main method –
The public keyword is an access modifier. When a class member is preceded by
public, then that member can be accessed by code outside the class in which it is
declared.
The keyword static allows main( ) to be called before an object of the class has
been created. This is necessary because main( ) is called by the JVM before any
objects are made.
The keyword void simply tells the compiler that main( ) does not return a value.
In main( ) there is only one parameter, String args[ ], which declares a
parameter named args. This is an array of objects of type String. (Arrays are
collections of similar objects.) Objects of type String store sequences of
characters. In this case, args receives any command-line arguments present when
the program is executed.
Identifiers are programmer-created tokens. They are used for naming classes,
methods, variables, objects, labels, packages and interfaces in a program. Java
identifiers follow the following rules:
They can have alphabets, digits, and the underscore and dollar sign
characters.
They must not start with a digit.
Uppercase and lowercase letters are individual.
They can be of any length.
Identifier must be meaningful, easily understandable and descriptive.
Literals
Literals are a sequence of characters (digits, letters and other characters)
that characterize constant values to be stored in variables. Java language
specifies five major types of literals are as follows:
1. Integer literals
2. Floating point literals
3. Character literals
4. String literals
5. Boolean literals
Operator
Java carries a broad range of operators. An operator is symbols that specify operation to be
performed may be certain mathematical and logical operation. Operators are used in programs
to operate data and variables. They frequently form a part of mathematical or logical
expressions. Categories of operators are as follows:
1. Arithmetic operators
2. Logical operators
3. Relational operators
4. Assignment operators
5. Conditional operators
6. Increment and decrement operators
7. Bit wise operators
Separator
Separators are symbols. It shows the separated code.
Java Statements
Command line arguments are parameters that are supplied to the application
program at the time of invoking its execution. They must be supplied at the time of
its execution following the file name.
In the main () method, the args is confirmed as an array of string known as string
objects. Any argument provided in the command line at the time of program
execution, are accepted to the array args as its elements. Using index or
subscripted entry can access the individual elements of an array. The number of
element in the array args can be getting with the length parameter.
class Add
{
public static void main(String args[])
{
int a=Integer.parseInt(args[0]);
int b=Integer.parseInt(args[1]);
int c=a+b;
System.out.println(“Addition is=” +c);
}
Output:
}
c:\javac Add.java
c:\java Add 5 2->Command Lime
arguments
Addition is=7
Constants
Constant means fixed value which cannot be changed at the time of execution of
program. In Java, there are two types of constant as follows:
Numeric Constants
a. Integer constant
b. Real constant
Character Constants
a. Character constant
b. String constant
a) Decimal integer b) Octal integer c) Hexadecimal
Embedded spaces, It allows any integer
commas and sequence of ‘F‘ or ’a‘ to ‘f‘ (‘A‘ to
characters are not numbers or digits ‘F‘ stands for the
allowed in between from 0 to 7 with numbers ‘10‘ to ‘15‘)
digits. leading 0 and it is it is called as
called as octal Hexadecimal integer.
integer.
For example: For example:
23 411 For example: 0x7
7,00,000 011 00X
00 0A2B
17.33
0425
a. Real Constant b. Character c. String
It allows us fractional Constant Constant
data and it is also It allows us single It allows us the
called as floating character within series of characters
point constant. It is pair of single coute. within pair of
used for percentage, double coute.
height and so on. For example:
‘A‘ For example:
For example: ‘7‘ “WELCOME”
‘\‘ “END OF
0.0234
PROGRAM”
0.777 “BYE …BYE”
-1.23 “A”
Symbolic constant
There are many things which is requires repeatedly and if we want to make changes
then we have to make these changes in whole program where this variable is used.
For this purpose, Java provides ‘final‘keyword to declare the value of variable as
follows:
Syntax:
final type Symbolic_name=value;
For example:
For declaring PI value:
final float PI=3.1459;
Backslash character constant
Variables
Variables are labels that express a particular position in memory and connect it
with a data type.
The first way to declare a variable: This specifies its data type, and reserves
memory for it. It assigns zero to primitive types and null to objects.
dataType variableName;
The second way to declare a variable: This specifies its data type, reserves
memory for it, and puts an initial value into that memory. The initial value must be
of the correct data type.
dataType variableName = initialValue;
The first way to declare two variables: all of the same data type, reserves memory for
each.
It is represent single and double precision numbers. The float type is used
for single precision and it uses 4 bytes for storage space. It is very useful
when we require accuracy with small degree of precision. But in double
type, it is used for double precision and uses 8 bytes of starage space. It is
useful for large degree of precision.
Character data type: It is used to store single character in memory. It uses 2
bytes storage space.
Class variables are global to a class and belong to entire set of objects that class
creates. Only one memory location is created for each class variable.
Variables declared and used inside methods are called local variables. They are not
available outside the method definition.
Standard Default Values
Operators
When evaluation of two numbers is performed depending upon their relation, assured
decisions are made. The value of relational expression is either true or false.
If A=7 and A < 10 is true while 10 < A is false. Following table shows the details of
operators.
Logical operators
When we want to form compound conditions by combining two or more
relations, then we can use logical operators.
Assignment Operators
Assignment Operators is used to assign the value of an
expression to a variable and is also called as Shorthand
operators.
Examples:
person. age;
person. salary();
The evaluation process includes two left to right passes through the expression. During
the first pass, the high priority operators are applied as they are encountered. During the
second pass, the low priority operators are applied as they are encountered.
Example
Type Conversion in Assignment
Example:
double x, y;
//…
(int ) (x/y) -> x and y are double but result is converted to int.
Mathematical Functions
Mathematical functions such as cos, sin, log, etc. are frequently used in an analysis of
real life problems. Java supports these basic math functions through Math class defined in
the java.lang package.
Using I/O
Java input and output are based on the use of streams, or sequences of bytes that travel
from a source to a destination over a communication path.
If a program is writing to astream, you can consider it as a stream’s source. If it is reading
from a stream, it is the stream’s destination. The communication path is dependent on
the type of I/O being performed.
It can consist of memory-to-memory transfers, a file system, a network, and other forms
of I/O.
Streams are powerful because they abstract away the details of the communication path
from input and output operations. This allows all I/O to be performed using a common set
of methods. These methods can be extended to provide higher-level custom I/O
capabilities.
Three streams given below are created automatically:
System.out - standard output stream
System.in - standard input stream
System.err - standard error
Stream
Stream is the logical connection between Java program and file.
Stream is basically a sequence of bytes, which has a continuous flow between Java
programs and data storage. All streams behave in the same manner, even if the
actual physical devices to which they are linked differ. Thus, the same I/O classes and
methods can be applied to any type of device.
An input stream can abstract many different kinds of input: from a disk file, a
keyboard, or a network socket.
An output stream may refer to the console, a disk having every part of your code
understand the difference between a keyboard and a network, file, or a network
connection.
Java provides many input and output stream classes which are used to read and write.
Streams are of two types.
1. Byte Stream
2. Character Stream
Byte stream Classes
Used in the input and output of byte. We do this with the help of different Byte stream
classes.
Groups
InputStream Classes - These classes are subclasses of an abstract
class,InputStream and they are used to read bytes from a source(file,
memory or console).
Character streams are defined by using two class hierarchies. At the top
are two abstract classes, Reader and Writer. These abstract classes handle
Unicode character streams. Java has several concrete subclasses of each of
these. The character stream classes are shown in Table.
The abstract classes Reader and Writer define several key methods that the
other stream classes implement. Two of the most important methods are
read() and write(), which read and write characters of data, respectively.
These methods are overridden by derived stream classes.
The Predefined Streams
System.err refers to the standard error stream, which also is the console by default.
However, these streams may be redirected to any compatible I/O device.
Syntax:
If(Test condition)
{statement block;}
Statement-x;
Syntax:
If(Test expression)
{true block
Statement(s)}
Else
{false block
Statement(s)}
If the test expression is true, then true-block Statements(s) are executed; otherwise
false-block Statements(s) are executed.
Nested if---else statement
Syntax:
If(Test expression 1)
{If(Test condition 2)
{Statements-1}
Else
{Statements-2}
Else
{Statements-3}
Statement x
If the test expression -1 is true then it will go to condition2. If the condition2 is true
then statement -1 will be executed otherwise statement-2 will be executed. If the test
expression -1 is false then statement-3 will be executed. In both cases the statement-x
will always executed.
else if ladder
Syntax:
if (condition1)
Statement-1;
else if (condition2) Here the conditions are evaluated from top to
downwards. As soon as true condition is found
Statement-2; the statements associated with it is executed
else if (condition3) and the control is transferred to the statement
– x by skipping the rest of the ladder. When all
Statement-3; ……………………… ……... conditions become false, the final else
else if (condition n) containing the default- statement will be
executed.
Statement-n;
Else
default – Statement
Statement - x
Switch statement