You are on page 1of 23

Unit-I

Fundamentals of Object Oriented Programming :


Introduction :
Object Oriented Programming is a new way of approaching the job of programming.
Approaches to programming have changed dramatically since the invention of the computer
in order to accommodate the increasing complexity of programs.
Object Oriented Programming takes the best ideas of structured programming and
combines them with powerful, new concepts that encourage you to look at the task of
programming in a new light. Object Oriented Programming allows you to easily decompose
a problem into subgroups of related parts. Then you can translate these subgroups into selfcontained units called objects. All Object Oriented Programming language have three things
in comm. These are objects, inheritance and polymorphism.
Differentiate between object oriented programming languages and structured Programming
languages and state the advantages and disadvantages for using Object oriented
programming languages.
In structured or procedural languages a program consists of a series of Procedures /
functions, and steps all tied together in a form of algorithm. Procedures / Functions are
grouped together to from modules, the building block of structured Programming. In
structured programming the problem is viewed as a sequence of things to be done
such as reading, calculating and orienting. A number of functions are written to
accomplish these tasks.
Features of structured programming language:

Emphasis is on algorithm rather than data.


Programs are divided into individual procedures (functions) that perform discrete
tasks.
Procedures are independent of each other as far as possible.
Procedures have their own local data and processing logic.
Most of the functions share global data and data move openly from function to
function.
Employs top-down approach in program design.
Projects can be broken up into modules and programmed independently.
Maintenance of a large software system is tedious and costly.

In object oriented programming the problem is decomposed into a number of enuties


called objects and then builds data and functions around these objects. OOP treats
data as a critical element in the programming development and dose 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 accidental modifications from outside functions.

Prepared by:

B.Rammurthy Naidu M.C.A,


Placement Incharge, Web Master, Assistant Professor,
Department of Computer Science,
GVP Degree College(A).

Features of object oriented programming language:

Emphasis is on data rather than procedure.


Programs are divided into what are known as objects.
Data structures are designed such that they characterize the objects.
Functions that operate on the data of an object are tied together in the data
structure.
Data is hidden and cannot be accessed by external functions and objects may
communicate with each other through functions.
Follows bottom-up approach in program design.

Advantages of OOP:

Through inheritance, we can eliminate redundant code and extend the use of
existing.
Information hiding and data abstraction increase reliability and helps the
programmer to build secure programs that cannot be invaded by code in other
parts of the program.
Dynamic binding increases flexibility by permitting the addition of a new class
of objects without having to modify the existing code.
Inheritance coupled with dynamic binding enhances the reusability of a code
thus increasing the productivity of a programmer.
Many OO languages provide a standard class library that can be extended by
the users thus saving a lot of coding and debugging effort.
If is possible to have multiple instances of an object to co-exist without any
interference.
It is easy to partition the work in a project based on objects.

DISADVANTAGES:

It is not suitable for small programs where functions can give more accurate and
quick results
It requires complicated spadework before OOP becomes fully operative
Creation of object libraries and its maintenance is a tough job.
Requires the master over the software engineering and programming
methodologies.
Benefits only in long run while managing large software projects.
Procedure Oriented Programming
Object Oriented Programming
Emphasis is on doing things
Emphasis is on data rather than procedures
Programs are divided into small things Programs are divided into what are known as
known as functions
Objects
Data move openly around the system from Data is hidden and cannot be accessed by
function to function
external functions
Debugging Process is very difficult
Debugging Process is very easy
Follows top-down approach in program Follows bottom-up approach in program
design
design
Most of the functions share global data
The data of an object can be accessed only by
the functions that are associated with it
Prepared by:

B.Rammurthy Naidu M.C.A,


Placement Incharge, Web Master, Assistant Professor,
Department of Computer Science,
GVP Degree College(A).

CONCEPTS OF OBJECT ORIENTED PROGRAMMING


The various concepts of OOP are

Objects
Classes
Data abstraction and encapsulation
Inheritance
Polymorphism
Dynamic binding
Message passing

