0% found this document useful (0 votes)
21 views26 pages

Iii Sem Java Unit-1

Uploaded by

Vk Telugu gamer
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views26 pages

Iii Sem Java Unit-1

Uploaded by

Vk Telugu gamer
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Object Oriented Programming Using JAVA UNIT-I

UNIT-1: FUNDAMENTALS OF OBJECT – ORIENTED PROGRAMMING:


Introduction, Object Oriented paradigm, Basic Concepts of OOP, Benefits of OOP, Applications of
OOP,
OVERVIEW OF JAVA LANGUAGE: Introduction, java features, Simple Java program structure, Java
tokens, Java Statements, Implementing a Java Program, Java Virtual Machine, Command line
arguments. CONSTANTS, VARIABLES & DATA TYPES: Introduction, Constants, Variables, Data
Types, Declaration of Variables, Giving Value to Variables, Scope of variables, Symbolic Constants,
Type casting, Getting Value of Variables, Standard Default values; OPERATORS & EXPRESSIONS.

OBJECT –ORIENTED PARADIGM: The major objective of Object Oriented approach is to


eliminate some of the drawbacks in procedural or conventional programming approaches.

OOP is an approach that provides a way of modularizing programs by creating partitioned memory area
for both data and functions that can be used as templates.

1. OOP treats data as a critical element in the program development and does not allow it to flow
freely around the system.
2. OOP allows us to divide a problem into a number of entities called objects which consists of data
and methods.
3. Data structures are designed such that they characterize the objects.
4. Data is hidden and cannot be accessed by external functions.
5. Objects may communicate with each other through methods.
6. New data and methods can be easily added whenever required.
7. It follows bottom – up approach in program design.
8. Object C, Object Pascal, C++, Java, etc are the examples
Basic concepts of Object Oriented Programming:

1. Object: Objects are the basic runtime entities in an object oriented system. They may represent a
thing, a person, a place or a back account. It represents data and methods that are used to manipulate
the data. Object must be declared is such a way that they match real world objects.
Ex: Customer and account are two objects in a bank program. The customer object may send a
message to the account object requesting for the balance.
2. Class: Class is a user defined data type. It consists of the entire set of data and methods that are used
to manipulate the data. A class is a collection of similar type of objects. Once a class is create we
create any number of objects belonging to that class.
Ex: Fruit is a class and mango, apple and orange are the objects of class fruit.

1
Object Oriented Programming Using JAVA UNIT-I
3. Data Abstraction: Abstraction refers to the act of representing essential features by hiding the
background details. Class and object uses this concept. Class is defined as a list attributes such as
size, weight and cost and methods to operate these attributes and these are represented by objects.
Since classes use the concept of data abstraction they are called as Abstract Data Types(ADT).
4. Data Encapsulation: The wrapping up of data and methods into a single unit is known as
encapsulation. Class follows this concept. The data is tied to methods and is not accessible to the
outside classes. This is called as data hiding.
5. Inheritance: Inheritance is the process of acquiring the properties of one class to another class. This
concept provides the idea of reusability. This means that we can add new features to an existing class
without modifying it.
6. Polymorphism: The ability to take more than one form is called as polymorphism. For example, an
operation may exhibit different behavior different situations. The behavior depends upon the types
of the data used in the operation. A single method name can be used to handle different types of
arguments and produce different results.
7. Dynamic Binding: Binding refers to the linking of a procedure call to the code to be executed in
response to the call. Dynamic binding means that the code associated with a given procedure call is
not known until the time of execution.
8. 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 is:

• Create classes that define objects.


• Creating objects from class definitions.
• Establishing communication among objects.
9. Generic Programming: This feature allows declaration of variables without specifying exact data
types. Object oriented programs can create a function that can use for any type of data.
Benefits of OOP:

• OOP provides greater programmer productivity, better quality programs and reduce
maintenance cost.
• By using inheritance feature we can reuse program.
• The data hiding feature helps the programmer to built secure programs.
• The polymorphism feature is used to develop efficient programs.
• Message passing techniques for communication between objects make the interface much
simpler.
• Software complexity can be easily managed.
• The data binding feature is used to develop powerful programs.
2
Object Oriented Programming Using JAVA UNIT-I
• OOP is used to solve real world problems effectively.
• It is possible to have multiple instances of an object.
• It is easy to partition the work of a project based on objects.
Applications of OOP:

