0% found this document useful (0 votes)
174 views159 pages

Chapter2 Oop

The document discusses object-oriented programming paradigms. It describes the key activities in object-oriented software development like object-oriented analysis, design, and programming. It also discusses some core object-oriented programming principles like objects, classes, abstraction, encapsulation, inheritance, and polymorphism.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
174 views159 pages

Chapter2 Oop

The document discusses object-oriented programming paradigms. It describes the key activities in object-oriented software development like object-oriented analysis, design, and programming. It also discusses some core object-oriented programming principles like objects, classes, abstraction, encapsulation, inheritance, and polymorphism.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 159

Object-oriented Programming Paradigm

2-4

• The software applications developed using object-oriented


programming paradigm is:
• Designed around data, rather than focusing only on the functionalities.

• Following shows different activities involved in the object-oriented


software development:

Object-oriented Programming
Paradigm 3-4
Object-oriented Analysis (OOA) phase determines
the functionality of the system.

Object-oriented Design (OOD) phases


determines the process of planning a system in
which objects interact with each other to solve a
software problem.

Object-oriented Programming (OOP) deals with


the actual implementation of the application.

• Unified Modeling Language (UML) helps to create visual models in the system.
• The actual implementation of these visual models is done using an OOP language.
Object-oriented Programming Paradigm 4-4
• An OOP language is based on certain principles that are as follows:
• Object – Represents an entity which possesses certain features and
behaviors.
• Class – Is a template that is used to create objects of that class.
• Abstraction – Is a design technique that focuses only on the essential
features of an entity for a specific problem domain.
• Encapsulation – Is a mechanism that combines data and implementation
details into a single unit called class.
• Inheritance – Enables the developer to extend and reuse the features of
existing classes and create new classes. The new classes are referred to as
derived classes.
• Polymorphism – Is the ability of an object to respond to same message in
different ways.
Concept of an Object 1
• An object represents a real-4-world entity.
• Any tangible or touchable entity in the real-world can be
described as an object.
• Following figure shows some real-world entities:
Concept of an Object 2-4

• Each object has:


• Characteristics – Defined as attributes, properties, or features
describing the object.
Concept of an Object 3-4
• Actions – Defined as activities or operations performed by the object.
 Example of an object, Dog.
 Properties – Breed, Color, and Age
 Actions – Barking, Eating, and Running

 The concept of objects in the real-world can be extended


to the programming world where software ‘objects’ can
be defined.
• A software object has state and behavior.
• ‘State’ refers to object’s characteristics or attributes.
Concept of an Object 4-4
• ‘Behavior’ of the software object comprises its actions.
• Following figure shows a software object, a Car with its state
and behavior:
• The advantages of using objects are as follows: • They help to
understand the real-world.
1
• They map attributes and actions of real-world entities with state and
behavior of software
2 objects.
Defining a Class 1-3
• In the real-world, several objects:
• Have common state and behavior.
• Can be grouped under a single class.
• Example: All car objects have attributes, such as color, make, or model.
• Class:
• Can be defined that a class is a template or blueprint which defines the
state and behavior for all objects belonging to that class.
• Following figure shows a car as a template and a Toyota car as an object or
instance of the class:
Defining a Class 2-3
• Class comprises fields and methods, collectively called as
members.
• Fields – Are variables that depict the state of objects.
• Methods – Are functions that depict the behavior of objects.
Defining a Class 3-3
• Following table shows the difference betweenObject
a class and an
object:Class
Class is a conceptual model Object is a real thing
Class describes an entity Object is the actual entity
Class consists of fields (data Object is an instance of a class
members) and functions
Creating a Java Class
Objectives
• Explain the structure of a Java class
• List and explain steps to write a Java program
• Identify the benefits of NetBeans IDE
• Describe the various elements of NetBeans IDE
• Explain the steps to develop, compile, and execute Java program
using NetBeans IDE
• Explain the various components of JVM
• Describe comments in Java
Introduction 1-2
• Java is a popular OOP language that supports developing applications for
different requirements and domain areas.

• All types of applications can be developed:


• In a simple text editor, such as Notepad.
• In an environment that provides necessary tools to develop a Java application.
• The environment is called as Integrated Development Environment (IDE).
Introduction 2-2
Console-
• Following figure shows the type of applications developed using Java
based
Application

Window-
Applets based
Application

Java
Applications

JavaBeans Enterprise
Component Components

Server-side
Web
Components
Structure of a Java Class 1-5
• The Java programming language is designed around object-oriented features and
begins with a class design.
• The class represents a template for the objects created or instantiated by the
Java runtime environment.
• The definition of the class is written in a file and is saved with a .java
extension.
Structure of a Java Class 2-5
• Following figure shows the basic structure of a Java class.

package

• Defines a namespace that stores classes with similar functionalities in them.


Structure of a Java Class 3-5
• The package keyword identifies:
• Name of the package to which the class belongs.
• Visibility of the class within the package and outside the package.
• The concept of package is similar to folder in the OS.
• In Java, all classes belongs to a package. If the package statement is not specified, then the class
belongs to the default package.
• Example: All the user interface classes are grouped in the java.awt or java.swing
packages.
import

• Identifies the classes and packages that are used in a Java class.
Structure of a Java Class 4-5
• Helps to narrow down the search performed by the Java compiler by informing it about the
classes and packages.
• Mandatory to import the required classes, before they are used in the Java program.
• Some exceptions wherein the use of import statement is not required are as follows:
• If classes are present in the java.lang package.
• If classes are located in the same package.
• If classes are declared and used along with their package name.
For example, java.text.NumberFormat nf = new
java.text. NumberFormat();
Structure of a Java Class 5-5
class

• classkeyword identifies a Java class.


• Precedes the name of the class in the declaration.
• publickeyword indicates the access modifier that decides the
visibility of the class.
• Name of a class and file name should match.

Variables

• Are also referred to as instance fields or instance variables.


• Represent the state of objects.
Structure of a Java Class 6-5
Methods

• Are functions that represent some action to be performed on an


object.
• Are also referred to as instance methods.

Constructors

• Are also methods or functions that are invoked during the creation of an object.
• Used to initialize the objects.
Developing a Java Program on
Windows

• Basic requirements to write a Java program are as follows:


• The JDK 7 installed and configured on the system.
• A text editor, such as Notepad.

• To create, compile, and execute a Java program, perform the following steps:
Create a Java Program 1-4

public class HelloWorld { args) {


“Welcome to the world of Java”);
Following code snippet demonstrates a simple Java
program:public static void main(String[]
System.out.println(
}
}

Build and
Create a Java Compile
execute Java
program .javafile
program