Object: Objects are the basic run-time entities in an object-oriented system. They may
represent a person, a place, a bank account, a table of data or any item that the
program has td handle. Objects take up space in the memory and have an associated
address like a record in Pascal or a structure in c.
Classes: Classes are user-defined data types and behave like the built-in types of a
programming language. The entire set of data and code of an object can be made a
user-defined data type with the help of a class. In fact, objects are variables of the
type class. Each object is associated with the data of type class with which they are
created. A class is a collection of objects of similar type. For example mango, apple
and orange are members of the class fruit.
Fruit mango;
Will create an object mango belonging to the class fruit.
Data Abstraction and Encapsulation: The wrapping up of data and functions into a
single unit is known as encapsulation. Data abstraction is done using the classes. The
data is not accessible to the outside world and only those functions, which are
wrapped in the class, can access it. This insulation of the data from direct access by
the program is called data hiding or information hiding.
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 attributes and functions to operate on these attributes. They
encapsulate all the essential properties of the objects that are to be created.
Inheritance: Inheritance is the process by which objects of one class acquire the
properties of objects of another class. It supports the concept 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. The idea behind this sort of division is that each derived class shares
common characteristics with the class form which it is derived. Inheritance provides the idea
of reusability.
There are Five types of Inheritance
a) Single
b) Multiple
c) Multilevel
d) Hierarchical
e) Hybrid
Prepared by:

B.Rammurthy Naidu M.C.A,


Placement Incharge, Web Master, Assistant Professor,
Department of Computer Science,
GVP Degree College(A).

Single inheritance: Derivation of a class from only one base class is called single
inheritance.
Multiple inheritance: Derivation of a class from two or more classes is called multiple
inheritances.
Hierarchical inheritance: Derivation of several classes from a single base class i.e. the traits
of one class may be inherited by more than one class is called hierarchical inheritance.
Multilevel inheritance: Derivation of a class from another derived class is called multilevel
inheritance.
Hybrid inheritance: Derivation of a class involving more than one form of inheritance is
known as hybrid inheritance.
Multipath inheritance: Derivation of a class from other derived classes, which are derived
from the same base class, is called multipath inheritance.
A

B
SingleInheritance

MultipleInheritance

Hierarchical
Inheritance

A
A

C
Multilevel Inheritance

D
Hybrid Inheritance

Polymorphism: Polymorphism, a Greek term, means the ability to take more than one form.
The following are the different ways of achieving Polymorphism in Java.

Prepared by:

B.Rammurthy Naidu M.C.A,


Placement Incharge, Web Master, Assistant Professor,
Department of Computer Science,
GVP Degree College(A).

polymorphism

Compile-time polymorphism
Or
static/early binding

Run-time polymorphism
Or
Dynamic/Late binding

The process of making an operator to exhibit different behaviors in different instances is


known as operator overloading . For example consider the operation of addition For two
numbers the operation will generate a sum. If the operands were strings then the operation
would produce a third string by concatenation.
Using a single function name to perform different types of tasks is known as function
overloading.
Dynamic binding: Binding refers to the linking of a procedure call to the code to be
executed in response to the call. Dynamic binding also known as late binding means
that the code associated with a given procedure call is not known until the time of
the call at run-time. It is associated with polymorphism and inheritance .
Message Passing : An object oriented program consists of a set of objects that
communicate with each other. A message for an object is a request for execution of
a procedure and therefore will invoke a function in the receiving object that generates
the desired result. It involves specifying the name of the object, the name of the
function and the information to be sent.
For example
Employee. Salary(name);
Employee is object, salary is message and name is information.
APPLICATIONS OF OOPS
Real time Systems
Simulation and modeling
Object Oriented databases
Hypertext, hypermedia and expertext
Artificial Intelligence
Neural works
CIM/CAM/CAD systems
Office automation systems
Decision support
Parallel Programming

Prepared by:

B.Rammurthy Naidu M.C.A,


Placement Incharge, Web Master, Assistant Professor,
Department of Computer Science,
GVP Degree College(A).

