0% found this document useful (0 votes)
100 views29 pages

Fundamentals of Object Oriented Programming

POP focuses on functions and uses global data that is accessible by all functions. This makes data security difficult. OOP treats data as critical and ties it closely to the functions that operate on it. OOP divides programs into objects that encapsulate both data and methods. This provides better security and makes programs easier to extend and maintain as systems scale up. Some key OOP concepts are classes, objects, encapsulation, inheritance, polymorphism and abstraction which help manage complexity and reuse code.

Uploaded by

kkalyani
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)
100 views29 pages

Fundamentals of Object Oriented Programming

POP focuses on functions and uses global data that is accessible by all functions. This makes data security difficult. OOP treats data as critical and ties it closely to the functions that operate on it. OOP divides programs into objects that encapsulate both data and methods. This provides better security and makes programs easier to extend and maintain as systems scale up. Some key OOP concepts are classes, objects, encapsulation, inheritance, polymorphism and abstraction which help manage complexity and reuse code.

Uploaded by

kkalyani
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/ 29

UNIT-!

KHK

Fundamentals of Object Oriented Programming


What is procedure oriented programming (POP)?
 In procedural programming programs are divided into a number of segments known
as subprograms.
 It focuses on functions apart from the data. The sub programs can access to the same
global data, here also the data is not fully protected.
 The control of programs is transferred using unsafe goto statement.
 These languages are used for developing medium size applications.

What are the limitations of POP?


 Large size programs are divided into smaller programs known as functions. These
functions can call one another. Hence security is not provided.
 Importance is not given to security of data but on doing things(functions).
 Data passes globally one function to another.
 Most functions have access to global data.
 Extension of the program was very difficult; the data structure is access by no of
functions.
 Once we modify the structure of the data we need to modify all the functions who
accessing the data structure.

Explain object oriented paradigm?


 It is an approach that provides a way of modularizing program by creating partitioned
memory area for both data and functions that can be used as template for creating
copies of such modules on demand.
 OOP treats data as critical element in the program development and does not allow it
to flow freely around the system.
 It ties the data more closely to the functions that operate on it.

Vasavi Degree College 1


UNIT-! KHK

 OOP allows us to decompose the problem into number of entities called Objects.

 Data of object can be accessed only by the methods associated with that object.
 It follows Bottom-Up approach in program development.

What are the advantages of OOP ?


OOP offers several benefits to both the program designer and the user. The principal
advantages are:
 Using inheritance we can extend the program very easily and can eliminate the
duplication of code.
 OO systems can be easily upgraded from small to large systems.
 It is easy to partition the work in a project based on objects.
 The concept of data hiding helps the programmer to develop secure programs.
 Software complexity can be easily managed

Explain the applications OOPS ?


Since 1960, when Simula-67 was developed, object-oriented paradigm has touched many
major application areas of software development. Some of the application areas where OOP
has been used to develop software are
Simulations and Modelling:
Simulation is the technique of representing the real world entities with the help of a
computer program. Simula-67 and Smalltalk are two object-oriented languages are
designed for making simulations.

Vasavi Degree College 2


UNIT-! KHK

User-interface design:
Another popular application of OOP has been in the area of designing graphical user
interfaces such as Windows. C++ is mainly used for developing user-interfaces.
Developing computer games:
OOP is also used for developing computer games . These games offer virtual reality
environments in which a number of objects interact with each other in complex ways
to give the desired result.
Scripting:
In recent years, OOP has also been used for developing HTML, XHTML and XML
documents for the Internet. Python, Ruby and Java are the scripting languages based
on object-oriented principles which are used for scripting.
Object Databases:
These days OOP concepts have also been introduced in database systems to develop a
new DBMS named object databases. These databases store the data directly in the
form of objects. However, these databases are not as popular as the traditional
RDBMS.
Office Automation Systems
These include formal as well as informal electronic systems primarily concerned with
information sharing and communication to and from people inside as well as outside
the organization. Some examples are:
Email
Word processing
Web calendars
Desktop publishing
CIM/CAD/CAM Systems
OOP can also be used in manufacturing and design applications as it allows people to
reduce the effort involved.OOP makes it possible for the designers and engineers to
produce flowcharts and blueprints accurately.
AI Expert Systems
These are computer applications which are developed to solve complex problems
pertaining to a specific domain, which is at a level far beyond the reach of a human
brain.