Create a Java Program 2-4
• class is a keyword and HelloWorld is the name of the class.
• The entire class definition and its members must be written within the opening
and closing curly braces {}.
• The area between the braces is known as the class body and contains the code
for that public class HelloWorld { class.
• Following
c ode snippet demonstrates a simple Java prograpublic static
void main(String[] args) m: {
System.out.println(“Welcome to the world of Java”);
}
}

• main()- method is the entry point for a java-based console application.


Create a Java Program 3-4
• public - Is a keyword that enables the JVM to access the main() method.
• static- Is a keyword that allows a method to be called from outside a class without creating an
instance of the class.
• void- Is a keyword that represents the data type of the value returned by the main() method. It
informs the compiler that the method will not return any value.
• args - Is an array of type String and stores command line arguments. String is a class in Java
and stores group of characters.
Createpublic
a Java Program
class HelloWorld {
4-4

Following code snippet demonstrates a simple Java program: public static
void main(String[] args) {
System.out.println(“Welcome to the world of
Java”); }
}
• System.out.println() statement displays the string that is passed as an
argument.
• System is the predefined class and provides access to the system resources, such as
console.
• out is the output stream connected to the console.
• println() is the built-in method of the output stream that is used to display a
string.
Createpublic
a Java Program 5-4
class HelloWorld {
• Following code snippet demonstrates a simple Java program:public
static void main(String[] args) {
System.out.println(“Welcome to the world of Java”);
}
}

• Save the file as HelloWorld.java.


• The file name is same as class name, as the compilation of a Java code results in
a class. Hence, the class name and the file name should be same.
Compile .java File 1-4
• Following figure shows the compilation process of the Java program.

• The HelloWorld.java file is known as source code file.


• It is compiled by invoking tool named javac.exe, which compiles the source
code into a .class file.
• The .class file contains the bytecode which is interpreted by java.exe
tool.
Compile .java File 2-4
• java.exe interprets the bytecode and runs the program.
Syntax
• The javac.exe syntax
to use javac [option] source the
command:

where, source - Is one or more file names that end with a .java
extension.
Compile .java File 3-4
• Following table lists some of the options that can be used with the javac
command:
Option Description
-classpath Specifies the location for the imported classes (overrides

Compile
-d
.javaSpecifies
Filethe4-4 the CLASSPATH environment variable)
destination directory for the generated class
• files
-g Prints all debugging information instead of the default line
number and file name
-verbose Generates message while the class is being compiled
-version Displays version information
Sourcepath Specifies the location of the input source file
-help Prints a synopsis of standard options
For javac -d c:\
example, HelloWorld.java will create and save
HelloWorld.class file in the C:\ drive.
• To compile the HelloWorld.java program from the Windows platform, the
user can:
• Click Start menu.
Compile .java File 5-4
• Choose Run.
• Enter the cmd command to display the Command Prompt window.

• Following figure shows the


Command Prompt window:

• Set the drive and directory path to the directory containing .java file. For example, cd
H:\Java.
• Type the command, javac HelloWorld.java and press Enter.
Build and Execute Java Program 1-4
• The JVM is at the heart of the Java programming language.
• It is responsible for executing the .class file or bytecode file.
• The .class file can be executed on any computer or device, that has
the JVM implemented on it.
Build and Execute Java Program 2-4
• Following figure shows the components of JVM involved in the execution of the

compiled bytecode.
The class loader component of JVM loads all the
necessary classes from the runtime libraries required
for execution of the compiled bytecode.
Build and Execute Java Program 3-4
The bytecode verifier then checks the code to
ensure that it adheres to the JVM specification.

The bytecode is executed by the interpreter.

To boost the speed of execution, in Java version 2.0,


a Hot Spot Just-in-Time (JIT) compiler was included
at runtime.
During execution, the JIT compiler compiles some of the code
into native code or platform-specific code to boosts the
performance.

• The Java interpreter command, java is used to interpret and run the Java
bytecode. Syntax
Build and Execute Java Program 4-4
• The java.exe java
syntax [option] classname [arguments]] to use
the command is as follows:

where,
classname: Is the name of the class file.
arguments: Is the arguments passed to the main function.

• To execute the HelloWorld class, type the command, javaHelloWorld


and press Enter.
Build and Execute Java Program 5-4

Option Description
classpath Specifies the location for the imported classes (overrides the
CLASSPATH environment variable)
-v or –verbose Produces additional output about each class loaded and each
source file compiled
-version Displays version information and exits
-jar Uses a JAR file name instead of a class name
-help Displays information about help and exits
-X Displays information about non-standard options and exits
Following table lists some of the options that can be used with the java
command:
NetBeans IDE 1-7
• It is an open-source integrated development environment written purely in Java.
• It is a free and robust IDE that helps developers to create cross-platform
desktop, Web, and mobile applications using Java.
• It contains features such as code completions, code template, and fix import for
faster development.
• Some of its benefits are as follows:
• Provides plug-in modules and supports rich client applications.
• Provides graphical user interface for building, compiling, debugging, and packaging of
applications.
• Provides simple and user-friendly IDE configuration.
• The NetBeans IDE has the following elements and views:
• Menu Bar
NetBeans IDE 2-7
• Folders View
• Components View
• Coding and Design View
• Output View
NetBeans IDE 3-7

Menu bar of NetBeans IDE


• Figure shows the various elements in theNetBeans IDE 7.1.2.
contains menus that have
several sub-menu items,
each providing a unique
functionality.
NetBeans IDE 4-7
Folder viewshows the structure of
files associated with Java
applications. It contains Projects
window, Files window, and Services
window.
NetBeans IDE 5-7

Component window is used for


viewing components in the
NetBeans IDE. It contains Navigator
window that displays details of the
source files of the currently opened
project.
NetBeans IDE 6-7

Code and Design view contains two elements:


Source Editor and Design Form. Source editor help
to create and edit the code. Design window helps in
design the form.
NetBeans IDE 7-7

Output window shows


compilation errors, debugging
messages, and the result of the
program.
Download and Install NetBeans IDE 1-5
• The latest version of NetBeans IDE for different platforms, such as Windows,
Linux, Solaris, and Mac OS X is available for download at
http://netbeans.org/downloads/index.html.
• On the NetBeans IDE download Web page, you will find different installers.
• Each installer of NetBeans IDE contains the basic IDE and its related tools.
• The different installers are as follows:
• Java SE - Supports all standard features that are necessary for Java SE development.
• Java EE - Provides tools for developing Java SE and Java EE applications. This download
option also includes GlassFish Server Open Source Edition and Apache Tomcat software.
• C/C++ - Supports development in the C, C++, Fortran, and Assembly languages.
• PHP - Provides tools for PHP 5.x development, Zend, and Symfony Framework support.
Download and Install NetBeans IDE 2-5
• All - This is a full download option, which contains all the runtimes and technologies available
for the NetBeans IDE.
• To download the NetBeans IDE 7.1.2, perform the following steps:
• Type http://netbeans.org/downloads/7.1.2/index.html in the Address bar
of the Web browser .
Download and Install NetBeans IDE 3-5
• Following figure shows the download Web page for theNetBeans 7.1.2 IDE:

• Select IDE language as English from the drop-down list. Also, select the Platform as
Windows from the drop-down list.
Download and Install NetBeans IDE 4-5
• Click Download under the installer All. The Save As dialog box is opened with netbeans7.1.2-
ml-windows.exe installer file. This installer will support development of all technologies in
the NetBeans IDE.

• Click Save to save the installer file on the local system. • Double-click netbeans-7.1.2-ml-
the installer.
windows.exe to run • To install the 1NetBeans IDE, perform the
following steps:
• Click Next at the Welcome page of the installation wizard. 2
• Click Next in the License Agreement page after reviewing the 3 license agreement, and
select the acceptance check box.
Download and Install NetBeans IDE 5
• At the JUnit License Agreement page, decide if you want to install JUnit-and click 5 4 the

appropriate option, click Next.

• Select either the default installation directory or specific directory where the NetBeans IDE needs to be
installed. Set the path of the default JDK installation and
5 click Next.
• The GlassFish Server Source Edition 3.1.2 installation page is displayed. You can
6 either select the default location or specify
another location to install the GlassFish Server.
• To install the Apache Tomcat Server, on the installation page, either select the 7 default location
or specify another location and then, click Next.

• The Summary page is opened. The list of components that are to be installed is
8
displayed,

• Click Install to install the NetBeans IDE on the system.


9

• After the installation is completed, click Finish to complete and close the setup
10 page.

Writing a Java Program Using NetBeans IDE


• The basic requirements to write a Java program using the NetBeans IDE is as
follows:
• The JDK 7 installed and configured on the system
• The NetBeans IDE

• To develop a Java program in NetBeans IDE, perform the following steps:

Add code to Build and


Create a
the generated execute Java project in IDE
source files program

Create a Project in IDE 1-2


• To create a project in IDE, perform the following steps:
• To launch NetBeans IDE, click StartAll ProgramsNetBeans and select NetBeans IDE
7.1.2.
• To create a new project, click FileNewProject. This opens the New Project wizard.
• Under Categories, expand Java and then, select Java Application under Projects.
• Click Next. This displays the Name and Location page in the wizard.
• Type HelloMessageApp in the Project Name box.
• Click Browse and select the appropriate location on the system.
• Click Finish.
Create a Project in IDE 2-2
• Following figure shows theHelloMessageAppproject in the NetBeans IDE:
Add Code to the Generated Source Files
• The necessary skeleton of the program has been created by the IDE.
• Following figure shows theNetBeansIDE with the modified code:
Build and Execute Java Program in
NetBeans IDE 1-2

• To compile the source file, HelloMessageApp.java, click RunBuild Main


Project in the NetBeans IDE menu bar.
• Following figure shows Files window that shows the generated bytecode file,
HelloMessageApp.class after the project is build successfully:
Build and Execute Java Program in
NetBeans IDE 2-2

• To execute the program, click RunRun Main Project.


• Following figure shows the

HelloMessageApp program.

Output
window that displays the output of the
Comments in Java
• Are placed in a Java program source file.
• Are used to document the Java program and are not compiled by the compiler.
• Are added as remarks to make the program more readable for the user.
• Are of three types:
• Single-line comments
• Multi-line comments
• Javadoc comments

Single-line Comments 1-2


• A single-line comment is used to document the functionality of a single line of code.
• There are two ways of using singleBeginning-of-line comment -line comments that
are as follows:
• This type of comment can be placed before the code (on a different line).
End-of-line comment
• This type of comment is placed at the end of the code (on the same line).

Syntax
• The syntax for applying the comments is as follows:
// Comment text

Single-line Comments 2-2


• Following
line code snippet shows the different ways of using single... -
// Declare a variable
int a = 32;
int b // Declare a
variable ...
comments in a Java program:

• Conventions for using single-line comments are as follows:


• Insert a space after the forward slashes.
• Capitalize the first letter of the first word.
Multi-line Comments
• Is a comment that spans multiple lines.
• Starts with a forward slash and an asterisk (/*).
• Ends with an asterisk and a forward slash (*/).
• Anything that appears between these delimiters is considered to be a comment.
• Following code snippet shows a Java program that uses multi-line comments:
...
/*
* This code performs mathematical *
operation of adding two numbers.
*/ int a =
20; int b =
30; int c;
c = a + b;
...

Javadoc Comments 1-2


• Is used to document public or protected classes, attributes, and methods.
• Starts with /** and ends with */.
• Everything between the delimiters is a comment.
• The javadoc command can be used for generating Javadoc comments.
• Following code snippet demonstrates the use of Javadoc comments in the Java
program:
/**
* The program prints the welcome message
* using the println() method.
*/ package
hellomessageapp;
/**
*
* @author vincent
*/ public class
HelloMessageApp {

/**
* @param args the command line arguments
*/ public static void main(String[]
args) {

// The println() method displays a message on the screen


System.out.println(“Welcome to the world of Java”);

}
}

Javadoc Comments 2-2


Summary
• The Java programming language is designed around object-oriented features and
begins with a class design.
• A Java class structure contains the following components namely, package, import,
class name, variables, and methods.
• Java programs can be written in a text editor, such as Notepad or in an IDE, such as
NetBeans.
• The entry point for a Java console application is the main() method.
• The javac.exe compiles the source code into a .class file. Similarly, the java.exe
command is used to interpret and run the Java bytecodes.
• NetBeans is a free and robust IDE that helps developers to create cross-platform
desktop, Web, and mobile applications using Java.
• Comments are used to document the Java program and are not compiled by the
compiler. There are three styles of comments supported by Java namely, single-line,
multi-line, and Javadoc.
Objectives • Explain variables and their purpose
• State the syntax of variable declaration
• Explain the rules and conventions for naming variables
• Explain data types
• Describe primitive and reference data types
• Describe escape sequence
• Describe format specifiers
• Identify and explain different type of operators
• Explain the concept of casting
• Explain implicit and explicit conversion
Introduction• The core of any programming language is the way it stores and
manipulates the data.
• The Java programming language can work with different types of data, such as
number, character, boolean, and so on.
• To work with these types of data, Java programming language supports the
concept of variables.
• A variable is like a container in the memory that holds the data used by the
Java program.
• A variable is associated with a data type that defines the type of data that will
be stored in the variable.
• Java is a strongly-typed language which means that any variable or an object
created from a class must belong to its type and should store the same type of
data.
• The compiler checks all expressions variables and parameters to ensure that
they are compatible with their data types.
Variables -21is a location in the computer’s memory which stores the data that is
A variable
used in a Java program.
• Following figure depicts a variable that acts as a container and holds the data in it:

 Variables
 are used in a Java program to store data that changes during the execution of the