JAVA FUNDAMENTALS
JAVA EVOLUTION:
Java was developed by a team of computer professionals under the guidance of James
Gosling at sun Microsystems in 1991. Java was designed for the development of software for
consumer electronic devices.
JAVA FEATURES
Compiled and Interpreted
Java combines both these approaches thus making java a two-stage system. First, Java
compiler translates source code into what is known as bytecode instructions. Bytecode 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.
Platform-Independent and Portable
Java is compiled to an intermediate form called Java Byte-Code or simply byte code. A Java
program never really executes immediately after compilation on the host machine. Rather,
this special program called the Java Interpreter or Java Virtual Machine reads the bytecode,
translates into the corresponding host machine instructions and then executes the machine
instruction. A java program can run on any computer system for which a JVM and some
library routines are installed. Because of Platform Independence Java programs can be
portable from a mini computer up to a super computer irrespective of H/W requirements and
OS Base.
Object-Oriented
Java is one of the Pure Object Oriented Programming Language where every construction of
the program should be written under the implementation of class which is the basic part of
OOPS.
Robust and Secure
Robustness is measured with the help of 2 concepts 1) Memory Management 2) Exception
Handling
In traditional applications, the programmer is responsible for both allocations and
deallocation of memory. In Java, Memory allocation is controlled by JVM where object
creation is done by the user deallocation is taken by Garbage Collector
In C,C++ error handling is done manually even before running the program. If any run-time
error comes the program is in inconsistent state which leads to memory leak. Java supports
pure exception handling which guards the program from abnormal situations.
Java is intended to work in networked and distributed environments by providing security.
Security becomes an important issue for a language that is used for programming on Internet.
Java Systems not only verify all memory access but also ensures that no viruses are
Prepared by:

B.Rammurthy Naidu M.C.A,


Placement Incharge, Web Master, Assistant Professor,
Department of Computer Science,
GVP Degree College(A).

communicated with an applet. The absence of pointers in Java ensures that programs cannot
gain access to memory locations without proper authorization.
Distributed
Java is designed as a distributed language for creating applications on networks. It has the
ability to share both data and programs. Java applications can open and access remote objects
on Internet as easily as they can do in a local system. This enables multiple programmers at
multiple remote locations to collaborate and work together on a single project.
Familiar, Simple and Small
By using Java different range of applications can be developed by keeping the common
structure which is understood by JVM. Java uses many constructs of C and C++ and
therefore, Java code looks like a C++ code.
Multithreaded and Interactive
Multithreaded means handling multiple tasks simultaneously. It is one of the important
features of Java that provides multi-tasking where 2 parts of a program can be runnable
concurrently by sharing the common block of resources. This feature greatly improves the
interactive performance of graphical applications.
High performance
Java performance is impressive for an interpreted language, mainly due to the use of
intermediate bytecode. Java architecture is also designed to reduce overheads during runtime.
Dynamic and Extensible
Java is capable of dynamically linking in new class libraries, methods and objects. In Java
classes that were unknown to a program when it was compiled can still be loaded into it at
runtime. Java programs support functions written in other languages such as C and C++.
Java Weaknesses:
Java is that it doesnt directly support true decimal data.
Ex:
Double x = 5.02;
Double y = 0.01;
Double z = X + Y;
System.out.println(z);
Output:
5.029999999999999
But result is 5.03

Prepared by:

B.Rammurthy Naidu M.C.A,


Placement Incharge, Web Master, Assistant Professor,
Department of Computer Science,
GVP Degree College(A).

HOW JAVA DIFFERS FROM C AND C++


Java and C
Java is a lot like C but the major difference between Java and C is that Java is an objectoriented language and has mechanism to define classes and objects. In an effort to build a
simple and safe language, the Java team did not include some of the C features in Java.
Java does not include the C unique statement keywords goto, sizeof, and typedef.
Java does not contain the data types struct, union and enum.
Java does not define the type modifiers keywords auto, extern, register, signed, and unsigned.
Java does not support an explicit pointer type.
Java does not have a preprocessor and therefore we cannot use # define, # include, and # ifdef
statements.
Java does not support any mechanism for defining variable arguments to functions.
Java requires that the functions with no arguments must be declared with empty parenthesis
and not with the void keyword as done in C.
Java and C++
Java is a true object-oriented language while C++ is basically C with object-oriented
extension. C++ has maintained backward compatibility with C. It is therefore possible to
write an old style C program and run it successfully under C++. Java appears to be similar to
C++ when we consider only the "extension" part of C+ +. However, some object-oriented
features of C++ make the C++ code extremely difficult to follow and maintain.
Java does not support operator overloading.
Java does not have template classes as in C++.
Java does not support multiple inheritance of classes. This is accomplished using a new
feature called "interface".
Java does not support global variables. Every variable and method is declared within a class
and forms part of that class.
Java does not use pointers.
Java has replaced the destructor function with a finalize( ) function.
There are no header files in Java.
JAVA AND INTERNET
Java is strongly associated with the Internet because of the fact that the first application
program written in Java was HotJava, a Web browser to runapplets on Internet. Internet users
can use Java to create applet programs and run them locally using a "Java-enabled browser"
such as HotJava.
Internet users can also set up their Web sites containing Java applets that could be used by
other remote users of Internet. The ability of Java applets to hitch a ride on the Information
Superhighway has made Java a unique programming language for the Internet. In fact, due to
this, Java is popularly known as Internet language.