Vasavi Degree College 3


UNIT-! KHK

Explain the basic concepts of Object - Oriented Programming?


OOP is programming model that uses “objects “ and their interaction to design applications
and computer programs. The basic concepts of Oops language are:

Class:
 A class is a template definition of the methods and variables for a particular kind of
object. In other words , class is the blue print ( logical representation) from which an
individual objects is created.

Object:
 An Object is a real time entity. It is also known as instance of a class.
 An object will have some properties and it can perform some actions. Object contains
variables and methods.
 The objects which exhibit similar properties and actions are grouped under one class.

Encapsulation:
 Wrapping up of data (variables) and methods into single unit is called Encapsulation.
Encapsulation can be described as a protective mechanism that prevents the code and
data being accessed by other code defined outside the class.
Abstraction:
 Providing the essential features without its inner details is called abstraction (or)
hiding internal implementation is called Abstraction.
 We can enhance the internal implementation without effecting outside world.
Abstraction provides security.
Inheritance:
 Acquiring the properties from one class to another class is called inheritance (or)
producing new class from already existing class is called inheritance.

Vasavi Degree College 4


UNIT-! KHK

 Reusability of code is main advantage of inheritance.


 The relation between the two class is known as “is a” relation.

Polymorphism:
 The word polymorphism came from two Greek words „poly‟ means „many‟ and
„morphos‟ means „forms‟. Polymorphism represents the ability to assume several
different forms. The ability to define more than one function with the same name is
called Polymorphism.
Dynamic Binding:
 It is also known as dynamic dispatch, it is the process of linking function call to a
specific function definition at run-time.
 Dynamic binding is also known as late binding.

Message Passing:
 OOPS includes objects which communicate with each other.
 Objects communicate with one another by sending and receiving information much
the same way as people pass messages to one another.

Vasavi Degree College 5


UNIT-! KHK

Data
Data

Function Function

Delegation:
 When objects of one class is used as data member in another class, such composition
of objects is known as delegation.
 Such a relation between two classes is known as “ has a” relation.

Explain Differences between POP and OOP:

Procedure Oriented Programming Object Oriented Programming

1. Main program is divided into small parts 1. Main program is divided into small object
depending on the functions depending on the problem
2. Functions get more importance than data 2. Data gets more importance than functions
in program. in Program
3. Most of the functions use global data. 3. Each object controls its own data
4.Same data may be transfer from one 4.Data does not possible transfer from one
function to another object to another
5. There is no perfect way for data hiding 5. Data hiding possible in OOP which
prevent illegal access of function from
outside of it. This is one of the best
advantages of OOP also.

6. More data or functions can not be added 6. More data or functions can be added with
easily Program very easily
.
7. Top down process is followed for 7. Bottom up process is followed for
program design. program design.

8. Example: C++, Java.


8. Example: Pascal, Fortran

Vasavi Degree College 6


UNIT-! KHK

Explain java features?


The development team of java wanted the language to be portable, reliable and
distributed but also simple. Apart from above the java has the following features.
Simple
 Java inherits the C/C++ syntax and many of the object-oriented features of C++. Also,
some of the more confusing concepts from C++ are eliminated from Java
Object-Oriented
 Java designed as pure object oriented language. We require minimum one class to
develop a program. The object model in Java is simple and easy to extend.
Robust
The ability to create robust programs was given a high priority in the design of Java.
 Java is a strictly typed language; it checks your code at compile time also at run time.
 Java eliminates manually disallocati0n of dynamically allocated memory i.e.
deallocation is completely automatic.
 Java provides object-oriented exception handling. In a well-written Java program, all
run-time errors can and should be managed by your program.
Multithreaded
 Java supports multithreaded programming, which allows you to write programs that
do many things simultaneously.
 This feature greatly improves the interactive performance of graphical and game
applications.
Platform independent and Architecture-Neutral
 Java programs can be easily moved from one computer to another , anywhere and
anytime.
 The Java Virtual Machine (JVM) made the java language platform independent and
architecture neutral.
Interpreted and High Performance
 Java enables the creation of cross-platform programs by compiling into an
intermediate representation called Java bytecode.
 The Java bytecode was carefully designed so that it would be easy to translate directly