program.
 are the basic units of storage in a Java program.
 can be declared to store values, such as names, addresses, and salary details.
 must be declared before they can be used in the program.
 A variable declaration begins with data type and is followed by variable name and a
semicolon.

Variables 2• The data type can be a primitive data type or a class.


-2
• The syntax to declare a variable in a Java program is as follows:

Syntax
datatype variableName;
where, datatype: Is a valid data type in
Java.
variableName: Is a valid variable name.
 Following code snippet demonstrates how to declare variables in a Java program:
...
int rollNumber;
char gender;
...
 In the code, the statements declare an integer variable named rollNumber, and a
character variable called gender.
 These variables will hold the type of data specified for each of them.

Rules for Naming Variables 1-2


Variable names may consist of Unicode letters and digits, underscore (_), and dollar
sign ($).
A variable’s name must begin with a letter, the dollar sign ($), or the underscore
character (_).
• The convention, however, is to always begin your variable names with a letter, not
‘$’ or ‘_’.

Variable names must not be a keyword or reserved word in Java.


Variable names in Java are case-sensitive.
• For example, the variable names number and Number refer to two different
variables.
If a variable name comprises a single word, the name should be in lowercase.

• For example, velocity or ratio.


If the variable name consists of more than one word, the first letter of each subsequent word should be capitalized.

• For example, employeeNumber and accountBalance.


Rules for Naming Variables 2• Following table shows some

-2
examples of valid and invalid Java variable names:

Variable Name Valid/Invalid


rollNumber Valid
a2x5_w7t3 Valid
$yearly_salary Valid
_2010_tax Valid
$$_ Valid
amount#Balance Invalid and contains the illegal character #
double Invalid and is a keyword
4short Invalid and the first character is a digit
Assigning Value to a Variable 1-3
• Values can be assigned to variables by using the assignment operator (=).
• There are two ways to assign value to variables. These are as follows:
At the time of declaring a variable

 Following code snippet demonstrates the initialization of variables at the time of


declaration:
...
int rollNumber = 101; char gender = ‘M’;
Assigning Value to a Variable 1-
...
 In the code, variable rollNumber is an integer variable, so it has been initialized with a
numeric value 101.

Literals are constant values assigned to variables directly in the code without
any computation.
 Similarly, variable gender is a character variable and is initialized with a character ‘M’.
Assigning Value to a Variable 2-3
 The values assigned to the variables are called as literals.
After the variable declaration

 Following code snippet demonstrates the initialization of variables after they are
declared:
int rollNumber; // Variable is declared
// Declares three integer variables x, y, and z
int x, y, z;

// Declares three integer variables, initializes a and c


int a = 5, b, c = 10;

// Declares a byte variable num and initializes its value to 20


byte num = 20;
...
rollNumber = 101; //variable is initialized
...
Assigning Value to a Variable 3-3
 Here, the variable rollNumber is declared first and then, it has been initialized with the
numeric literal 101.
 Following code snippet shows the different ways for declaring and initializing variables
in Java:
// Declares the character variable c with value ‘c’
char c = ‘c’;

// Stores value 10 in num1 and num2


int num1 = num2 = 10; //
 In the code, the declarations, int x, y, z; and int a=5, b, c=10; are examples of comma
separated list of variables.
 The declaration int num1 = num2 = 10; assigns same value to more than one variable
at the time of declaration.
Different Types of Variables 1-3
 Java programming language allows you to define different kind of variables that
are categorized as follows:

Instance variables
 The state of an object is represented as fields or attributes or instance variables in
the class definition.
 Each object created from a class will have its own copy of instance variables.
 Following figure shows the instance variables declared in a class template:
Different Types of Variables 2Static variables -3
 These are also known as class variables.
 Only one copy of static variable is maintained in the memory that is shared by all the
objects belonging to that class.
 These fields are declared using the static keyword.
 Following figure shows the static variables in a Java program:
Different Types of Variables 3Local variables -3
 The variables declared within the blocks or methods of a class are called local variables.
 A method represents the behavior of an object.
 The local variables are visible within those methods and are not accessible outside them.
 A method stores it temporary state in local variables.
 There is no special keyword available for declaring a local variable, hence, the position of
declaration of the variable makes it local.
Scope and Lifetime of Variables 1-3
 In Java, variables can be declared within a class, method, or within any block.  A scope
determines the visibility of variables to other part of the program.
Languages
such as Java
C/C++

Globa Metho
Local Class
l d

Class scope

 The variables declared within the class can be instance variables or static variables.

 The instance variables are owned by the objects of the class and their existence or
scope depends upon the object creation.

 Static variables are shared between the objects and exists for the lifetime of a class.
Scope and Lifetime of Variables 2-3
Method scope

 The variables defined within the methods of a class are local variables.

 The lifetime of these variables depends on the execution of methods.

 This means memory is allocated for the variables when the method is invoked and
destroyed when the method returns.

 After the variables are destroyed, they are no longer in existence.

 Methods parameters values passed to them during method invocation.

 The parameter variables are also treated as local variables which means their
existence is till the method execution is completed.
Scope and Lifetime of Variables 3-3
 Following figure shows the scope and lifetime of variables x and y defined within the
Scope and Lifetime of Variables 4-3

Java program:
Data Types When you define a variable in Java, you must inform the compiler what kind of a
variable it is.
That is, whether it will be expected to store an integer, a character, or some other
kind of data.
This information tells the compiler how much space to allocate in the memory
depending on the data type of a variable.
Thus, the data types determine the type of data that can be stored in variables and
the operation that can be performed on them.

In Java, data types fall under two categories that are as follows:

Primitive data
types Reference data types
Primitive Data Types The Java programming language provides eight
primitive data types to store data
in Java programs.

A primitive data type, also called built-in data type, stores a single value at a time,
such as a number or a character.

The size of each data type will be same on all machines while executing a Java
program.

The primitive data types are predefined in the Java language and are identified as
reserved words.

• Following figure shows the primitive data types that are broadly grouped into four groups:
Integer Types• The integer data types supported by Java are byte, short, int,
and long.
• These data type can store signed integer values.
• Signed integers are those integers, which are capable of representing positive as well as negative
numbers, such as -40.
• Java does not provide support for unsigned integers.
• Following table lists the details about the integer data types:
byte short int long
A signed 8-bit type. A signed 16-bit type. Signed 32-bit type. Signed 64-bit type.
Range:
9,223,372,036,854,775,8
Range: -32,768 to Range: -2,147,483,648
Range: -128 to 127 08 to
32,767 to 2,147,483,647
9,223,372,036,854,775,8
07
Used to store Used to store the total Used to store very large
Useful when
smaller numbers, for salary being paid to all values such as
working with
example, employee the employees of the population of a
raw binary data.
number. company. country.
Keyword: byte Keyword: short Keyword: int Keyword: long