• OOP is used to develop software for Real-time systems such as cell phones, TVs, VCRs and
other electronic machines.
• OOP is used for simulation and modeling. It is used to design the simulator like chess playing
etc.
• It is used to develop Object Oriented databases such as Oracle and SQL server etc.
• It is used to develop AI models like robotics.
• It is used to design expert system like car theft scanning etc.
• It is used to develop neural networks and parallel programming in network system.
• It is used to develop CAM and CAD software for architecture planning in industries.
• It is used to develop and design some new system software and packages such as operating
systems and new programming languages etc.
• It manage all the textual, graphical and animation by developing the multimedia events.
• It helps in game playing softwares.
• All resource management softwares are designed and developed through object oriented
languages.
• It develops security software for banks and finance oriented organizations.
Difference between C and Java:

C – Language Java

Java is a Object Oriented Programming


C is a structured programming language.
language.
C is not that much suitable to solve real world
Java is suitable to solve real world problems.
problems
C allows us to divide problem into a number of Java allows us to divide problem into a number
functions. of entities called objects.
Java does not use header files and preprocessor
C uses header files like stdio.h.
directives.
C uses global variables. So there is no data Java does not use global variables. So there is
security. data security.
C uses goto, sizeof and typedef statements. Java does not include goto, sizeof and typedef.
3
Object Oriented Programming Using JAVA UNIT-I
C uses type modifier keywords such as auto,
Java does not use such kind of keywords.
extern, register, signed and unsigned.
C uses pointers. Java does not use pointers.
C uses structures and unions to create user Java uses classes in the place of structures and
defined data types. unions to create user defined data types.
C does not have inheritance and polymorphism Java has both inheritance and polymorphism
features. features.
C follows top-down approach in program Java follows bottom-up approach in program
design. design.

Difference between C++ and java:

C ++ Java
C++ is a Object Oriented Programming Java is also a Object Oriented Programming
language. language.
Java does not use header files and preprocessor
C++ uses header files like iostream.h.
directives.
C++ uses goto, sizeof and typedef statements. Java does not include goto, sizeof and typedef.
C++ uses type modifier keywords such as auto,
Java does not use such kind of keywords.
extern, register, signed and unsigned.
C++ uses pointers. Java does not use pointers.
Java does not support multiple inheritance. It
C++ supports multiple inheritance.
uses interfaces.
C++ supports operator overloading. Java does not support operator overloading.
C++ uses destructor function. Java uses finalize function.
C++ follows bottom-up approach in program Java also follows bottom-up approach in
design. program design.

History of java:
1) Java is a general-purpose, object-oriented programming language developed by Sun
Microsystems of USA in 1991.

2) Originally called Oak by James Gosling,

3) it was designed for the development of software for consumer electronic devices like TVs,
VCRs, toasters and electronic machines.

4
Object Oriented Programming Using JAVA UNIT-I
4) Oak was unsuccessful. So in 1995, sun changed the name to java and modified the language
to take the advantage of WWW.

5) The java team wanted to develop a language which is simple, portable and highly realiable.

6) The team modeled the new language java on C & C++, but removed a number of features that
were considered as sources of problems. So it makes java a powerful language.

7) The most striking feature of java is that it is a platform neural and it is the first language that
it is not tied to any particular hardware operating system.

8) The programs developed in java can be executed at anywhere and at any system.

YEAR DEVELOPMENT
1990 Sun Micro Systems decided to develop a special software
1991 OAK was developed
1992 The first project called Green project was developed
1993 WWW appeared on the Internet
1994 Developed a web browser called Hot Java
1995 OAK was renamed as java
1996 Sun releases Java Development Kit(JDK 1.0)
1997 Sun releases Java Development Kit(JDK 1.1)
1998 Sun releases Java2 with Software Development Kit(SDK 1.2)
Sun releases Java2 Standard Edition(J2SE) and Java2 Enterprise
1999
Edition(J2EE)
2000 J2SE with SDK 1.3 was released
2002 J2SE with SDK 1.4 was released
2004 J2SE with JDK 5.0 was released