into native machine code for very high performance by using a just-in-time compiler.

Vasavi Degree College 7


UNIT-! KHK

Portable:
 Java ensures portability in two ways. First java compiler generates bytecode
instructions that can be implemented on any machine. Secondly the size of the
primitive data types are machine – independent.
Distributed
 Java is designed for the distributed environment of the Internet, because it handles
TCP/IP protocols
 Java included features for intraaddress-space messaging. This allowed objects on two
different computers to execute procedures remotely.
Dynamic
 Java programs carry with them substantial amounts of run-time type information that
is used to verify and resolve accesses to objects at run time. This makes it possible to
dynamically link code in a safe and expedient manner.
Security
 Java systems not only verify all memory access but also ensure that no viruses are
communicated with an applet . the absence of pointers in java ensures that programs
can not gain access to memory locations.

Vasavi Degree College 8


UNIT-! KHK

Overview of Java language


Differentiate between C and JAVA?
1. JAVA is Object-Oriented while C is procedural.
2. Java is an Interpreted language while C is a compiled language.
3. C is a low-level language while JAVA is a high-level language.
4. C uses the top-down approach while JAVA uses the bottom-Up approach.
5. JAVA cannot support pointers while C requires explicit handling of pointers.
6. JAVA supports Method Overloading while C does not support overloading at all.
7. Unlike C, JAVA does not support Preprocessors.
8. Exception Handling is strong in JAVA where as in C language very difficult to handle
run time errors.
Explain java environment?
Java environment includes a large number of development tools and hundreds of
classes and methods. The development tools are the part of the system known as Java
Development Kit (JDK) and the classes and methods are the part of Java Standard
Library (JSL) also known as the application Programming Interface (API).

Java Development Kit (JDK):


The Java Development Kit comes with a collection of tools are used for developing
and running java programs. They include
 appletviewer  javap
 javac  javadoc
 java  jdb
 javah
The source code is compiled using the java compiler “JAVAC” and executed by using
java interpreter “java”. The java debugger ”jdb” is used to find errors if any. A
compiled java program can be converted into a source code with the help of java
disassembler (javap).

Vasavi Degree College 9


UNIT-! KHK

Application Programming Interface (API) :


The java Standard library includes hundreds of classes and methods grouped into
several functional packages. The most commonly used packages are
 java.lang  java.net
 java.util  java.awt
 java.io  java.applet

Explain Java Runtime Environment?


Java Runtime Environment (JRE) is a set of software tools for the development of
Java applications. It combines Java Virtual Machine (JVM), and platform core classes
and auxiliary libraries. If JRE is not installed on the computer, then Java programs
cannot be recognized by the operating system and will not run.
JRE software provides a runtime environment in which Java programs can be
executed, such as software programs that have been compiled for computer
processors. JRE software is available as both a standalone environment and a web
browser plug-in, which allows Java applet to run in a web browser.
A Java Runtime Environment performs the following main tasks respectively.

Vasavi Degree College 10


UNIT-! KHK

 Loads the class


 Verifies the byte-code
 Interprets the byte-code
Class Loader
Class loader loads all the class files needed to execute the program. Once the byte-
code has been successfully loaded, the next step is the byte-code verifier byte-code
verifier.
Byte-code Verifier
The byte-code verifier verifies the byte code to see if any security problems are there
in the code. Once this code has been verified and proven that there is no security
problem with the code, JVM will convert the byte code to the machine code which
will be executed directly by the machine in which the Java program runs.
Just in time (JIT) compiler
When Java program is executed, byte code is interpreted by JVM. But this
interpretation is a slow process. To overcome this difficulty, the JRE Component JIT
compiler is included. JIT makes execution faster. If the JIT compiler library is
present, when a special byte code is executed for the first time, JIT compliance
compiles it into native machine code that can be run directly by the Java machine.
Once the bytecode is compiled into that particular machine code, it is cached by the
JIT compiler and will be reused for future needs.

The java runtime environment (JRE) facilitates the execution of programs developed
in java. It basically consists of the following:

Vasavi Degree College 11


UNIT-! KHK

Java virtual machine:


It is the program that interprets the intermediate byte code and generates desired
output.
Runtime class Libraries:
Set of class libraries that are required for execution of java program.
User interface toolkits:
This includes different input methods for the users to interact with the application
program.
Deployment technologies:
JRE comprises the following key deployment technologies
 Java plugins
 Java web start