Prepared by:

B.Rammurthy Naidu M.C.A,


Placement Incharge, Web Master, Assistant Professor,
Department of Computer Science,
GVP Degree College(A).

JAVA AND WORLD WIDE WEB


World Wide Web (WWW) is an open-ended information retrieval system designed to be used
in the Internet's distributed environment. This system contains what are known as Web pages
that provide both information and controls.
Java was meant to be used in distributed environments such as Internet. Since, both the Web
and Java share the same philosophy, Java could be easily incorporated into the Web system.
Before Java, the World Wide Web was limited to the display of still images and texts.
However, the incorporation of Java into Web pages has made it capable of supporting
animation, graphics, games and a ,vide range of special effects. With the support of Java, the
Web has become more interactive and dynamic. On the other hand, with the support of Web,
we can run a Java program on someone else's computer across the Internet.
WEB BROWSERS
Internet is a vast sea of information represented in many formats and stored on many
computers. A large portion of the Internet is organized as the World Wide Web, which uses
hypertext. Web browsers are used to navigate through the information found on the net. They
allow us to retrieve the information spread across the Internet and display it using the
hypertext markup language (HTML). Examples of Web browsers: Hot Java, Netscape
Navigator, and Internet Explorer.
HARDWARE AND SOFTWARE REQUIREMENTS
Operating Systems
RAM
Processor
JDK
Editors
and Netbeans
Hard Disk Drive

:
:
:
:
:

Any Comparatable Operating System.


Minimum 512 MB
P3 Higher
1.5 or 1.6
Notepad, JCreator, Editplus, JBuilder

JAVA ENVIRONMENT
It is a product from sun microsystem which is a collection of n number of tools and
utilities which are used together to develop dynamic applications using java. 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).
Tools of Java Development Kit (JDK)
1. Javac (Java Compiler) :
Usage: javac <filename.java>
It stands for Java Compiler which takes the source code and translates into byte code.

Prepared by:

B.Rammurthy Naidu M.C.A,


Placement Incharge, Web Master, Assistant Professor,
Department of Computer Science,
GVP Degree College(A).

2. Java (Java Interpreter) :


Usage: java <filename>
It stands for Java Interpreter that interprets the byte code and produces the output.
3. applet viewer (for viewing Java applets) :
Usage: applet viewer <filename.java>
It is used to run applet based programs that provides graphical interface
4. Javap (Java help) :
Usage: javap <fully qualified class name>
It stands for Java Disassembler which will explore all methods and properties of the given
class.
5. Jdb (Java Debugger) :
Usage: jdb <class file>
It stands for Java Debugger. It makes the class file to execute line by line interruption.
6. Java doc (Java Documentation) :
Usage: javadoc <filename.java>
It is used to create HTML files for every class and method used in the program.
Application Programming Interface (API)
The Java Standard Library includes hundreds of classes and methods grouped into several
functional packages. Most commonly used packages are:
Language Support Package:
A collection of classes and methods required for implementing basic features of java.
Utilities Package:
A collection of classes to provide utility functions such as date and time functions.
I/O Package:
A Collection of classes required for Input/Output manipulations
Networking Package:
A collection of classes for communicating with other computers via network.

Prepared by:

B.Rammurthy Naidu M.C.A,


Placement Incharge, Web Master, Assistant Professor,
Department of Computer Science,
GVP Degree College(A).

10

AWT Package:
The Abstract Window Tool Kit package contains classes that implements platform
independent graphical user interface.
Applet Package:
This includes a set of classes that allows us to create Java applets.
OVERVIEW OF JAVA LANGUAGE
SIMPLE JAVA PROGRAM

Class Example
{
public static void main(String args[])
{
System.out.println(Welcome to Java);
}
}
Save this file as Example.java same as class name
Class Example
It defines a class named Example using a keyword class. After that, class definition is
specified within curly braces.
Prepared by:

B.Rammurthy Naidu M.C.A,


Placement Incharge, Web Master, Assistant Professor,
Department of Computer Science,
GVP Degree College(A).