Features of Java:
The inventors of java wanted the language to be not only reliable, portable and distributed but
also simple, compact and interactive. The following are the features of java:
1. Compiled and Interpreted: Usually a computer language is either compiled of interpreted, but java
combines both these approaches in two stages. In the first stage java compiler translates the source
code into byte code. In the second stage java interpreter generates the byte code that can be directly
executed by the machine.

5
Object Oriented Programming Using JAVA UNIT-I
2. Platform-independent and portable: Java programs can be easily moved from one system to
another. It can be run on any kind of system with any type of operating system. Changes and upgrades
in operating systems, processors and system resources will not force any changes in java programs.
So java has become a popular language for Internet programming.
3. Object Oriented: Java is a true object oriented language. Almost everything in java is an object. The
object model in java is simple and easy to extend.
4. Robust and secure: Java is a robust language. It provides many safeguards to ensure reliable code.
They are:

• It is designed as garbage collected language which solves all memory management problems.
• The exception handling feature helps us to identify and eliminate the errors.
• Java ensures that no viruses are communicated with an applet.
5. Distributed: Java is designed as a distributed language for creating applications on networks. It has
the ability to share both data and programs. This will help multiple programmers at multiple remote
locations to work together on a single project.
6. Simple, Small and Familiar: Java is a small and simple language as many features of C and C++
are eliminated in java. It eliminates pointers, header files and goto etc from C and operator
overloading and multiple inheritance from C++.
7. Multithreaded and interactive: Multithreaded means handling multiple parts of the same program
simultaneously. We need not wait for the application to finish one task before beginning another.
8. High performance: Java performance is impressive mainly due to the ustie of intermediate byte
code. Java is designed to reduce difficulties during the run time. It is efficient and reliable.
9. Dynamic and Extensible: Java is capable linking new class libraries, methods and objects
dynamically at run time.
10. Ease of development: It is very easy to develop java programs as java supports features sucAh as
generics, enhanced for loop, auto boxing, type safe etc.

Applications of java:

• Used in android apps.


• Used in server apps at financial services industry.
• Used in software tools.
• Used in trading applications.
• Used in J2ME apps.
• Used in high frequency trading space
6
Object Oriented Programming Using JAVA UNIT-I

Java Environment:
Java environment includes a large number of development tools that are used for hundreds of classes
and methods. They are two categories. They are:
1. Java Development Kit (JDK):
It contains the development tools such as applet viewer, java, javac, etc.
Java Development Tools
Tool Use
Applet viewer It enables us to run java applets.

Javac (java compiler) It translates java source code to bytecode.

Java (java interpreter) It interprets java bytecode.

Javadoc It creates HTML format documentation from java source code


files.
Javah It produces header files for use with native methods.

Javap (java diassembler) It enables us to convert bytecode files into a program.

Jdb (java debugger) It helps us to find errors in our programs.

Flowchart for the usage of java tools in application development

Text Editor

Java
javadoc HTMLS Files
Source Code

javac

Java
javah Header files
Class File

java jdb

7
output
Object Oriented Programming Using JAVA UNIT-I

Java Standard Library (JSL) or Application Programming Interface (API):

It contains the classes and methods such as language support package, utilities package, etc. It is
also known as Application Programming Interface (API). Most commonly used packages are:

• Language Support Package: It is a collection of classes and methods required for implementing
basic features of java.
• Utilities Package: It is a collection of classes that contains utility functions such as date and time
functions.
• Input / Output Package: It is a collection of classes required for input/output manipulations.
• Networking Package: It is a collection of classes for communicating with other computers through
internet.
• AWT Package: The Abstract Window Tool Kit package contains classes that implements graphical
user interface.
• Applet Package: It is a collection of classes that allows us to create java applets.
OVERVIEW OF JAVA LANGUAGE: Java is a general-purpose, object-oriented programming
language. We can develop two types of java programs. They are:
• Stand-alone applications.
• Applets.
Stand-alone applications: They are the programs that are written in java to carry out certain tasks on
stand-alone computer. Stand-alone programs can read and write files and perform certain operations that
applets cannot do. HotJava itself is a Java application program. Executing a stand-alone Java program
involves two steps:
1. Compiling source code into byte code using javac compiler.
2. Executing the byte code program using java interpreter.
Applets: They are small java programs developed for internet applications. An applet located on a
distant computer (server) can be downloaded via Internet and executed on a local computer (client) using
a browser. We can develop applets for doing everything from simple animated graphics to games and
utilities. An applet can only run within a web browser. An applet program can compile the program
using Javac and can run this program using appletviewer.
8
Object Oriented Programming Using JAVA UNIT-I
Implementing a Java Program:
Creating the program: We can create a program using any text editor. We must save the program by
the class name, which contains the main method. This file is called the source file. Java source files
will have the extension (.java).
C:\> EDIT
class Sum
{
public static void main(String args[])
{
int s=0,i;
for(i=1;i<=10;i++)
{
s=s+i;
}
System.out.println(“Sum of 10 natural numbers:”+s);
}
}
• Compiling the program: To compile the program, we must run the java compiler javac, with
the name of the source file on the command line
C:\> javac Sum.java
If every thing is OK, the javac compiler creates a file called Sum.class containing the
byte code of the program.
• Running the program: We need to use the java interpreter to run a stand-alone program. At the
command prompt, type
C:\>java Sum 55 (Output)