Floating• The floating-point Types-point data types supported by Java


are float and double.
• These are also called real numbers, as they represent numbers with fractional precision.
• For example, calculation of a square root or PI value is represented with a fractional part.
• The brief description of the floating-point data types is given in the following table:
float double
A single precision value with 32-bit
A double precision with 64-bit storage.
storage.

Useful when a number needs a fractional Useful when accuracy is required to be


component, but with less precision. maintained while performing calculations.
Keyword: float Keyword: double

For example, float squRoot,


For example, double bigDecimal;
cubeRoot;
Character and Boolean Types 1-4
• char data type belongs to this group and represents symbols in a character set like
letters and numbers.
• char data type stores 16-bit Unicode character and its value ranges from 0 (‘\
u0000’) to 65,535 (‘\uffff’).
• Unicode is a 16-bit character set, which contains all the characters commonly used in
information processing.
• It is an attempt to consolidate the alphabets of the world’s various languages into a
single and international character set.

 boolean data type represents true or false values.


 This data type is used to track true/false conditions.
 Its size is not defined precisely.
 Apart from primitive data types, Java programming language also supports strings.
 A string is a sequence of characters.
 Java does not provide any primitive data type for storing strings, instead provides a class
String to create string variables.
Character and Boolean Types 2-4
 The String class is defined within the java.lang package in Java SE API.
• Following code snippet demonstrates the use of String class as primitive data type:

...
String str = “A String Data”;
...
 The statement, String str creates an String object and is not of a primitive data type.

 When you enclose a string value within double quotes, the Java runtime environment
automatically creates an object of String type.

 Also, once the String variable is created with a value ‘A String Data’, it will remain
constant and you cannot change the value of the variable within the program.

 However, initializing string variable with new value creates a new String object.

 This behavior of strings makes them as immutable objects.


Character and Boolean Types 3-4
• Following code snippet demonstrates the use of different data types in Java:
Character and Boolean Types 4-4
public class EmployeeData {
/**
* @param args the command line arguments
*/ public static void main(String[]
args) {

// Declares a variable of type integer


int empNumber;
//Declares a variable of type decimal
float salary;
// Declare and initialize a decimal variable
double shareBalance = 456790.897;
// Declare a variable of type character
char gender = ‘M’;
// Declare and initialize a variable of type boolean
boolean ownVehicle = false;
// Variables, empNumber and salary are initialized
empNumber = 101;
salary = 6789.50f;
Character and Boolean Types 5-4
// Prints the value of the variables on the console
System.out.println(“Employee Number: “ + empNumber);
System.out.println(“Salary: “ + salary);
System.out.println(“Gender: “ + gender);
System.out.println(“Share Balance: “ + shareBalance);
System.out.println(“Owns vehicle: “ + ownVehicle);
}
}
• Here, a float value needs to have the letter f appended at its end.
• Otherwise, by default, all the decimal values are treated as double in Java.
• The output of the code is shown in the following figure:
Character and Boolean Types 6-4
Reference Data Types • In Java, objects and arrays are referred to
as reference variables.
• Reference data type is an address of an object or an array created in memory.
• Following figure shows the reference data types supported in Java:

 Following table lists and describes the three reference data types:
Data Type Description
It is a collection of several items of the same data type. For
Array
example, names of students in a class can be stored in an array.

Class It is encapsulation of instance variables and instance methods.


Literals 1
Interface It is a type of class in Java used to implement inheritance.

• A literal represents a fixed value assigned to a variable. -4


• It is represented directly in the code and does not require computation.
• Following figure shows some literals for primitive data types:

 A literal is used wherever a value of its type is allowed.


 However, there are several different types of literals as follows:

Integer Literals
 Integer literals are used to represent an int value, which in Java is a 32-bit integer
value.
 Integers literals can be expressed as:
Literals 2
Decimal values have a base of 10 and consist of numbers from 0 through 9. For
example, int decNum = 56;.

Hexadecimal values have a base of 16 and consist of numbers 0 through 9 and letters
A through F. For example, int hexNum = 0X1c;.

Binary values have a base of 2 and consist of numbers 0 and 1. Java SE 7 supports -
4 binary literals. For example, int binNum = 0b0010;.

An integer literal can also be assigned to other integer types, such as byte or long.

 When a literal value is assigned to a byte or short variable, no error is generated, if the
literal value is within the range of the target type.
Literals 3
 Integer numbers can be represented with an optional uppercase character (‘L’) or
lowercase character (‘l’) at the end.
 This will inform the computer to treat that number as a long (64-bit) integer.

Floating-point Literals

 Floating-point literals represent decimal values with a fractional component.


 Floating-point literals have several parts.
Whole number component, for example 0, 1, 2,....., 9.

Decimal point, for example 4.90, 3.141, and so on.

-4
Exponent is indicated by an E or e followed by a decimal number, which can be
e+208, 7.436E6, 23763E-05, and so on.
positive or negative. For example,

Type suffixD, d, F, or f.
Literals 4
 Floating-point literals in Java default to double precision.
 A float literal is represented by F or f appended to the value, and a double literal is
represented by D or d.
Boolean Literals

 Boolean literals are simple and have only two logical values - true and false.
 These values do not convert into any numerical representation.
 A true boolean literal in Java is not equal to one, nor does the false literal equals to
zero.
 They can only be assigned to boolean variables or used in expressions with boolean
operators.

Character Literals -4
 Character literals are enclosed in single quotes.
 All the visible ASCII characters can be directly enclosed within quotes, such as ‘g’, ‘$’,
and ‘z’.
Literals 5
 Single characters that cannot be enclosed within single quotes are used with escape
sequence.
Null Literals

 When an object is created, a certain amount of memory is allocated for that object.
 The starting address of the allocated memory is stored in an object variable, that is, a
reference variable.
 However, at times, it is not desirable for the reference variable to refer that object.
 In such a case, the reference variable is assigned the literal value null. For example,
Car toyota = null;.
String Literals

 String literals consist of sequence of characters enclosed in double quotes. For


example, “Welcome to Java”, “Hello\nWorld”.
Underscore Character in Numeric Literals
1 -2
Java SE 7 allows you to add underscore characters (_) between the digits of a
numeric literal.

The underscore character can be used only between the digits.

 In integral literals, underscore characters can be provided for telephone numbers,


identification numbers, or part numbers, and so on.
 Similarly, for floating-point literals, underscores are used between large decimal values.
 Restrictions for using underscores in numeric literals are as follows:
A number cannot begin or end with an underscore.

In the floating
-point literal, underscore cannot be placed adjacent to a
decimal point.

Underscore cannot be placed before a L or F.


suffix,

Underscore cannot be placed before or after the binary or hexadecimal


identifiers, such bor
as x.