11

public static void main(String args[])


This is the point from where the program will start the execution. The public keyword
is used to control the access of various class members. If member is public it can be accessed
outside the class. So we have to declare main( ) as public because it has to be invoked by the
code outside the class when program is executed. Static keyword allows the main( ) method
to be executed without creating an object of that class, and void means main( ) method does
not return any value.
String args[]
String is a predefined class and it takes any type of variable. [ ] represents free array.
args represents reference variable of string type.
System.out.println(Welcome to Java);
System is a class from java.lang package that contains all I/O related reference variables. Out
is a variable of system class. println( ) function is used to display this line.
Running the program
First set the path
location
C:\ set path=c:\jdk 1.3\bin;%path%
Compile the program
C:\> javac Example.java
The javac compiler creates a file called Example.class that contains the bytecode version of
the program.
Run the Program
C:\> java Example
Output: Welcome to java
JAVA PROGRAM STRUCTURE
Java program may contain many classes of which only one class defines a main method.
Documentation Section
The documentation section comprises a set of comment lines giving the name of the program,
and other details.
Package Statement
This statement declares a package name and informs the compiler that the classes defined
here belong to this package
Import Statement
This is similar to #include statement in c/c++
Ex: import java.io.*;
Prepared by:

B.Rammurthy Naidu M.C.A,


Placement Incharge, Web Master, Assistant Professor,
Department of Computer Science,
GVP Degree College(A).

12

This statement instructs the interpreter to load the methods contained in the package java.io.
Interface Statement
This is an optional section and is used only when we wish to implement the multiple
inheritance feature in the program.
Class Definition
A java program may contain multiple class definitions, which contains business logic
methods.
Main Method Class
Since every Java program requires a main method as its starting point, this class is the
essential part of a java program.
JAVA TOKENS
Smallest individual units in a program are known as Tokens. The complier recognized them
for building up expressions and statements. Java languages include 5 types of Tokens. They
are:
Reserved Keywords
Identifiers
Literals
Operators
Separators
Keywords:
A keyword is a word that has special meaning defined by the Java programming language.
The program shown earlier in Listing 1-1 uses four keywords:public, class, static, and void.
In all, Java has 51 keywords. Theyre listed in alphabetical order in Table 1-1. abstract do if
package synchronized boolean double implements private this break else import protected
throw byte extends instanceof public throws case false int return transient catch final
interface short true char finally long static try class float native strictfp void

Prepared by:

B.Rammurthy Naidu M.C.A,


Placement Incharge, Web Master, Assistant Professor,
Department of Computer Science,
GVP Degree College(A).

13

Identifiers:
An identifier is a word that you make up to refer to a Java programming element by
name. Although you can assign identifiers to many different types of Java elements, theyre
most commonly used for the following elements:
Classes, such as the HelloApp class in Listing 1-1
Methods, such as the main method in Listing 1-1
Variables and fields, which hold data used by your program
Parameters, which pass data values to methods
Comments:
A comment is a bit of text that provides explanations of your code. Comments are completely
ignored by the compiler, so you can place any text you wish in a comment. Using plenty of
comments in your programs is a good idea to explain what your program does and how it
works.
Java has three basic types of comments:
end-of-line comments
traditional comment
Multi comments
JavaDoc comments.
End-of-line comments (single Line comments):
An end-of-line comment begins with the sequence // and ends at the end of the line. You can
place an end-of-line comment at the end of any line.
Everything you type after the // is ignored by the compiler. For example:
total = total * discountPercent; // calculate the discounted total
If you want, you can also place end-of-line comments on separate lines,
like this:
// calculate the discounted total
total = total * discountPercent;
You can place end-of-line comments in the middle of statements that span
two or more lines. For example:
total = (total * discountPercent) // apply the discount first
+ salesTax; // then add the sales tax
Traditional comments (Multi Line comments):
A traditional comment begins with the sequence /* and ends with the sequence */ and can
span multiple lines. For example:
/* HelloApp sample program.
This program demonstrates the basic structure
that all Java programs must follow. */
A traditional comment can begin and end anywhere on a line. If you want, you can even
sandwich a comment between other Java programming elements, like this:
x = (y + /* a strange place for a comment */ 5) / z;
Usually, traditional comments appear on separate lines. One common use for traditional
comments is to place a block of comment lines at the beginning of a class to indicate
information about the class such as what the class does, who wrote it, and so on. However,
that type of comment is usually better coded as a JavaDoc comment, as described in the next
section.
Prepared by:

B.Rammurthy Naidu M.C.A,


Placement Incharge, Web Master, Assistant Professor,
Department of Computer Science,
GVP Degree College(A).

14

You may be tempted to temporarily comment out a range of lines by placing


/* in front of the first line in the range and */ after the last line in the range.
However, that can get you in trouble if the range of lines you try to comment
out includes a traditional comment. Thats because traditional comments
cant be nested. For example, the following code wont compile:
/*
int x, y, z;
y = 10;
z = 5;
x = (y + /* a strange place for a comment */ 5) / z;
*/
Here, I tried to comment out a range of lines that already included a traditional comment.
Unfortunately, the */ sequence near the end of the fifth line is interpreted as the end of the
traditional comment that begins in the first line. Then, when the compiler encounters the */
sequence in line 6, it generates an error message.
Multi Comments (Comments with comments or Nested comments):
Here, comments with in comments, nested comments. It can be represented with
/** Multi comments or Comments with in comments or Nested comments */
JavaDoc comments:
JavaDoc comments are actually a special type of traditional comment that you can use to
automatically create Web-based documentation for your programs. Because youll have a
better appreciation of JavaDoc comments when you know more about object-oriented
programming, I devoted a section in Book III, Chapter 8 to creating and using JavaDoc
comments.
IMPLEMENTING A JAVA PROGRAM
Steps to be followed to implement a Java Program:
Creating the program
Compiling the program
Running the program
Creating the program
We can create a program using any text editor.
Class Sample
{
public static void main(String args[])
{
System.out.println( HELLO );
}
}
We must save this program with the filename Sample.java ensuring that the filename and
classname should be same. This file is called as source file. If a program contains multiple
classes, the filename must be the classname of the class containing the main method.
Prepared by:

B.Rammurthy Naidu M.C.A,


Placement Incharge, Web Master, Assistant Professor,
Department of Computer Science,
GVP Degree College(A).

15

Compiling the program


C:\> javac Sample.java
The javac compiler creates a file called Sample.class that contains the bytecode version of the
program.
Running the program
C:\> java Sample
Now the interpreter looks for the main method in the program and begins execution from
there.
JAVA VIRTUAL MACHINE
When a Java program is compiled it is converted to bytecode, which is then executed by the
Java Interpreter by translating the bytecode into machine instructions. Program in Java
runtime environment, which is used to interpret bytecode, is called Java Virtual Machine.
Any machine for which java interpreter is available can execute this bytecode. Thats why
java is called as Machine Independent and Architecture Neutral. The JVM plays the main
role to making Java portable.

Java Interpreter
For windows 98
Byte Code

Java Compiler
Java Program

Byte Code

Byte Code

Java Interpreter
For macintosh
Java
Interpreter
Java Interpreter
For Linux

Java is Machine Independent and Architecture Neutral


COMMAND LINE ARGUMENTS.
Command Line arguments are parameters that are supplied to the application program at the
time of invoking it for execution.

Prepared by:

B.Rammurthy Naidu M.C.A,


Placement Incharge, Web Master, Assistant Professor,
Department of Computer Science,
GVP Degree College(A).

16

/* Program to find the average of 3 numbers */


class average
{
public static void main(String []args)
{
int s1=Integer.parseInt(args[0]);
int s2=Integer.parseInt(args[1]);
int s3=Integer.parseInt(args[2]);
int total=s1+s2+s3;
double avg=total/4;
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
System.out.println("Total= " +total);
System.out.println("Average="+avg);
}
}
Output:
E:\javaprograms>javac average.java
E:\javaprograms>java average 50 60 70
50
60
70
Total= 180
Average=45.0
CONSTANTS
Constants are the fixed values that do not change during the execution of a program. Java
supports several types of constants.
Integer Constant
An integer constant refer to a sequence of digits. There are 3 types namely:
Decimal Integer
ex:123
-321
0
654321
octal Integer
ex:037
0
0435
0551
hexadecimal integer
ex:0X2
0X9F
0Xbcd 0x

DATA TYPES
A Data type is the type of data that can be stored into the variable. A description on a variable
that determines what kind of information you can enter in the variable.
There are seven primitive data types, which are supported by Java language programming. A
primitive data type is a data type, which is predefined in Java. Following are the eight
The term Data Type refers to the type of data that can be stored in a variable.
Java is sometimes called a strongly typed language.
Prepared by:

B.Rammurthy Naidu M.C.A,


Placement Incharge, Web Master, Assistant Professor,
Department of Computer Science,
GVP Degree College(A).

17

Java has two types of data types.


1. Primitive data types.
2. Reference data types.
Primitive data types:
Primitive data types are the data types that are defined by the language Itself.
The memory location associated with a primitive types variables contains the actual value of
the variable.It is also called as Value types.

Type
int
short
long
byte
float
double
char
boolean

Javas Primitive Types


Explanation
A 32-bit (4-byte) integer value
A 16-bit (2-byte) integer value
A 64-bit (8-byte) integer value
An 8-bit (1-byte) integer value
A 32-bit (4-byte) floating-point value
A 64-bit (8-byte) floating-point value
A 16-bit character using the Unicode encoding scheme
A true or false value

primitive data types:


int
It is a 32-bit signed two's complement integer data type. It ranges from -2,147,483,648 to
2,147,483,647. This data type is used for integer values. However for wider range of values
use long.
byte
The byte data type is an 8-bit signed two's complement integer. It ranges from -128 to127
(inclusive). We can save memory in large arrays using byte. We can also use byte instead of
int to increase the limit of the code.
short
The short data type is a 16-bit signed two's complement integer. It ranges from -32,768 to
32,767. short is used to save memory in large arrays.
long
The long data type is a 64-bit signed two's complement integer. It ranges from 9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. Use this data type with larger
range of values.
float
The float data type is a single-precision 32-bit IEEE 754 floating point. It ranges from
1.40129846432481707e-45 to 3.40282346638528860e+38 (positive or negative). Use a float
(instead of double) to save memory in large arrays. We do not use this data type for the exact
values such as currency. For that we have to use java.math.BigDecimal class.
double
This data type is a double-precision 64-bit IEEE 754 floating point. It ranges from
4.94065645841246544e-324d to 1.79769313486231570e+308d (positive or negative). This
data type is generally the default choice for decimal values.
boolean
The boolean data type is 1-bit and has only two values: true and false. We use this data type
for conditional statements. true and false are not the same as True and False. They are defined
constants of the language.
Prepared by:

B.Rammurthy Naidu M.C.A,


Placement Incharge, Web Master, Assistant Professor,
Department of Computer Science,
GVP Degree College(A).

18

char
The char data type is a single 16-bit, unsigned Unicode character. It ranges from 0 to 65,535.
They are not same as ints, shorts etc.
/* Program on Datatypes */
class datatypes
{
public static void main(String []args)
{
int a=457647657;
byte b=12;
short c=435;
long d=345;
float g=3.5f;
double f=345.6;
char k='a';
boolean h=false;
System.out.println("Integer="+a);
System.out.println("Byte="+b);
System.out.println("Short="+c);
System.out.println("Long="+d);
System.out.println("Float="+g);
System.out.println("Double="+f);
System.out.println("Character="+k);
if(h==true)
System.out.println("Boolean value is true");
else
System.out.println("Boolean value is false");
}
}
Output:
E:\sysvol>javac datatypes.java
E:\sysvol>java datatypes
Integer=457647657
Byte=12
Short=435
Long=345
Float=3.5
Double=345.6
Character=a
Boolean value is false
Reference data types :
Reference types are types that are defined by the language java API rather than by the
language itself.
Prepared by:

B.Rammurthy Naidu M.C.A,


Placement Incharge, Web Master, Assistant Professor,
Department of Computer Science,
GVP Degree College(A).

19

The memory location associated with a reference tpes variable contains an address
(called pointer) that indicates the memory location of the actual object.

VARIABLES
A variable is a basic unit of storage, which represents memory location in which value can be
stored.
Rules for variables:
1. They must not begin with a digit
2. It should not be a keyword
3. White space is not allowed
4. Variable names can be of any length
DECLARATION OF VARIABLES
Before using any variable, it must first be declared. A variable declaration specifies the
datatype, the variable name, and optionally the default value for the variable.
Syntax: datatype identifier {=default value}
Ex:
byte b;
int age, enrolno
boolean male
GIVING VALUES TO VARIABLES
Once you have declared the type of a variable, you can initialize it with some value.
Syntax: variable name=some value
Ex:
int year=20;
SCOPE OF VARIABLES
Java actually has three kinds of variables
Instance variables
Class variables
Local variables
Instance variables are created when the objects are instantiated and therefore they are
associated with the objects. They take different values for each object. Class variables are
similar to instance variables, except their values apply to all the instances of a class rather
than having different values for each object. Local variables are declared and used inside
methods.
Variables :
Variables are also the key to creating programs that can perform calculations.
Type of Variables :
1. class variable
2. Instance variable
3. Local variable
Prepared by:

B.Rammurthy Naidu M.C.A,


Placement Incharge, Web Master, Assistant Professor,
Department of Computer Science,
GVP Degree College(A).

20

4. Final variable
5. shadowing variable
Class Variable :
A class variable is a variable that any method in a class can access, including static
methods such as main.
When declaring a class variable you have two basic rules to follow:
1. You must place the declarations within the body of the class, but not within any of
the class method.
2. You must include the word static in the declaration. The word static comes before the
variable type.
E.g.: public class helloapp {
static string hellomessage;
public static void main(String[] args) {
hellomessage = Helloworld!;
System.out.println(hellomessage);
}
}
Instance variable :
An instance variable is similar to a class variable, but doesnt specify The word static in its
declaration.
Instance variables are associated with instances of classes.
E.g.:
public class helloapp {
string hellomessage;
public static void main(String[] args) {
hellomessage = Helloworld!;
System.out.println(hellomessage);
}
}
Error :
Cannot make a static reference to the non-static field hellomessage
Local variable :
A local variable is a variable thats declared within the body of a method.
You dont specify static on a declaration for a local variable.
local variables are not given initial default values. The compiler checks to make sure
that you have assigned a value before you use a local variable.
Final variable (Constants) :

A final variable, also called a constant.


It is a variable whose value you cant change once its been initialized.

Prepared by:

B.Rammurthy Naidu M.C.A,


Placement Incharge, Web Master, Assistant Professor,
Department of Computer Science,
GVP Degree College(A).

21

Final variables are class or instance variables


Shadowing variables :
A shadowing variable is a variable that would otherwise be accessible, but is temporarily
made unavailable because a variable with the same name has been declared in a more
immediate scope.
Scope :
The scope of a variable refers to which parts of a class the variable exists in.
*SYMBOLIC CONSTANTS
symbolic constants are used like macros in C and C++
symbolic names take the same form as variable names. But, they are written in capitals to
visually distinguish them from normal variables. After declaration of symbolic constants they
should not be assigned to any other within the program by using an assignment statement.
A constant can be declared as follows:

Final type symbolic name =value;


Examples:
final int STRENGTH
= 100;
final int PASS_MARK
= 50;
final float PI
= 3.14159;
TYPE CASTING
The process of converting one data type to another is called casting
Type variable1 = (type) variable 2
Examples:
int m=50;
byte n=(byte)m;
long count=(long) m;
class Typecasting
{
public static void main(String args[])
{
System.out.println("variales created");
char c='x';
byte b=50;
short s=1996;
Prepared by:

B.Rammurthy Naidu M.C.A,


Placement Incharge, Web Master, Assistant Professor,
Department of Computer Science,
GVP Degree College(A).

22

int i=123456789;
long l=1234567654321L;
float f1=3.142F;
float f2=1.2e-5F;
double d2=0.000000987;
System.out.println(" c="+c);
System.out.println(" b ="+b);
System.out.println(" s= "+s);
System.out.println(" i="+i);
System.out.println(" l="+l);
System.out.println(" f1= "+f1);
System.out.println(" f2="+f2);
System.out.println("d2 ="+d2);
System.out.println(" ");
System.out.println(" Types converted");
short s1=(short)b;
short s2=(short)i;
float n1=(float)l;
int m1=(int)f1;
System.out.println(" (short)b ="+s1);
System.out.println(" (short)i ="+s2);
System.out.println(" (float)l= "+n1);
System.out.println(" (int)f1= - "+m1);
}
}
Note : floating point constants have a default type of double
For example when we want to declare a float variable and initializing it to constant
float x=7.56;
This will give incompatible type for declaration. Explicit cast needed to convert double to
float.
This should be written as
float x=7.56F

Prepared by:

B.Rammurthy Naidu M.C.A,


Placement Incharge, Web Master, Assistant Professor,
Department of Computer Science,
GVP Degree College(A).

23

You might also like