Structure of Java Program:


Documentation section Suggested
Package Statement
Import statement
Interface statement Optional
Class Definition
Main method class
{
Main method definition Essential
9
Object Oriented Programming Using JAVA UNIT-I
}
▪ 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.
Example: /* Addition of two numbers */
▪ 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. The package statement is optional.
Example: package student;
▪ Import statement: This statement instructs the interpreter to load the Test class contained in the
package student. Using import statements, we can have access to classes that are part of other
named packages.
import student.Test;
▪ Interface statement: An interface is like a class but includes a group of method declarations.
This is also an optional section and is used only when we wish to implement the multiple
inheritance features in the program.
interface interface_name;
▪ Class definition: 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 problem.
class class_name
{
Data members;
methods
}
▪ Main method class: Since every Java stand-alone program requires a main method as its starting
point, this class is the essential part of a Java program. The main method creates objects of
various classes and establishes communications between them.
class Sample
{
public static void main (String args[])
{
-------
}
}
10
Object Oriented Programming Using JAVA UNIT-I
Simple Java Program:
class Sample
{
public static void main (String args[])
{
System.out.println(“Welcome to Java”);
}
}

• Class declaration: The first line class Sample declares a class, which is an object-oriented
construct. Java is a true object-oriented language and therefore everything must be placed inside
a class. class is a keyword and declares that a new class definition follows. Sample is a java
identifier that specifies the name of the class to be defined.
• Opening Brace: Every class definition in Java begins with an opening brace { and ends with a
matching closing brace } appearing in the last line.
• main(): 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. The java applets will not use the main
method.
• All parameters to a method are declared inside a pair of parentheses. Here String args[] declares
a parameter named args, which contains an array of objects of the class type String.
• The output statement in the program is System.out.println(“Welcome to Java”);
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 static data member of System class. Every
Java statement must end with a semicolon.
Java Virtual Machine (JVM): It is a program that interprets the intermediate java byte code and
generates the desired output. Java is highly portable because of JVM concept. All language compilers
translate source code into machine code for a specific computer. The java compiler produces an
intermediate code known as byte code for a machine that does not exist. That machine is called as the
JVM and it exists only inside the computer memory.

Java Program Java Compiler Byte Code

11
Object Oriented Programming Using JAVA UNIT-I
The virtual machine code is not machine specific. The machine code is generated by the java
interpreter by acting as an mediator between the virtual machine and the real machine.

Byte code Java Interpreter Machine code

Virtual machine real machine