Underscore Character in Numeric Literals 2•


-2
Following table shows the list of valid and invalid placement of underscore character:

Numeric Literal Valid/Invalid

1234_9876_5012_5454L Valid
Invalid, as underscore placed at the
_8976
beginning

3.14_15F Valid
0b11010000_11110000_00001111 Valid
Invalid, as underscore is adjacent to a
3_.14_15F
decimal point
Invalid, an underscore is placed after the
0x_78
hexadecimal
Escape Sequences 1-3
An escape sequence is a special sequence of characters that is used to represent characters,
which cannot be entered directly into a string.
• For example, to include tab spaces or a new line character in a line or to include
characters which otherwise have a different notation in a Java program (\ or “),
escape sequences are used.
An escape sequence begins with a backslash character (\), which indicates that the character
(s) that follows should be treated in a special way.

The output displayed by Java can be formatted with the help of escape sequence characters.

 Following table lists escape sequence characters in Java:


Escape Sequences 2-3

• Following code snippet demonstrates the use of escape sequence characters:


public class EscapeSequence {
/*
* @param args the command line arguments

Escape Sequences 3-3


*/ public static void main(String[]
args) {
 // Usesoftab
The output theand new
code line escape
is shown in thesequences
following figure:
System.out.println(“Java \t Programming \n Language”);
// Prints Tom “Dick” Harry string
System.out.println(“Tom \”Dick\” Harry”);
}
}

• To represent a Unicode character, \u escape sequence can be used in a Java program.


• A Unicode character can be represented using hexadecimal or octal sequences.
Escape Sequences 4-3
• Following code snippet demonstrates the Unicode characters in a Java program:
public class UnicodeSequence {
/**
* @param args the command line arguments
*/ public static void main(String[]
args) {
// Prints ‘Hello’ using hexadecimal escape sequence characters
System.out.println(“\u0048\u0065\u006C\u006C\u006F” + “!\n”);
// Prints ‘Blake’ using octal escape sequence character for ‘a’
System.out.println(“Bl\141ke\”2007\” “);
}
 }
The output of the code is shown in the following figure:
Constants and Enumerations 1-5
• Constants in Java are fixed values assigned to identifiers that are not modified
throughout the execution of the code.
• In Java, the declaration of constant variables is prefixed with the final keyword.
• The syntax to initialize a constant variable is as follows:

public class AreaOfCircle {


/**
* @param args the command line arguments
*/ public static void main(String[]
args) { // Declares constant variable
final double PI = 3.14159; double
radius = 5.87; double area;

Syntax
final data-type variable-name = value;
Constants and Enumerations 2-5
where, final: Is a keyword and denotes that the variable is declared as a
constant.
 Following code snippet demonstrates the code that declares the constant variables:
// Calculates the value for the area variable
area = PI * radius * radius;
System.out.println(“Area of the circle is: “ + area);
}
}
 In the code, a constant variable PI is assigned the value 3.14159, which is a fixed value.
The output of the code is shown in the following figure:
Constants and Enumerations 3-5
Java SE 5.0 introduced enumerations.

An enumeration is defined as a list that contains constants.

Unlike C++, where enumeration was a list of named integer constants, in Java,
enumeration is a class type.

This means it can contain instance variables, methods, and constructors.

The enumeration is created using enumkeyword.


the

• The syntax for declaring a method is as follows:

Syntax
enum enum-name {
constant1, constant2, . . . , constantN
}
Constants and Enumerations 4-5
• Though, enumeration is a class in Java, you do not use new operator to instantiate it.
• Instead, declare a variable of type enumeration to use it in the Java program.
• This is similar to using primitive data types.
• The enumeration is mostly used with decision-making constructs, such as switch-case
statement.
• Following code snippet demonstrates the declaration of enumeration in a Java
program:
Constants and Enumerations 5-5
public class EnumDirection {

/**
* Declares an enumeration
*/ enum
Direction {
East, West, North, South
}

/**
* @param args the command line arguments
*/ public static void main(String[]
args) {
// Declares a variable of type Direction
Direction direction;

Constants and Enumerations 6-5


// Instantiate the enum Direction
direction = Direction.East;

// Prints the value of enum
System.out.println(“Value: “ + direction);
}
}
The output of the code is shown in the following figure:
Formatted Output and Input• Whenever an output is to be
displayed on the screen, it needs to be formatted.
• Formatting can be done using three ways that are as follows:

print() and
println()

printf()

format()

 These methods behave in a similar manner.


 The format() method uses the java.util.Formatter class to do the formatting work.
‘print()’ and ‘• These methods convert all the data to strings and display it as a single

println()’ Methods 1-2


value.

• The methods uses the appropriate toString() method for conversion of the values.
• These
methods public class DisplaySum {
can also /**
* @param args the command line arguments
*/ public static void main(String[]
args) { “ + sum + “.”); int num1 = 5;
int num2 = 10;
int sum = num1 + num2;
System.out.print(“The sum of “);
System.out.print(num1);
System.out.print(“ and “);
System.out.print(num2);
System.out.print(“ is “);
System.out.print(sum);
be used to print mixture combination of strings and numeric values as strings on the standard
output.
• Following code snippet demonstrates the use of print() and println()
methods:

System.out.println(“.”);
int num3 = 2;
sum = num1 + num2 + num3;
System.out.println(“The sum of “ + num1 + “, “ + num2 + “ and “ +
num3 + “ is
}
}

‘print()’ and ‘println()’ Methods 2-2

• The sum variable is formatted twice.


• In the first case, the print() method is used for each instruction which prints the
result on the same line.
• In the second case, the println() method is used to convert each data type to
string and concatenate them to display as a single result.
• The output of the code is shown in the following figure:

‘ printf• The ()printf’ Method () method introduced in J2SE 5.0 can be


used to format the numerical 1-2 output to the console.

• Following table lists some of the format specifiers in Java:


 Following code snippet demonstrates the use of printf() methods to format the output:

public class FormatSpecifier {


/**
* @param args the command line arguments
*/ public static void main(String[]
args) { int i = 55 / 22; // Decimal
integer
System.out.printf(“55/22 = %d %n”, i);
// Pad with zeros
double q = 1.0 / 2.0;
System.out.printf(“1.0/2.0 = %09.3f %n”, q);
// Scientific notation
q = 5000.0 / 3.0;
System.out.printf(“5000/3.0 = %7.2e %n”, q);
// Negative infinity
q = -10.0 / 0.0;
System.out.printf(“-10.0/0.0 = %7.2e %n”, q);
// Multiple arguments, PI value, E–base of natural logarithm
System.out.printf(“pi = %5.3f, e = %5.4f %n”, Math.PI, Math.E);
}
The output of the code is shown in the following figure:}

‘printf()’ Method 2-2