Explain Java program structure ?


To write java program, we first define classes and then put them together. A jav program may
contain one or more sections.

Documentation Section:
 The documentation comprises a set of comment lines giving the name of the program,
the author and other details, which the programmer would like to refer at a latter
stage.
 Java supports three types of comments single line comments ( // ), multi line
comments(/*… */) , documentation comments(/** ... */)

Vasavi Degree College 12


UNIT-! KHK

Package Statements:
 The first statement allowed in java file is a package statement, this statements declares
a package name and informs the compiler that the classes defined here belong to this
package.
package pack_name;
 The package statement is optional, that is our classes do not have to be a part of a
package.
Import statement:
 The next statement after a package statement may be a number of import statements.
This is similar to the #include statement in C.
import java . lang. * ;
import java . awt . * ;
 This statement instructs the interpreter to load the classes contained in the packages
mentioned.
Interface statement:
 An interface is like a class but includes a group of method declarations. This is also an
optional statement and is used only when we wish to implement the multiple
inheritance feature in the program. Interface is new concept in the java.
Class Definition:
 A java program may contain multiple class definitions. Classes are the primary
essential elements of a java program. The no of classes used depends on the
complexity of the problem.
Main method class:
 Since every java stand alone program requires a main method as its starting point.
This class is defined the essential part of a java program.
 A simple java program may contain only this part. The main method creates objects
of various classes and establishes communications between them.

What is byte code?


 Bytecode is a highly optimized set of instructions designed to be executed by the Java
run-time system, which is called the Java Virtual Machine (JVM). That is, in its
standard form, the JVM is an interpreter for bytecode.

Vasavi Degree College 13


UNIT-! KHK

 Bytecode is the result of compiling source code written in a language that supports
this approach.

Java Java
Byte Code
Program Compiler

 The best-known language today that uses the bytecode is java, LISP , ICON, Prolog.

What is Java Virtual Machine:


 Java Virtual Machine (JVM) is the heart of entire Java program execution process.

First of all, the .java program is converted into a .class file consisting of byte code

instructions by the java compiler at the time of compilation.


 The JVM exists only inside the computer memory . it is a simulated computer with in
the computer

Explain Java Tokens?


A token is the smallest element of a program that is meaningful to the compiler. These tokens
define the structure of the Java language. The compiler recognizes them for building up
expressions and statements. Java tokens can be broken into five categories:
 Identifiers
 keywords
 literals
 operators
 separators

Vasavi Degree College 14


UNIT-! KHK

Keywords:
 It is a special type of reserved word for a specific purpose in the program
development.
 There are 50 keywords currently defined in the Java language. All the keywords must
be written in lower case
Ex: abstract, byte, class extends, private , protected , case , switch, if , else

Identifiers:
Identifiers are the names given by the programmer to variables, methods, and classes to
identify them to the compiler
 The can have letters, numbers, or the underscore( _ ) and dollar-sign($) characters
 Must not begin with a number.
 Upper case and Lower case letters are distinct.
 They can be of any length.

Valid Invalid
HelloWorld Hello World (uses a space)
Hi_JAVA Hi JAVA! (uses a space and punctuation mark)
value3 3value(begins with a number)
Tall short (this is a Java keyword)
$age #age (does not begin with any other symbol except _ $ )

Literals:
Literals in java are sequence of characters that represents constant values to be stored
in variables. Java language specifies five major types of literals:
 Integer Literals. (10,20)
 Floating point literals.(10.234)
 Character literals.(„J‟)
 String literals. (“java”)
 Boolean literals. (true, false)

Vasavi Degree College 15


UNIT-! KHK

Operators:
Operator is a special symbol that takes one or more arguments and operates on them
to produce a result. Java provides a rich set of operators to manipulate variables. We
can divide all the Java operators into the following groups:
 Arithmetic Operators
 Relational Operators
 Bitwise Operators
 Logical Operators
 Assignment Operators
 Misc Operators
Separators:
Separators are used to inform the Java compiler of how things are grouped in the
code. For example, items in a list are separated by commas much like lists of items in
a sentence. The most commonly used separator in Java is the semicolon.

Symbol Name
; Semicolon
, Comma
{} Braces
() Parentheses
[] Brackets
. Period

Explain how to implement java program?


(OR)

Explain the steps involved in developing a java program?


Implementation of a java application program involves a series of steps they include: edit,
compile, and run a Java program.
 Editing a Program
Any text editor may be used to edit a program by typing the program and
making corrections as needed.

Vasavi Degree College 16


UNIT-! KHK

 Compiling a Program
The Java source programs have to compile it into the Java bytecode, the
intermediate code understood by the Java Virtual Machine (JVM).
The Java SDK compiler is named javac. At the Windows command prompt
HelloWorld.java file would be compiled by typing the following command :

javac HelloWorld.java
 Running a Java Application Program
In order to run a java program (or execute) a program on any computer, the
program's .class file must be loaded into the computer's memory, where it is then
interpreted by the Java Virtual Machine(JVM). To run a Java program on Windows
command prompt, type
java HelloWorld
on the command line. This command loads the JVM, which will then load and
interpret the application's bytecode (HelloWorld.class).

Explain different types of java statements:


A statement is an executable combination of tokens ending with a semicolon( : ).
Mark. Statements are usually executed in sequence in the order in which they apper..
java implements several types of statements they are:
Declaration statement:
The statement that declares a variable of a particular type. In Java, a variable must be
declared any where before it can be used in a program.
type VariableName ;
Ex: int sno;
double sal;
Assignment statement:
The statement that stores (assigns) a value in a variable. An assignment statement uses
the equal sign (=) as an assignment operator. Like other statements, an assignment
statement ends with a semicolon:
VariableName = Value ;
greeting = "Hello World";
num1 = 50; // (a) Assign 50 to num1
num2 = 10 + 15; // (b) Assign 25 to num2

Vasavi Degree College 17


UNIT-! KHK

num1 = num2; // (c) Copy num2's value (25) into num1


Control flow statements
Regulate the order in which statements get executed. We can write statements using
if, switch, loops.
Jump Statements:
Jump statements pass control to the beginning or end of the current block, or to a
labelled statement. The labels must be in the same block.. java supports four types of
jump statements:
 break
 continue
 return
 throw
Blocks
A block is a group of zero or more statements between balanced braces and can be
used anywhere a single statement is allowed.

Vasavi Degree College 18


UNIT-! KHK

Constants, variables, and Data types


Write all about constants?
Constants in java refer to fixed values that do not change during the execution of a
program.java supports five types of constants:
 Integer literals
 Floating literals
 Character literals
 String literal
 Boolean literals
Integer literals:
 An integer constant refers to a sequence of digits. Java supports three types of integer
literals.
 Decimal (Base 10)
 Octal (Base 8)
 Hexadecimal (Base 16)
Floating-Point Literals
 Floating-point numbers represent decimal values with a fractional component. They
can be expressed in either standard or scientific notation.
 Floating-point literals in Java default to double precision..
double d1 = 123.4;
double d2 = 1.234e2; // same value as d1, but in scientific notation
float f1 = 123.4f;
Character constants:
 A single character constant contains a single character enclosed with in a pair of
single quote marks. Java supports Unicode character set.
String Literals
 A string constant is a sequence of characters enclosed between double quotes. The
characters may be alphabets , digits, special characters and blank spaces.
“Hello World”
“two\nlines”
 Java string is that they must begin and end on the same line.

Vasavi Degree College 19


UNIT-! KHK

Boolean Literals
 Constants which stores either true or false.
 The values of true and false do not convert into any numerical representation. The
true literal in Java does not equal 1, nor does the false literal equal 0.

Write about Escape Sequence characters?


Java supports some special backslash characters constants that are used in output
methods. Although they consists of two characters they treat as one character , these
character combinations are known as escape sequences.
Escape Sequence Description
\‟ Single quote
\” Double quote
\\ Backslash
\r Carriage return
\n New line (also known as line feed)
\f Form feed
\t Tab
\b Backspace

Explain java Data Types?


Data types specify the size and type of values that can be stored . java language is rich
in its data types. Java supports two types of data types
 Primitive data types
 Reference data types

Java defines eight primitive types of data: byte, short, int, long, char, float, double, and
boolean. The simple types are defined to have an explicit range and mathematical behavior.
These can be put in four groups:
 Integers This group includes byte, short, int, and long, which are for whole valued
signed numbers.

Vasavi Degree College 20


UNIT-! KHK

 Floating-point numbers This group includes float and double, which represent
numbers with fractional precision.
 Characters This group includes char, which represents symbols in a character set,
like letters and numbers.
 Boolean This group includes boolean, which is a special type for representing
true/false values.
Integer types:
Integer types can hold whole numbers such as 123, -90, 5678. The size of the values
that can be stored depends on the integer type we choose. Java supports four types of
integers , they are byte , short, int, long.

Type Size (bytes) Range


byte 1 -128 to 127
short 2 -32768 To 32767
int 4 -2147483648 To 2147483647
long 8 -9223372036854775808 To 9223372036854775807

We can make integers long by appending the letter L or l at the end of the number
Ex:
123L or 123 l
Floating point types:
This type holds numbers containing fractional parts such as 27.68 and -1.342. java
supports two types of floating point storage float (single precision), double (double
precision)

Vasavi Degree College 21


UNIT-! KHK

 By default all floating point numbers are double precision numbers. To make them
single precision numbers append f or F
Ex:
1.23 F
Type Size (bytes) Range
float 4 3.4 e -38 To 1.7 e+38
double 8 3.4e-38 To 1.7 e+308

Character type:
In order to store character constants in memory , java provides a character data type
called “char” . Java supports Unicode format of characters i.e. it can support 65536 no
of characters. It occupies 2 bytes of memory.

Type Size (bytes) Range


char 2 Unicode format
Boolean type:
Boolean type is used when we want to test a particular condition during the execution
of the program. There are only two possible values that a Boolean type can take:
“true” or “false”. All relational and logical operators will return booleans.
Type Size (bits) Range
boolean 1 true or false

Write all about variables?


A variable is an identifier that denotes a storage location used to store a data value. A
variable is defined by the combination of an identifier, a type, and an optional

Vasavi Degree College 22


UNIT-! KHK

initializer. In addition, all variables have a scope, which defines their visibility, and a
lifetime.
Declaring a Variable
 In Java, all variables must be declared before they can be used. The basic form of a
variable declaration is shown here:
type identifier [ = value][, identifier [= value] ...] ;
 To declare more than one variable of the specified type, use a comma-separated list
Ex:
int m1,m2,m3;

Initializing Variables
 You can initialize the variable by specifying an equal sign(assignment operator) and a
value. The initialization expression must result in a value of the same (or compatible)
type as that specified for the variable.
byte z = 22; // initializes z.
double pi = 3.14159; // declares an approximation of pi.
char x = 'x'; // the variable x has the value 'x'.
Dynamic Initialization
 Java allows variables to be initialized dynamically, using any expression valid at the
time the variable is declared.
double a = 3.0, b = 4.0;
double c = Math.sqrt(a * a + b * b); // c is dynamically initialized

Explain scope and lifetime of a variable?


 A scope determines what objects are visible to other parts of your program. It also
determines the lifetime of those objects.
 Variables are created when their scope is entered, and destroyed when their scope is
left.
 When you declare a variable within a scope, you are localizing that variable and
protecting it from unauthorized access and/or modification. The scope rules provide
the foundation for encapsulation.

Vasavi Degree College 23


UNIT-! KHK

What is a default value of a variable?


It's not always necessary to assign a value when a field is declared. Fields that are
declared but not initialized will be set to a reasonable default by the compiler.
Data Type Default Value (for fields)
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char '\u0000'
String (or any object) null
boolean false
The compiler never assigns a default value to an uninitialized local variable.

Explain Type Casting:


 Converting one type of data into another must follow the rules of casting. If a
conversion results in the loss of precision, as in an int value converted to a short, then
the compiler will issue an error message unless an explicit cast is made.
 Java supports two types of castings – primitive data type casting and reference type
casting. Reference type casting is nothing but assigning one Java object to another
object. In java conversion takes place in two ways
1. Implicit casting
2. Explicit casting
1. Implicit casting (widening conversion)
 A data type of lower size (occupying less memory) is assigned to a data type of higher
size. This is done implicitly by the JVM. The lower size is widened to higher size.
This is also named as automatic type conversion.
Examples:
int x = 10; // occupies 4 bytes
double y = x; // occupies 8 bytes
System.out.println(y); // prints 10.0
In the above code 4 bytes integer value is assigned to 8 bytes double value.

Vasavi Degree College 24


UNIT-! KHK

2. Explicit casting (narrowing conversion)


 A data type of higher size (occupying more memory) cannot be assigned to a data
type of lower size. This is not done implicitly by the JVM and requires explicit
casting; a casting operation to be performed by the programmer. The higher size is
narrowed to lower size.
Syn: type variable1 = (type) variable2
double x = 10.5;
int y = (int) x;

 A boolean value cannot be assigned to any other data type. Except boolean, all the
remaining 7 data types can be assigned to one another either implicitly or explicitly;
but boolean cannot.

class cast_ex{
public static void main (String args[ ] ){
float x =254.01f;
byte b;
b = (byte) x ; /*type conversion*/
System.out.println( " 'value of b ' "+b);
}}

Vasavi Degree College 25


UNIT-! KHK

Operators and Expressions


Explain all about operators?
Operator is special symbol which performs a specific operation the operands. An
operator takes one or more arguments and produces a new value. All operators
produce a value from their operands. In addition, an operator can change the value of
an operand. This is called a side effect. Operators can be categorised into two ways
 Based on no of operands
 Based on type of operation
Based on no of operands that an operator requires to perform its operation the
operators are three types
 Unary operators
 Binary operators
 Ternary operators
Based on type of operation that an operator performs the operators are
1. Arithmetic Operators.
2. Relational Operators.
3. Logical Operators.
4. Assignment Operators.
5. Increment, Decrement Operators.
6. Conditional Operators.
7. Bitwise Operators.
8. Special Operators.
Arithmetic Operators:
Arithmetic operators are used to construct mathematical expressions as in algebra.
Java provides all the basic arithmetic operators.
+ Addition
- Subtraction
* Multiplication
/ Division
% modulo division
These can operate on any built in numeric data type of java. We cannot use these operators on
boolean data types. All these are binary operators.

Vasavi Degree College 26


UNIT-! KHK

Relational operators
Relational operators generate a boolean result and binary operators. They evaluate the
relationship between the values of the operands.. The relational operators are
< Less than,
> Greater than,
<= Less than or equal to
>= Greater than or equal to
== Equivalent
!= Not equivalent

A simple relational expression contains only one relational operator and is of the
following form:
Op1 Relational Operator Op2
Ex:
a > b
Logical Operators:
The logical operators are used to form compound conditions by combining two or
more relations. The logical expressions also give a value of true or false according to
the truth table.java supports three types of logical operators:
&& Logical AND
|| Logical OR
! Logical NOT
Truth Table:
A B A || B A && B !A
false false false false true
true false true false false
false true true false true
true true true true false

Bitwise operators
The bitwise operators allow you to manipulate individual bits in an integral primitive
data type. Java the following bit wise operators :
bitwise AND operator ( & )
bitwise OR operator ( | )

Vasavi Degree College 27


UNIT-! KHK

bitwise, EXCLUSIVE OR, or XOR ( ^ )


bitwise NOT ( ~ )
Assignment Operator
The assignment operator is the single equal sign, =. The assignment operator works in
Java much as it does in any other computer language. It has this general form:

var = expression;

Increment and Decrement Operator:


The increment operator( ++ ) increases its operand by one. The decrement operator
( -- ) decreases its operand by one. These are unary operators.
x = 42; x = 42;
y = ++x; y = x++;

Conditional Operator:
Java includes a special ternary (three-way) operator that can replace certain types of if-else
statements. The ? : has this general form:

exp1 ? exp2 : exp3

Here, exp1 can be any expression that evaluates to a boolean value. If exp1 is true, then exp2
is evaluated; otherwise, exp3 is evaluated.

Shift operators
The shift operators also manipulate bits. They can be used solely with primitive,
integral types.
left-shift operator (<<)
right-shift operator (>>)

SPECIAL OPERATORS
Java supports some special operations of interest such as instanceof operator and
member selection operator( . ) and comma operator.

Vasavi Degree College 28


UNIT-! KHK

What is an Operator Precedence and Associativity?


Each operator in java has a precedence associated with it. This precedence is used to
determine how an expression involving more than one operator is evaluated. The operators of
the same precedence are evaluated either from left to right or from right to left depending on
the level.

Vasavi Degree College 29

You might also like