Command line arguments: Command line arguments are parameters that are supplied to the
application program at the time of execution. We can write java program that can receive and use the
arguments provided in the command line.
public static void main(String args[])
args is declared as an array of strings. Any arguments provided in the command line are passed
to the array args as its elements. We can simply access the array elements and use them in the program
as we wish.
class CommandLine
{
public static void main(String args[])
{
int count, i;
String s;
count=args.length;
System.out.println(“Number of arguments=” +count);
for(i=0;i<count;i++)
{
s=args[i];
System.out.println(s);
}
}
}
C:\> javac CommandLine.java
C:\> java CommandLine Maths Physics Electronics ComputerScience
Number of arguments=4
Maths
Physics
Electronics
Computer science
12
Object Oriented Programming Using JAVA UNIT-I
Java Tokens: The smallest individual units in a program are known as tokens. Java program is a
collection of tokens, comments and white spaces. Java language includes five types of tokens.
1. Keywords
2. Identifiers
3. Literals (Constants)
4. Operators
5. Separators
1. Keywords: Keywords are the reserved or pre-defined words. Java language has 50 keywords. Since
keywords have specific meaning in Java, we cannot use them as names for variables, classes, methods
and so on. All keywords are to be written in lower-case letters. Since Java is case-sensitive.
2. Identifiers: Identifiers refer to the names of classes, methods, variables, arrays, objects, labels,
packages and interfaces in a program. These are user- defined names and consist of a sequence of letters
and digits with a letter as a first character.
Rules for identifiers:
• They can have alphabets, digits, underscore and dollar sign.
• They must begin with a letter.
• The upper and lowercase are distinct.
• The variable name should not be a keyword.
• White spaces are not allowed.
• They can be of any length.
3. Literals (Constants): Literals in Java are a sequence of characters that represent fixed values that do
not change during the execution of a program.
▪ Integer literals
▪ Floating point literals
▪ Character literals
▪ String literals
▪ Boolean literals
4. Operators: An operator is a symbol that takes one or more arguments and performs certain
mathematical or logical manipulations.
Types of Operators:
1. Arithmetic
2. Relational
3. Logical
4. Increment and decrement
5. Bit wise
13
Object Oriented Programming Using JAVA UNIT-I
6. Assignment
7. Conditional
8. Special.
5. Separators: Separators are symbols used to indicate where groups of code are divided and arranged.
They basically define the shape and function of our code.
Parentheses () Used to enclose parameters in method definition
braces {} Used to contain the values of automatically initialized arrays
brackets [] Used to declare array types and for dereferencing array values.
semicolon : Used to separate statements
comma , Used to separate consecutive identifiers in a variable declaration.
Period . Used to separate package names from sub-packages and classes;
also used to separate a variable or method from a reference variable.

Java Statements: The statements in Java are like sentence in natural languages. A statement is an
executable combination of tokens ending with a semicolon (;) mark. There are five types of statements
in java. They are:
➢ Expression: Most statements are expression statements. Java has seven types of expression
statements. They are assignment, pre-increment, pre-decrement, post-increment, post-decrement,
method call and allocation expression.
➢ Labeled statement: Labels in java are used as the arguments of jump statements. Such labels
must not be keywords, already declared local variables or previously used labels in this module.
➢ Control statement:
▪ Sequential statement: Statements, Which are in between { and }
▪ Branching statement: selects one of several control flows. There are two types of
selection statements in java:
o Conditional branching: if, switch, conditional operator
o Unconditional branching: break, continue, return
▪ Iteration statement (Loop): Loop is a statement, which executes a group of statements
for a fixed number of times. There are three types of iteration statement:. They are: for,
while and do while
➢ Synchronization statement: These are used for handling issues with multithreading.
➢ Guarding statement: Guarding statements are used for safe handling of code that may cause
exceptions (such as division by zero). These statements use the keywords such as try, catch and
finally.

14
Object Oriented Programming Using JAVA UNIT-I
Constants: Constants in Java refer to fixed values that do not change during the execution of a
program.
Integer constant:
• An integer constant refers to a sequence of digits.
• There are three types of integer namely decimal integer, octal integer and hexadecimal
integer.
• Decimal integers consist of digits 0 through 9, preceded by an optional minus sign. Spaces,
commas and non-digit characters are not permitted between digits.
Example: 127, -131, 65534 etc.,
• An octal integer constant consists of digits from the 0 through 7, with leading O.
Example: O37, O435, o346 etc.
• A sequence of digits preceded by Ox or OX is considered as hexa-decimal integer. They may
also include alphabets A through F or a through f. A letter A through F represents the numbers
10 through 15.
Example: OX2, OX9F, OXbcd etc.,
Real Constants:
• Numbers containing fractional parts like 17.548. Such numbers are called real constants.
• A real number may also be expressed in exponential notation. The general form is
mantissa E exponent
• Mantissa is either a real number or an integer. The exponent is an integer with an optional + or –
sign. The mantissa and the exponent can be written in either lower case or uppercase.
Example: 215.65 may be written as 2.1565e2.
e2 means multiple by 102.
Single character constant:
A single character constant contains a single character enclosed within a pair of single quote
marks.
Examples: ‘5’ ‘x’ ‘;’ ‘’
• Note that the character constant ‘5’ is not the same as the number 5.
String character constant:
A string constant is a sequence of characters enclosed between double quotes. The character
may be alphabets, digits; special characters and blank spaces.
“2009” “Programming with Java” “3+6=9” “X”