‘format()’ Method 1-3
• This method formats multiple arguments based on a format string.
• The format string consists of the normal string literal information associated with
format specifiers and an argument list.
• The syntax of a format specifier is as follows:

Syntax
%[arg_index$] [flags] [width] [.precision] conversion character
where, arg_index: Is an integer followed by a $ symbol. The integer indicates
that the argument should be printed in the mentioned position.
flags: Is a set of characters that format the output result. There are different flags
available in Java.
‘format()’ Method 2-3
 Following table lists some of the flags available in Java:

width: Indicates the minimum number of characters to be printed and cannot be


negative.
precision: Indicates the number of digits to be printed after a decimal point. Used
with floating-point numbers.
public class VariableScope {
/**
* @param args the command line arguments
*/ public static void main(String[]
args) {
conversion character: Specifies the type of argument to be formatted. For
example, b for boolean, c for char, d for integer, f for floating-point, and s for
string.
‘format()’ Method 3-3
 The values within ‘[]’ are optional.
 The only required elements of format specifier are the % and a conversion character.
 Following code snippet demonstrates the format() method:
int num = 2;
double result = num * num;
System.out.format(“The square root of %d is %f.%n”, num, result);
}
}
 The output of the code is shown in the following figure:
Formatted Input 1
 The Scanner class allows the user to read or accept values of various data types from

-3 the keyboard.
 It breaks the input into tokens and translates individual tokens depending on their

data type.
 To use the Scanner class, pass the InputStream object to the constructor as follows:
Formatted Input 2
Scanner input = new Scanner(System.in);
 Here, input is an object of Scanner class and System.in is an input stream object.
 Following table lists the different methods of the Scanner class that can be used to
accept numerical values from the user:

 Following code snippet demonstrates the -3 Scanner class methods and how
they can be used to accept values from the user:
public class FormattedInput {

/**
* @param args the command line arguments
*/ public static void main(String[]
args) {

// Creates an object and passes the inputstream object


Scanner s = new Scanner(System.in);
System.out.println(“Enter a
Formatted Input 3
number:”); // Accepts integer value
from the user
int intValue = s.nextInt();
System.out.println(“Enter a decimal number:”);
// Accepts integer value from the user
float floatValue = s.nextFloat();
System.out.println(“Enter a String value”);
// Accepts String value from the user
String strValue = s.next();
Formatted Input 4
- System.out.println(“Values entered are: “);
System.out.println(intValue + “ “ + floatValue + “ “ + strValue);
}
}

3
 The output of the code is shown in the following figure:
Formatted Input 5
Operators
Operators are set of symbols used to indicate the kind of operation to be
performed on data.
 Consider the expression:
Z = X + Y;
 Here, • is called the Operator and the operation performed is
+
addition.

X andY, on which addition is performed,


• the two variables
X andY
are called as Operands.

• a combination of both the operator and the operands, is


Z = X + Y
known as an Expression.

 Java provides several categories of operators and they are as follows:


Assignment Operators-21
This operator is used to assign the value on its right to the operand on its left.

Assigning values to more than one variable can be done at a time.

In other words, it allows you to create a chain of assignments.

 Consider the following statements:


The basic assignment operator is a single equal to sign, ‘=’.
int balance = 3456;
char gender = ‘M’;
 The value 3456 and ‘M’ are assigned to the variables, balance and gender.
Assignment Operators 2  In addition to the basic assignment

-2
operator, there are combined operators that allow
you to use a value in an expression, and then, set its value to the result of
that expression. X = 3;
X += 5;
 The second statement stores the value 8, the meaning of the statement is that X = X +
5.
 Following code snippet demonstrates the use of assignment operators:
...
x = 10; // Assigns the value 10 to variable
x x += 5; // Increments the value of x by 5
x -= 5; // Decrements the value of x by 5 x
*= 5; // Multiplies the value of x by 5 x /=
2; // Divides the value of x by 2
x %= 2; // Divides the value of x by 2 and the remainder is returned
Arithmetic Operators Arithmetic operators manipulate numeric data

and perform common arithmetic


operations on the data.
 Operands of the arithmetic operators must be of numeric type.
 Boolean operands cannot be used, but character operands are allowed.
 The operators mentioned here are binary in nature that is, these operate on two
operands, such as X+Y. Here, + is a binary operator operating on X and Y. 
Following table lists the arithmetic operators:

 Following code snippet demonstrates the use of arithmetic operators:


...
x = 2 + 3; // Returns 5 y = 8 – 5; // Returns 3 x = 5 *
2; // Returns 10 x = 5/2; // Returns 2 y = 10 % 3; //
Returns 1
...

Unary Operator  Unary operators require only one operand.


 They increment/decrement the value of a variable by 1, negate an expression, or invert
the value of a boolean variable. Following table lists the unary operators:

 The prefix version (++variable) will increment the value before evaluating.
 The postfix version (variable++) will first evaluate and then, increment the original
value.
 Following code snippet demonstrates the use of unary operators:
...
int i = 5; int j = i++; // i=6, j=5 int k = ++i; //i=6,k=6 i = -
i ; //now i is -6 boolean result = false; //result is false
result = !result; //now result is true

Conditional Operators 1 
The conditional operators test the

-2
relationship between two operands.

 An expression involving conditional operators always evaluates to a boolean value


(that is, either true or false).

public class TestConditionalOperators {


/**
* @param args the command line arguments
*/ public static void main(String[]
args) { int value1 = 10; int value2 =
20;

 Following table lists the various conditional operators:


 Following code snippet demonstrates the use of conditional operators:
// Use of conditional operators
System.out.print(“value1 == value2: “);
System.out.println(value1 == value2);
System.out.print(“value1 != value2: “);
System.out.println(value1 != value2);
System.out.print(“value1 > value 2: “);
System.out.println(value1 > value2);
System.out.print(“value1 < value2: “);
System.out.println(value1 < value2);
System.out.print(“value1 <= value2: “);
System.out.println(value1 <= value2);
}
The output of the code is shown in the following figure:}

Conditional Operators 2-2


Logical Operators 1 Logical operators (&& and ||) work on two -2


boolean expressions.
 These operators exhibit short-circuit behavior, which means that the second operand is
evaluated only if required.
public class TestLogicalOperators {
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{ int first = 10; int second = 20;

// Use of logical operator


System.out.println((first == 30) && (second == 20));

 Following table lists the two logical operators:

 Following code snippet demonstrates the use of logical operators:


System.out.println((first == 30) || (second == 20));
}
}

Logical Operators 2-2


 The output of the code is shown in the following figure:
Bitwise Operators 1 
Bitwise operators work on binary representations of

-2
data.