Backslash character constant:

15
Object Oriented Programming Using JAVA UNIT-I
Java supports some special backslash character constants that are used in output methods. For
example the symbol ‘\n’ stands for new line character.
List of backslash character constants
Constant Meaning
‘\b’ Back space
‘\f’ Form feed
‘\n’ New line
‘\r’ Carriage return
‘\t’ Horizontal tab
‘\” Single quote
‘\”’ Double quote
‘\\’ backslash

Symbolic constants: Symbolic constants are the variables in which they will be assigned with a
constant that cannot be changed in the program.
Syntax: final type symbolic-name = value;
Ex: final float PI= 3.14159;
Points to be remembered:
1. Symbolic names take the same form as variable names. But, they are written in capitals to distinguish
them from normal variable names.
2. After declaration of symbolic constants, they should not be assigned any other values within the
program.
3. Symbolic constants cannot be declared inside a method. They should be used only as class data
members in the beginning of the class.
//EXAMPLE PROGRAM FOR SYMBOLLIC CONSTANTS
import java.lang.Math;
class Circle
{
final double PI=3.1459f;
int r;
void putdata(int x)
{
r=x;
}
void area()
16
Object Oriented Programming Using JAVA UNIT-I
{
double a=PI*Math.pow(r,2);
System.out.println("the area of circle is ="+a);
}
}
class Carea
{
public static void main(String args[])
{
Circle c=new Circle();
c.putdata(2);
c.area();
}
}
OUTPUT:
D:\java>javac Carea.java
D:\java>java Carea
the area of circle is =12.583600044250488

Data types: Data type is the representation of the kind of data that we use in the program. Every
variable in Java has a data type. Data types specify the size and type of values that can be stored. Java
language is rich in its data types.
1. Integer types: Integer types can hold whole numbers along with the negative numbers. The size of
the values that can be stored depends on the integer data type. Java supports four types of integers.
They are byte, short, int and long. Java doest not support the concept of unsigned types.

Integer

Byte Short Int Long

Default
Type Size Minimum Value Maximum Value
value
byte 1 byte 0 -128(-27) 127(27-1)
short 2 bytes 0 -32,768(-215) 32,767(215-1)
int 4 bytes 0 -2,147,483,648(-231) 2,147,483,647(231-1)

17
Object Oriented Programming Using JAVA UNIT-I
long 8 bytes 0L -9,232,372,036,854,775,808(-263) -9,232,372,036,854,775,807(263-1)

2. Floating Point Types: Floating point type can hold numbers containing fractional part such as
22.365 and -89.365. There are two kinds of floating point storage in java.
Floating point

Float Double

Type Size Default value Minimum Value Maximum Value


float 4 bytes 0.0f 3.4e-038 3.4e+038
double 8 bytes 0.0d 1.7e-308 1.7e+308
• Floating point numbers are treated as double precision quantities. To force them to be in single
precision mode, we must append f or F to the number.
• Double-precision types are used when we need greater precision in storage of floating point
number.
3. Character type: In order to store character constant in memory, java provides a character data
type called char. The char type assumes a size of 2 bytes but basically it can hold only a single
character.
4. 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.
Non-primitive datatypes:

Class: Class is a user defined data type. It consists of the entire set of data and methods that are used to
manipulate the data. A class is a collection of similar type of objects. Once a class is created we create
any number of objects belonging to that class.

Ex: Fruit is a class and mango, apple and orange are the objects of class fruit.

Interface: An interface is basically a kind of class. The difference is that interfaces define only
abstract methods and final fields. This means that interfaces do not specify any code to implement
these methods and data fields contain only constants.

Arrays: An array is a variable that can store multiple values of same data type; where as an ordinary
variable can store a single value at a time.

18
Object Oriented Programming Using JAVA UNIT-I
Variable: A variable is a data name that may be used to store a data value. A variable may take
different values at different times during execution. A variable name can be chosen by the programmer
in a meaningful way so as to reflect what it represents in the program.
Rules for a variable:
• They must begin with a letter.
• The upper and lowercase are distinct.
• It should not be a keyword.
• White spaces are not allowed.
• Variable names can be of any length.
Declaration of variables: In Java, variables are the name of storage locations. After designing suitable
variable names, we must declare them to the compiler.
• It tells the name of the variable.
• It specifies the type of data.
• The place of declaration decides the scope of the variable.
Syntax: type variable_1, variable_2, . . . . . variable_n;
Example: int a,b;
Assigning values to variables: A variable must be given value after it has been declared but before it
is used in an expression.
1. By using an assignment statement:
Syntax: variable name=value; Example: x=0;
It is also possible to assign a value to a variable at the time of its declaration.
Syntax: type variable name=value; Example: int y=2;
The process of giving initial values to variable is known as the initialization. If the variable is
not initialized, it is automatically set to zero.
2. By using a Read statement:
import java.io.*;
Class Reading
{
public static void main(String args[])throws Exception
{
InputStreamReader instr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(instr);
int n=0;
float m=0.0f;
System.out.println(“Enter an integer”);
19
Object Oriented Programming Using JAVA UNIT-I
n=Integer.parseInt(br.readLine());
System.out.println(“Enter a float value”);
m=Float.valueOf(br.readline()).floatValue();
System.out.println(“N=”+ n);
System.out.println(“M=”+ m);
}
}

Scope of variables: The area of the program where the variable is accessible is called its scope.
1. Instance variables: Instance and class variable are declared inside a class. Instance variables are
created, when the objects are instantiated and therefore they are associated with the objects. They
take different values for each object.
2. Class variables: Class variable are global to a class and belong to the entire set of objects that
class creates. Only one memory location is created for each class variable.
3. Local variables: Variables declared and used inside methods are called local variable. They are
not available for the outside the method definition. Local variables can also be declared inside
program blocks that are defined between an opening brace and a closing brace.

Type casting: Type casting is a process of converting one data type to another data type.
Syn: type variable_1 = (type) variable_2
Casting into a smaller type may result in a loss of data. The float and double can be cast to any
other type except Boolean. Casting a floating point value to an integer will result in a loss of the
fractional part.
Example: int m=50; byte n = (byte) m;
Automatic type conversion is possible only if the destination type has enough precession to
store the source value. For example, int is large enough to hold a byte value.
Example: byte b=75; int a=b;

The following conversions will not have any loss of data.

From To
Byte short, char, int, long, float, double
Short int, long, float, double
Char int, long, float, double

20
Object Oriented Programming Using JAVA UNIT-I
Int long, float, double
Long float, double
Float Double

• The process of assigning a smaller type to a larger one is known as widening or promotion
• The process of assigning a larger type to a smaller one is known as narrowing.

// EXAMPLE ON TYPECASTING

class Dataconversion

{
public static void main(String args[])
{
byte m=50;
System.out.println("m="+m);

int n=m;
System.out.println("n="+n);
}
}
OUTPUT:
D:\java>javac Dataconversion.java
D:\java>java Dataconversion
m=50
n=50
Operators: An operator is a symbol that tells the computer to perform certain mathematical or logical
operations. Types of Operators:

1. Arithmetic 5. Increment and decrement

21
Object Oriented Programming Using JAVA UNIT-I
2. Relational 6. Conditional

3. Logical 7. Bit wise

4. Assignment 8. Special

1.Arithmetic Operators: Arithmetic operators are used to construct mathematical expressions.

Arithmetic operations are classified as:


Operator Meaning
Integer arithmetic (Both operands are integers)
+ Addition
Real arithmetic (Both operands are real numbers)
- Subtraction
Mixed mode arithmetic (one operand is int and another one is real)
* Multiplication
Example: a + b, X / y
/ Division

% Modulo Division

2.Relational Operators: These are used to compare two


Operator Meaning
values. An expression, which containing a relational operator
is termed as a relational expression. The result of a relational < Is less than
expression is either true or false
<= Is less than or equal to
Example: 35>55 false
> Is greater than
35==25+10 true
>= Is greater than or equal to

== Is equal to

!= Is not equal to