public class TestBitwiseOperators {


/**
* @param args the command line arguments
*/ public static void main(String[]
args) { int x = 23; int y = 12;
//23 = 10111 , 12 = 01100

 These operators are used to change individual bits in an operand.


Following table lists the various bitwise operators:
 Following code snippet demonstrates the use of bitwise operators:
System.out.print(“x & y: “);
System.out.println(x & y); // Returns 4 , i.e, 4 = 00100
System.out.print(“x | y: “);
System.out.println(x | y); // Returns 31, i.e 31 = 11111
System.out.print(“x ^ y: “);
System.out.println(x ^ y); // Returns 27, i.e 31 =
11011 int a = 43; int b = 1;
System.out.print(“a >> b: “);
System.out.println(a >> b); // returns 21 , i.e, 21 = 0010101
System.out.print(“a << b: “);
System.out.println(a << b); //returns 86 , i.e, 86 = 1010110
}
The output of the code is shown in the following figure:}

Bitwise Operators 2-2


Ternary Operator 1• The ternary operator (?:) is a shorthand operator


for an if-2 -else statement.
• It makes your code compact and more readable.
• The syntax to use the ternary operator is as follows:
Syntax
expression1 ? expression2 : expression3
where, expression1: Represents an expression that evaluates to a boolean value of
true or false. expression2: Is executed if expression1 evaluates to true.
expression3: Is executed if expression1 evaluates to false.
 Following code snippet demonstrates the use of ternary operator:
public class VariableScope {
/**
* @param args the command line arguments
*/ public static void main(String[]
args) { int value1 = 10;
int value2 = 20;
int result;
boolean someCondition = true;
result = someCondition ? value1 : value2;
System.out.println(result);
}
}

Ternary Operator 2-2

 As someCondition variable evaluates to true, the value of value1 variable is assigned to the
result variable.
 Thus, the program prints 10 on the console.
Operator Precedence 1• Expressions that are written generally
consist of several operators. -2
• The rules of precedence decide the order in which each operator is evaluated in any
given expression.
• Following table lists the order of precedence of operators from highest to lowest in
which operators are evaluated in Java:

 Parentheses are used to change the order in which an expression is evaluated.


 Any part of an expression enclosed in parentheses is evaluated first.
 For example, consider the following expression:
2*3+4/2 > 3 && 3<5 || 10<9

Operator Precedence 2• The evaluation of the expression based on


its operators precedence is as follows:-2
• (2*3+4/2) > 3 && 3<5 || 10<9
1 • First the arithmetic operators are evaluated.

•((2*3)+(4/2)) > 3 && 3<5 || 10<9


2 • Division and Multiplication are evaluated before addition and subtraction.

• (6+2)>3 && 3<5 ||


10<9
3
•(8>3)&& [3<5] || [10<9]
4 • Next to be evaluated are the relational operators all of which have the same precedence.

• These are therefore evaluated from left to right.


5 •(True && True) False ||

• The last to be evaluated are the logical &&takes


operators.
precedence ||
over
.
6 •True || False

•True
7
Operator • When two operators with the same precedence appear in an expression,
the expression Associativity 1-2
is evaluated, according to its associativity.
• For example, in Java the - operator has left-associativity and x - y - z is
interpreted as (x - y) - z, and = has right-associativity and x = y = z is
interpreted as x = (y = z).
• Following table shows the Java operators and their associativity:
Operator  Consider the following expression: Associativity 2-2
2+10+4-5*(7-1)
• The ‘*’ has higher precedence than any other operator in the equation.
• However, as7-1 is enclosed in parenthesis, it is evaluated first.
1 • 2+10+4-5*6

• Next, *
‘ ’ is the operator with the highest precedence.
• Since there are no more parentheses, it is evaluated according to the rules.
2 • 2+10+4-30

• As ‘+’ and -
‘ ‘ have the same precedence, theassociativity
left works out.
• 12+4-30
3

• Finally, the expression is evaluated from left to right.


• 6 – 30
4 • The result is-14.

Type Casting Type conversion or typecasting refers to changing an entity of one data type
into another.
• For instance, values from a more limited set, such as integers, can be stored in a more
compact format.
• There are two types of conversion:

implicit The term for implicit type conversion is coercion.

explicit The most common form of explicit type conversion is


known as casting.
Explicit type conversion can also be achieved with

separately defined conversion routines such as an overloaded object constructor.

Implicit Type Casting 1• When a data of a particular type is assigned


to a variable of another type, then -3
automatic type conversion takes place.
• It is also referred to as implicit type casting, provided it meets the conditions specified:
 The two types should be compatible
 The destination type should be larger than the source
• Following figure shows the implicit type casting:

Implicit Type Casting 2• The primitive numeric data types that can be
implicitly cast are as follows:-3
byte (8 bits) to short, int, long, float, double

short(16 bits) to int, long, float, double

int (32 bits) to long, float, double

long(64 bits) to float, double

 This is also known as the type promotion rule.


 The type promotion rules are listed as follows:

If one operand is long, the whole expression is promoted to long.

If one operand is float then, the whole expression is promoted to float.

If one operand is double then, the whole expression is promoted to double.


Al
l byte and short values are promoted to int type.
Implicit Type Casting 3• Following code snippet demonstrates
implicit type conversion:-3
...
double dbl = 10; long lng = 100; int in = 10; dbl = in; //
assigns the integer value to double variable lng = in; //
assigns the integer value to long variable
Explicit Casting 1• A data type with lower precision, such as -2 short,
can be converted to a type of higher
precision, such as int, without using explicit casting.
• However, to convert a higher precision data type to a lower precision data type, such as
float to int data type, an explicit cast is required.
• The syntax for explicit casting is as follows:

Syntax
(target data type) value;
 Following figure shows the explicit type casting of data types:
Explicit Casting 2• Following code snippet adds a -2float value to an
int and stores the result as an
integer:
...
float a = 21.3476f; int b = (int) a + 5;
...
 The float value in a is converted into an integer value 21.
 It is then, added to 5, and the resulting value, 26, is stored in b.
 This type of conversion is known as truncation.
 The fractional component is lost when a floating-point is assigned to an integer type,
resulting in the loss of precision.

Summary Variables store values required in the program and should be declared

before they are used. In Java, variables can be declared within a class, method, or
within any block.
 Data types determine the type of values that can be stored in a variable and the
operations that can be performed on them. Data types in Java are divided mainly into
primitive types and reference types.
 A literal signifies a value assigned to a variable in the Java program. Java SE 7 supports
the use of the underscore characters (_) between the digits of a numeric literal.
 The output of the Java program can be formatted using three ways: print() and
println(), printf(), format(). Similarly, the Scanner class allows the user to read or accept
values of various data types from the keyboard.
 Operators are symbols that help to manipulate or perform some sort of function on
data.
 Parentheses are used to change the order in which an expression is evaluated.
 The type casting feature helps in converting a certain data type to another data type.
The type casting can be automatic or manual and should follow the rules for
promotion.

You might also like