22
Object Oriented Programming Using JAVA UNIT-I
3.Logical Operators: An expression, which combines one or more relational expressions, is termed as

Operato Meaning Example a logical expression.

&& AND (a>b)&&(a>c)

|| OR (a>b)||(a>c)

! NOT !(a>b)

Example: a=10, b=5, c=15

i=(a>b) &&(b>c) then value of i is false

4. Assignment Operator (=): Assignment operators are used to assign the value to a variable.

Syntax: variable = expression;


Example: sum = a + b;

5. Increment and decrement Operators: The operator ++ adds 1 to the operand and the operator - -
subtracts 1 from operand. We use the increment and decrement statements in for and while loops
extensively.

A pre-increment operator first adds 1 to the operand and then the result is assigned to the variable on
left.

m=5; y=++m;

A post-increment operator first assigns the value to the variable on the left and then increment the
operand.

m=5; y=m++;

A pre-decrement operator first subtracts 1 from the operand and then the result is assigned to the variable
on left. Ex:m=5; y = --m;

A post-decrement operator first assigns the value to the variable on the left and then decreases the
operand by 1. Ex: m=5; y=m--;

6.Conditional operator: Conditional operator is a combination of ? , : and takes three operands. So it


is a ternary operator.

Syn: (expression_1)?(expression_2): (expression_3);


23
Object Oriented Programming Using JAVA UNIT-I
Example: a=10; b = 15;

x = (a > b)? a: b;

In the above example x will be assigned the value of b as the value of a is not greater than the value of
b.

7.Bit wise Operators: These operators are used for testing the bits, or shifting them right or left.

Operator Meaning

& bit wise AND

| bit wise OR

^ bit wise exclusive OR

<< shift left

>> shift right

>>> shift right with zero fill

~ one’s complement
8. Special Operator:

a. Instanceof operator: This operator allows us to find whether the object belongs to a particular class
or not.

Example: x instanceof student;

It is true, if the object x belongs to the class student; otherwise it is false.

b. Dot operator: The dot operator (.) is used to access the instance variable and methods of class objects.

Ex: x.rno, x.name, x.average() It is also used to access classes and sub-packages from a package.

Arithmetic expressions: An arithmetic expression is a combination of variables, constants and


arithmetical operators arranged as per the syntax of the language.
Example: (m+n) * (x+y)
There are three types of arithmetic expressions. They are:
1. Integer Arithmetic Expression: It is an expression in which all the operands are integers and
the result is also an integer.

24
Object Oriented Programming Using JAVA UNIT-I
Ex: a=5; b= 6;
a + b = 11
2. Real Arithmetic Expression: It is an expression in which all the operands are real and the result
is real.
Ex: a=2.5; b= 3.5;
a + b = 6.0
3. Mixed Mode Arithmetic Expression: It is an expression in which all the operands are both
integers and real and the result is real.
Ex: a=2.5; b= 6;
a + b = 8.5
Evaluation of expressions: Expressions are evaluated using an assignment statement such as
Variable = expression;
Variable is any valid java variable name. When the statement is encountered the expression
is evaluated first and the result will replaces the previous value of the variable on the left-hand side.
All variables used in the expression must be assigned values before evaluation is attempted.

Operator precedence and associatively: The precedence is used to determine how expression
involving more than one operator is evaluated. The operator at the higher level of precedence is
evaluated first. The operators of the same precedence are evaluated either from left to right or from
right to left, depending on the level. This is known as the associatively property of an operator.

Operator Description Association Rank


. Member selection
() Method call Left to right 1
[ ] Array element reference
- Unary minus
++ Increment
-- Decrement Right to left 2
! Logical not
~ One’s complement
* Multiplication
/ Division Left to right 3
% Modulo division

25
Object Oriented Programming Using JAVA UNIT-I
+ Addition
Left to right 4
- Subtraction
<< Left shift
>> Right shift Left to right 5
>>> Right shift zero fill
< Less than
<= Less than or equals to
Left to right 6
> Greater than
>= Greater than or equals to
== Equality
Left to right 7
!= inequality
& Bitwise and 8
^ Bitwise Xor 9
| Bitwise or 10
&& Logical and Left to right 11
|| Logical or 12
?: Conditional operator 13
= Assignment operator 14

26

You might also like