0% found this document useful (0 votes)
29 views64 pages

CJ Unit 1

This module introduces object-oriented concepts and the Java programming language. It explains classes and objects, and how they are used to represent real-world entities in software. It also demonstrates how to define a class and compare classes and objects.

Uploaded by

Esha Worlikar
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)
29 views64 pages

CJ Unit 1

This module introduces object-oriented concepts and the Java programming language. It explains classes and objects, and how they are used to represent real-world entities in software. It also demonstrates how to define a class and compare classes and objects.

Uploaded by

Esha Worlikar
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/ 64

Core

JAVA
MODULE-1: Introduction and Data Types

Vidyalankar School of Compiled by: Beena Kapadia


Information Technology
Wadala (E), Mumbai [email protected]
www.vsit.edu.in
Certificate
This is to certify that the e-book titled “CORE JAVA” comprises all
elementary learning tools for a better understating of the relevant concepts. This e-
book is comprehensively compiled as per the predefined eight parameters and
guidelines.

Signature Date: 19-11-2019


Ms. Beena Kapadia
Assistant Professor
Department of IT

DISCLAIMER: The information contained in this e-book is compiled and distributed for
educational purposes only. This e-book has been designed to help learners understand
relevant concepts with a more dynamic interface. The compiler of this e-book and
Vidyalankar Institute of Technology give full and due credit to the authors of the contents,
developers and all websites from wherever information has been sourced. We acknowledge
our gratitude towards the websites YouTube, Wikipedia, and Google search engine. No
commercial benefits are being drawn from this project.
Unit I Introduction and Data Types

Contents:
Introduction: History, architecture and its components, Java Class File, Java Runtime Environment, The
Java Virtual Machine, JVM Components, The Java API, java platform, java development kit, Lambda
Expressions, Methods References, Type Annotations, Method Parameter Reflection, setting the path
environment variable, Java Compiler And Interpreter, java programs, java applications, main(), public,
static, void, string[] args, statements, white space, case sensitivity, identifiers, keywords, comments,
braces and code blocks, variables, variable name.

Data types: primitive data types, Object Reference Types, Strings, Auto boxing, operators and properties
of operators, Arithmetic operators, assignment operators, increment and decrement operator, relational
operator, logical operator, bitwise operator, conditional operator.

Recommended Books :
Core Java 8 for Beginners, Vaishali Shah, Sharnam Shah, 1st Edition
Java: The Complete Reference , Herbert Schildt ,9th Edition
Murach’s beginning Java with Net Beans, Joel Murach , Michael Urban, 1st Edition
Core Java, Volume I: Fundamentals, Hortsman, 9th Edition
Core Java, Volume II: Advanced Features, Gary Cornell and Hortsman, 8th Edition
Core Java: An Integrated Approach , R. Nageswara Rao , 1st Edition

Prerequisites/linkages
Unit II Pre- Sem. I Sem. II Sem. III Sem. V Sem. VI
requisites
Control Flow -- IP WP, Python Enterprise Project
Statements,Iterati OOPS Java,
ons and Classes AWP
Unit I Introduction to Java and Datatypes

Contents:
1. Inheritance: Derived Class Objects, Inheritance and Access Control,
2. Default Base Class Constructors
3. this and super keywords
4. Abstract Classes, Abstract Methods
5. Interfaces, What Is An Interface
6. How Is An Interface Different From An Abstract Class
7. Multiple Inheritance, Default Implementation, Adding New Functionality, Method Implementation
8. Classes V/s Interfaces
9. Defining An Interface, Implementing Interfaces.
10. Packages: Creating Packages, Default Package, Importing Packages, Using A Package

• Recommended Books:
1. Core Java 8 for Beginners - Vaishali Shah, Sharnam Shah
2. Java: The Complete Reference - Herbert Schildt McGraw Hill
3. Murach’s beginning Java with Net Beans - Joel Murach , Michael Urban
4. Core Java, Volume I: Fundamentals - Hortsman Pearson
5. Core Java, Volume II: Advanced Features - Gary Cornell and Hortsman
Pearson
6. Core Java: An Integrated Approach - R. Nageswara Rao

• Prerequisites and Linking


Pre- SEM-VI
requisites
C++ Advance
Java
Module 1
Introduction to Java

Concepts
Module Overview

Welcome to the module, Introduction to Java. This module introduces object-oriented concepts
and the Java programming language. The module begins with a brief explanation of object-
oriented concepts. It introduces Java as a platform and as a programming language. It further
explains the Java Development Kit (JDK), Java Virtual Machine (JVM), and demonstrates how to
write and execute a Java application program. Finally, it provides an overview on writing
comments in Java programs.

In this module, you will learn about:

Classes and Objects



Getting Started with Java

Introduction to JDK

Java Virtual Machine

Writing a Java program

NetBeans IDE Overview

Using Comments in Java

1.1 Classes and Objects

In this first lesson, Classes and Objects, you will learn to:

Describe real-world entities as objects.



Describe a software object.

Define a class and describe its structure.

Compare classes and objects.

Core Java
Module 1
Introduction to Java

1.1.1 Introduction to Classes and Objects


Concepts

Objects and classes are the bricks used to build Java applications. A class is a template for multiple
objects with similar features. Classes represent all the features of a particular set of objects.

1.1.2 Object

An object is the software representation of a real-world entity. For example, objects in a railway
reservation system may include a train, a journey destination, an icon on a screen, or a full screen with
which a railway booking agent interacts. Any tangible entity in the real-world can be described as an
object. Examples of real-world entities exist around everyone, such as a car, bike, flower, or person.

Every entity has some characteristics and is capable of performing certain actions. Characteristics are
attributes or features describing the entity, while actions are activities or operations involving the object.

For instance, consider a real-world entity, such as a Toyota or a Ford car. Some of the characteristics
associated with a Toyota or Ford car are as follows:

Color

Make

Model

Some of the actions associated with a Toyota or Ford car are as follows:

Drive

Accelerate

Decelerate

Apply brake

1.1.3 Software Object

The concept of objects in the real-world can be extended to the programming world, where software
‘objects’ can be defined.

Like its real-world counterpart, a software object has state and behavior. The ‘state’ of the software object
refers to its characteristics or attributes, whereas the ‘behavior’ of the software object comprises its
actions.

Core Java
Module 1
Introduction to Java

For example, a real-world object, such as a Car will have the state as color, make, or model and the
behavior as driving, changing gear, increasing speed, and applying brakes.

Concepts
The software object stores its state in fields (also called variables in programming languages) and
exposes its behavior through methods (called functions in programming languages).

Figure 1.1 depicts a ‘Car’ object.

Figure 1.1: A ‘Car’ Software Object

The advantages of using objects are as follows:

They help to understand the real world.



They map attributes and actions of real world entities into state and behavior of software objects.

1.1.4 Defining a Class

In the real-world, several objects having common state and behavior can be grouped under a single
class. For example, a car (any car in general) is a class and a Toyota car (a specific car) is an object or
instance of the class.

A class is a template or blueprint which defines the state and behavior for all objects belonging to that
class.

Core Java
Module 1
Introduction to Java

Typically, in an object-oriented language, a class comprises fields and methods, collectively called as
members, which depict the state and behavior respectively.
Concepts

Figure 1.2 defines a class that represents a conceptual model of a ‘Car’ entity.

Figure 1.2: Defining Class

As shown in figure 1.2, the conceptual model of a class is universal and is not specific to a particular
object. An actual instance of the entity will come into existence when the object is created.

1.1.5 Comparison Between Class and Object

Table 1.1 shows the difference between a class and an object.

Class Object
Class is a conceptual model Object is a real thing
Class describes an entity Object is the actual entity
Class consists of fields (data members) Object is an instance of a class
and functions

Table 1.1: Difference Between a Class and an Object

Core Java
Module 1
Introduction to Java

Figure 1.3 depicts the comparison of a class and an object.

Concepts
Figure 1.3: Comparison of a Class and an Object

As shown in figure 1.3, each object is said to be an instance of its class.

Knowledge Check 1

Can you match the terms against their corresponding description?

Description Term
(A) This represents the behavior of an object (1) Object
(B) This is an instance of a class (2) Class
(C) This represents the state of an object (3) Method
(D) Template or blueprint which defines the state and behavior for all objects (4) Field
This describes an entity

Core Java
Module 1
Introduction to Java

1.2 Getting Started with Java


Concepts

In this second lesson, Getting Started with Java, you will learn to:

Identify the evolution stages of Java.



State the components of the Java platform.

List the features of Java as a programming language.

1.2.1 Introduction to Java

In the year 1995, Sun Microsystems introduced a new programming language to the world - Java. Until
then, the word ‘Java’ could only mean an island in Indonesia or a blend of coffee.

Java is a language and a platform that helps professional programmers to develop wide range of
applications on various platforms. Java is built upon C and C++. It derives its syntax from C and its
features from C++. Java was initially developed to cater to small-scale problems, but was also found
capable of addressing large-scale problems across the Internet. Very soon, Java was hugely successful
and adopted by millions of programmers all across the world.

1.2.2 Evolution

Java has, over the years, undergone a series of changes and evolved into the robust language that it is
today. The different stages of evolution of Java are:

Java Origins: Embedded Systems (1991-1994)



In 1991, a team of engineers from Sun Microsystems wanted to design a language for electronic
devices, such as television, ovens, washing machines, and so on. Thus, the basic objective behind
developing the language was to create software that could be embedded in consumer electronic
devices. In C and C++ languages the compilers were targeted for a particular CPU.

Compilers are expensive and a lot of time is required to create these. Hence, it was not possible to have
compilers for every CPU. An easy and cost efficient way was needed for creating compilers. In addition,
the software had to be small, fast, efficient and platform independent, that is, a code that could run on
different CPUs under different environments. Efforts were taken to produce a portable, platform
independent language, and the result of this led to the creation of Java. James Gosling and a team of
 other programmers were the pioneers behind this development. It was initially called
‘Oak’, but was later renamed to Java.

Core Java
Module 1
Introduction to Java

Java: A Client-side Wonder (1995-1997)


Concepts
In 1995, Web s did not have dynamic capability. Java provided this capability. Later, Java
gained popularity and served as ideal software for network computers.

Java: Moved into the Middle-tier (1997 to Present)

In the late 1990’s, Sun revised middle-tier capabilities for Java to ensure that it runs on
Web/Application Servers. In 1997, Sun defined Servlets for Java to generate dynamic HTML Web
s. Sun also defined Enterprise JavaBeans (EJB) so that business logic can be developed in Java.
In 1999, Sun offered a middle-tier solution for Java called Java 2 Enterprise Edition (J2EE).

Future

In future, Java may gain more success on the client-side. Improved Java performance and the
introduction of Java 2 Micro Edition have opened the door for increased use of Java in embedded
devices.

1.2.3 Platform

A platform is a hardware or software environment in which a program runs. Some of the commonly used
platforms are: Microsoft Windows, Linux, and Solaris. A number of these platforms, such as Linux and
Solaris are a combination of operating system and underlying hardware components.

The Java platform can be considered as an execution engine referred to as virtual engine and not a
specific operating system or hardware. The Java platform comprises two essential components:

The Java Virtual Machine (JVM)



The Java Virtual Machine (JVM) is the Java runtime environment and is available on different
operating systems. It serves as the intermediary between a Java program and a host computer.
JVM executes compiled Java programs (bytecodes). It forms a layer of abstraction for:

Underlying hardware platform

Operating system

Compiled code

Different versions of JVMs are available for different operating systems.

Core Java
JVM (Java Virtual Machine) & Architecture - Java Programming Tutorial
Visit: https://www.youtube.com/watch?v=G1ubVOl9IBw

Understand the Differences between JVM vs JRE vs JDK in java in one video
https://www.youtube.com/watch?v=RJ5NLb2zLhw
Module 1
Introduction to Java

The Java Application Programming Interface (API)



Concepts

Java APIs contain vast libraries of classes and other software components, such as interfaces.
These are included as a part of the Java SDK. Newer releases of Java APIs provide enhanced
features with introduction of new class libraries and packages.

1.2.4 Programming Language

In addition to providing a platform-independent environment, Java is a high-level programming language. It


can be used to create applications and applets (a Java program designed to run within Web browsers).

Java as a programming language has the following features:

Object-oriented

Java is purely object-oriented language. There are no stand-alone constants, variables, or functions
in Java. All of these are part of objects. The constants, variables, or functions in Java are accessed
through classes and objects.

Other hybrid object-oriented languages, such as C++, have features of structured languages as
well as object extensions. For example, C++ is an object-oriented language, but structured pro-
gramming constructs, such as main() method external to any classes and objects still have to be
written, which dilutes the effectiveness of the object-oriented extensions. Java does not allow this
way of declaration. In Java the main() method is to be declared inside a class.

Platform-independent

Platform-independence is the ability of a program to run on any machine regardless of the
underlying platform. Java is platform independent at the source level, and the binary level, that is
the bytecode level.

In short, platform independence at the source level allows moving the source code from one
system to another, compile the code, and run it cleanly on a system.

Using bytecode, Java solves the problem of platform independence. Unlike the C compiler, Java
compiler produces a special format known as bytecode, which is same on every platform.

To run Java on a new computer or an operating system, only the interpreter and a few native
libraries need to be ported. The work of the interpreter is to read the bytecode and translate it into
the native language of the host machine.

Core Java
Module 1
Introduction to Java

Robust

Concepts
Java is strongly typed language. It is designed for writing highly reliable or robust software. Hence,
it requires explicit method declaration. Java checks the code for syntax error at the time of compila-
tion, and also at the time of interpretation. Thus, it eliminates certain programming errors.

Java does not have pointers and pointer arithmetic. It checks all access to arrays and strings at
runtime, to ensure that they are in bounds. It also checks the casting of objects from one type to
another at runtime.

In traditional programming environments, the programmer had to manually allocate memory. By
the end of the program, the programmer had to also explicitly free this memory. Problems arose
when the programmer forgot to deallocate the memory. In Java, the programmer does not need to
bother about memory deallocation. It is done automatically, as Java provides garbage collection for
unused objects.

Java’s exception handling feature simplifies the task of error handling mechanism.

Secure

 Computer viruses are a great cause of worry in the world of computers. Prior to the advent of
Java, programmers had to first scan files before downloading and executing them. Often, even this
precaution was no guarantee against viruses. Also, there are many malicious programs that can
search the contents of your local file system and retrieve sensitive data.

Java provides a controlled environment for the execution of the program. It never assumes that the
code is safe for execution. Since, Java is more than a programming language, it provides several
layers of security control.

In the first layer, the data and methods are accessed only through the interface that the class pro-vides.
Java does not allow any pointer arithmetic. Hence, it does not allow direct access to memory.
It disallows array overflow, and provides garbage collection. All these features help minimise
safety and portability problems.

In the second layer, the compiler ensures that the code is safe, and follows the protocols set by
Java before compiling the code.

The third layer is the safety provided by the interpreter. The verifier provided by interpreter
thoroughly screens the bytecodes to ensure that they obey the rules before executing them.

The fourth layer takes care of loading the classes. The class loader ensures that the class does
not violate the access restrictions, before loading it into the system.

Core Java
Module 1
Introduction to Java

Distributed

Concepts

Java is used to develop applications that are portable across multiple platforms, operating systems,
and graphical user interfaces. It supports network applications. Hence, Java is widely used as a
development tool in an environment like the Internet, which has different platforms.

Multi-threaded

Java provides support for multi-threading to perform many tasks simultaneously. For example, an
application has to carry out a task while waiting for user input. Similarly, in a GUI-based network
application, such as a Web browser, there are usually multiple things going on at the same time.

Dynamic

Java is a dynamic language designed to adapt to an evolving environment. Java source code is
 divided into .java files. The compiler compiles these into .class files containing bytecode. Each
.java file generally produces exactly one .class file.

The compiler first checks the path containing current directory and other directories specified in the
CLASSPATH environment variable. This is required to find other classes explicitly referenced by
name in each source code file. For example, if the file compiled depends on other non-compiled
files, the compiler will try to find them and compile them as well. A compiler can handle circular
dependency as well as methods that are used before they are declared. It also can determine
whether a source code file has changed since the last time it was compiled. Thus, the compiler is
quite smart.

Architecture-neutral

Java technology is designed to support applications which will be deployed into heterogeneous
network environments. In such environments, applications must be capable of executing on a
variety of hardware architectures.

Java programs are compiled to an architecture neutral bytecode format to transport code efficiently
to multiple hardware and software platforms. Hence, the binary distribution problem and the version
problem are solved by the interpreted nature of Java technology.

Any system that implements the Java Virtual Machine allows the Java application to run on that
system. This is useful not only for the networks, but also for single system software distribution.

Portable

The portability actually comes from architecture-neutrality. Java technology takes portability a stage
further by being strict in its definition of the basic language. It explicitly specifies the size of its basic
data types to eliminate implementation dependence, and the behavior of its arithmetic operators.
The Java system itself is quite portable.

Core Java
Module 1
Introduction to Java

The Java compiler is written in Java, while the Java run-time system is written in ANSI C with a
clean portability boundary.

Concepts
High Performance

Performance is always a consideration. Compared to those high-level, fully-interpreted scripting
languages, Java is high-performance. The automatic garbage collector runs as a low-priority
background thread, ensuring a high probability. Sun claims that the performance of bytecodes
converted to machine code is nearly as good as native C or C++.

Knowledge Check 2

Which of these statements about the components of the Java platform are true and which
statements are false?

Java APIs contain libraries of classes and other software components such as interfaces
JVM serves as the intermediary between a Java program and a host computer
JVM executes compiled Java programs also called as bytecodes
The Java SDK does not include APIs
JVM is not available on different operating systems

Can you match the features of Java against their corresponding descriptions?

Description Feature
(A) Provides security control (1) Platform-independent
Supports the development of applications across multiple (2) Object-oriented
platforms, operating systems and graphic user interfaces
All constants, variables, or functions must exist within classes (3) Distributed or
objects
(D) Java provides support for performing many tasks (4) Secure
simultaneously
(E) Can run on any machine (5) Multithreading

Core Java
Module 1
Introduction to Java

1.3 Introduction to JDK


Concepts

In this third lesson, Introduction to JDK, you will learn to:

Explain JDK and its tools.



Explain JVM.

Configure JDK.

1.3.1 Java Development Kit

The Java Development Kit (JDK) is provided by Sun Microsystems and is popularly used by Java
programmers worldwide. The purpose of JDK is to provide the software and tools required for compiling,
debugging, and executing Java applications. The JDK software and documentation are freely available
at Sun’s official Web site.

Java Standard Edition, popularly called Java SE, is a technology and platform that provides support to
build applications that have high functionality, speed, and reliability. Java SE Development Kit, popularly
called JDK, includes the necessary development tools, runtime environment, and APIs for creating Java
programs with the Java platform.

JDK includes two important tools:

javac (compiler)

The javac compiler is used to compile Java source code into bytecodes. The source code can be
created using an Integrated Development Environment, such as NetBeans or a simple text editor,
such as Notepad.

Syntax:

javac [option] source

where,

source is one or more file names that end with the extension .java.

For example,
javac FirstProgram.java

This command will produce a file named ‘FirstProgram.class’. This class file is what runs on
the Java Virtual Machine.

Core Java
Module 1
Introduction to Java

Table 1.2 lists some of the options that can be supplied for the javac compiler.

Concepts
Option Description
-classpath Specifies the location for import classes (overrides
the CLASSPATH environment variable).
-d Specifies the destination directory for class files.
-g Prints all debugging information instead of the
default line number and file name.
-verbose Produces additional output about each class
loaded and each source file compiled.
-version Displays version information.
-sourcepath Imports a class location.
-help Prints a synopsis of standard options.

Table 1.2: Options for javac Compiler

Consider an example using an option -d.

javac -d c:\ FirstProgram.java

This command will produce and save ‘FirstProgram.class’ file in C drive.

java (interpreter)

The java interpreter is used to interpret and run Java bytecodes. It takes the name of a class file
as an argument for execution.

Syntax:

java [option] classname [arguments]

where,

classname is the name of the class file.

arguments is the arguments passed to the main function.

For example,

java FirstProgram

Core Java
Module 1
Introduction to Java

Table 1.3 lists some of the options that can be supplied for the java interpreter.
Concepts

Options Description
classpath Specifies the location for import 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 usage information and exits.
-X Displays information about non-standard options and exits.

Table1.3: Options for java Interpreter

1.3.2 Java Virtual Machine

The Java Virtual Machine (JVM) is at the heart of the Java programming language. The Java
environment consists of five elements:

Java language

Bytecode definitions

Java/Sun libraries

Java Virtual Machine

Structure of .class files

The portability feature of the .class file has made the principle of Java ‘ write once, and run anywhere’
possible. This file helps the execution on any computer or chip set, with an implementation of the JVM.

The virtual machine is a software concept based on the idea of an imaginary computer. It has a logical
set of instructions. These instructions define the operations of this imaginary computer. It can be thought
as a mini operating system. It forms a layer of abstraction for the underlying hardware platform, the
operating system, and the compiled code.

The compiler converts the source code into a code based on the imaginary computer’s instruction set
that is not targeted to a particular processor. An interpreter is an application that understands these
streams of instructions. It converts these instructions for the underlying hardware to which the interpreter
is targeted.

Core Java
Module 1
Introduction to Java

The JVM internally creates a runtime system that helps in execution of code through the following steps:

Concepts
Loading the .class files

Class loaders are one of the fundamentals of the JVM architecture. They enable the JVM to load
classes without knowing anything about the file system semantics, and they allow applications to
dynamically load Java classes as extension modules.

Managing the memory

The JVM manages memory in the following way:

When a JVM is invoked to run an application, it requests the operating system for enough
memory for the JVM itself for running and free memory for the application to create new
objects.

When a new object is created, the JVM allocates memory for that object from the free
memory area.

When the free memory area is reduced after several object creations, the JVM asks the
operating system for more.

When an object is no longer used, it will be destroyed. The memory occupied by it will be
freed up and it will be merged back to the free memory area.

When the free memory area is occupied, and no more additional memory is available from
the operating system, the JVM will halt the application that created the situation, and will raise
‘Out of memory error’.

Performing the garbage collection

The garbage collector releases the memory occupied by an object once it determines that the object
is no longer accessible. This automatic process makes it safe to throw away unnecessary object
references because the garbage collector does not collect the object if it is still needed elsewhere.
Therefore, in Java the act of releasing unnecessary references never runs the risk of deallocating
memory prematurely.

The other popular concept in Java is the use of the ‘Just-In-Time’ (JIT) compiler. Browsers, such as
Netscape Navigator and Internet Explorer include JIT compilers that increase the speed of Java code
execution. JIT’s main purpose is to convert the bytecode instruction set to machine code instructions
targeted for a particular microprocessor. These instructions are stored and used whenever a call is made
to that particular method.

Core Java
Module 1
Introduction to Java

Figure 1.4 shows the relationship between the Java compiler and JIT compiler.
Concepts

Figure 1.4: Relationship between Java Compiler and JIT Compiler

1.3.3 Configuring JDK

To work with the JDK and Java programs, certain settings need to be made to the environment variables.
Environment variables are pointers pointing to programs or other resources. The variables to be
configured are as follows:

PATH

The PATH variable is set to point to the location of Java executables (javac.exe, java.exe).
This is necessary so that the javac and java command can be executed from any directory
without having to type the full path.

Setting path in DOS:

C:\>set path=<drivename>:\<installation_folder>\bin

Setting path in Windows 2000/XP:

Right-click the My computer icon present on the desktop. Click properties. Click Advanced tab.
Click Environment variables. In the System variable area, select the PATH variable. Click Edit
and type the path of the bin folder of jdk1.5.

Core Java
Module 1
Introduction to Java

CLASSPATH

Concepts
CLASSPATH is an environment variable that specifies the location of the class files and libraries
needed for the Java compiler (javac) to compile applications.

Setting CLASSPATH in DOS:

C:\>set CLASSPATH=<drivename>:\<installation_folder>

Setting CLASSPATH in Windows 2000/XP:

Right-click My Computer icon present on the desktop. Click properties. Click Advanced tab. Click
Environment variables, and then in System variables area click New. Type CLASSPATH in
Variable Name and then type C:\jdk1.5.0 as value. Click OK.

1.4 Writing a Java Program

In this fourth lesson, Writing a Java program, you will learn to:

Identify the steps in writing a Java program.



Describe how to compile and execute a Java program.

1.4.1 Steps

A step by step procedure to create a simple Java program is now discussed here. The program will
display a message, ‘Welcome to the world of Java’.

Step 1: Declare a class

class <class_name> {
}

where,

class is a keyword and <classname> is the class name.

Opening and closing curly braces tell the compiler where the class will begin and end. The area
between the braces is known as the class body and contains the code for that class.

Core Java
Module 1
Introduction to Java

For instance,
Concepts

class HelloWorld {
}

HelloWorld is the identifier depicting the name of the class.

Step 2: Write the main method



The main() method is the entry point for an application.

Syntax:

public static void main(String[] args)

{ }

where,

public keyword enables the JVM to access the main method.

static keyword allows a method to be called from outside a class without creating an in-
stance of the class.

void keyword tells the compiler that the method will not return any value.

args is an array of type String and stores command line arguments.

Step 3: Write desired functionality



In this step, actionable statements are written within the methods. The current example illustrates
a string can be displayed as the output.

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

System.out.println() statement displays the string that is passed as an argument.



Step 4: Save the program

Save the file with a .java extension. The name of the file plays a very important role in Java. A
.java extension is a must for a Java program. In Java, the code must reside in a class, and
hence the class name and the file name would be the same most of the times.

Core Java
Module 1
Introduction to Java

1.4.2 Compile and Execute

Concepts
The Java compiler, javac.exe, compiles a Java program by checking the syntax, grammar, and the
data types used in it. Compilation leads to creation of a file with a .class extension. The file contains
the bytecode that is interpreted and converted into machine code before execution.

To actually run the program, the Java interpreter, java.exe, is required, which will interpret and run the
code. Figure 1.5 demonstrates the compilation and execution steps of the Java program.

Figure 1.5: Compilation and Execution

Knowledge Check 4

Which of these statements about compiling and executing a Java program are true and which
statements are false?

The javac tool invokes the Java compiler


The java tool invokes the Java interpreter
The Java interpreter checks for the syntax, grammar, and data types of the program
The .class files contain bytecodes
The Java interpreter compiles the code

Core Java
Can you match the elements of NetBeans IDE against their corresponding descriptions?

Description Element
(A) Shows compilation errors, debugging messages, and Javadoc (1) Runtime window

Concepts
Comments
(B) Directs the user in adding the missing code (2) Properties window
Displays information on currently running processes and (3) Source Editor
registered servers
Consists of Source packages, Test Packages, Libraries, and (4) Output window Test
Libraries
(E) Lists the properties of the control selected (5) Project window

Java Lambda Expressions


Lambda expression is a new and important feature of Java which was included in Java SE 8. It provides a
clear and concise way to represent one method interface using an expression. It is very useful in collection
library. It helps to iterate, filter and extract data from collection. Before lambda expression, anonymous inner
class was the only option to implement the method.

In other words, we can say it is a replacement of java inner anonymous class. Java lambda expression is
treated as a function, so compiler does not create .class file.

Functional Interface
Lambda expression provides implementation of functional interface. An interface which has only one
abstract method is called functional interface. Java provides an anotation @FunctionalInterface, which is
used to declare an interface as functional interface.

Why use Lambda Expression


1. To provide the implementation of Functional interface.
2. Less coding.

Java Lambda Expression Syntax


1. (argument-list) -> {body}

Java lambda expression is consisted of three components.

1) Argument-list: It can be empty or non-empty as well.

2) Arrow-token: It is used to link arguments-list and body of expression.


3) Body: It contains expressions and statements for lambda expression.

Let's see a scenario. If we don't implement Java lambda expression. Here, we are implementing an interface
method without using lambda expression.

Java 8 Method Reference


A method reference is the shorthand syntax for a lambda expression that executes just ONE
method. Here's the general syntax of a method reference:

Object :: methodName

We know that we can use lambda expressions instead of using an anonymous class. But
sometimes, the lambda expression is really just a call to some method, for example:

Consumer<String> c = s -> System.out.println(s);

To make the code clearer, you can turn that lambda expression into a method reference:

Consumer<String> c = System.out::println;

In a method reference, you place the object (or class) that contains the method before the ::
operator and the name of the method after it without arguments.

But you may be thinking:

• How is this clearer?


• What will happen to the arguments?
• How can this be a valid expression?
• I don't understand how to construct a valid method reference...

First of all, a method reference can't be used for any method. They can only be used to replace a
single-method lambda expression.

So to use a method reference, you first need a lambda expression with one method. And to use a
lambda expression, you first need a functional interface, an interface with just one abstract method.

In other words:

Instead of using
AN ANONYMOUS CLASS
you can use
A LAMBDA EXPRESSION
And if this just calls one method, you can use
A METHOD REFERENCE
There are four types of method references:

• A method reference to a static method.


• A method reference to an instance method of an object of a particular type.
• A method reference to an instance method of an existing object.
• A method reference to a constructor

Java 8 Type Annotations


Java annotation is a tag that represents the metadata i.e. attached with class, interface,
methods or fields to indicate some additional information which can be used by java compiler and
JVM.

➢ Built- In Java Annotation


1. @Override
2. @SupressWarnings
3. @Deprecated
4. @Target
5. @Retention
6. @Inherited
7. @Documented

Method Parameter Reflection


With the new getParameters() method of the class Method from the Reflection API, it is
possible to retrieve the formal parameter name of a method. Earlier it was only possible to retrieve
the number of method parameters and their types.

The prerequisite is that the class which contains the method for which we want to retrieve
the parameter names of a method has been compiled with the new javac option -parameters. The
runtime libraries have not been compiled with this option, so we cannot retrieve the parameter
names of methods from the standard runtime library.
Module 1
Introduction to Java

1.6 Using Comments in Java


Concepts

In this last lesson, Using Comments in Java, you will learn to:

State the syntax of single-line comments.



State the syntax of multi-line comments.

State the syntax of Javadoc comments.

1.6.1 Single-line Comments

Comments help easy understanding of code. A single-line comment is used to document the functionality of
a single line of code. Figure 1.13 shows the Java program documented with single-line comments.

Figure 1.13: Single-line Comments

There are two ways of using single-line comments:

Beginning-of-line comment

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).

Conventions for using single-line comments are as follows:

Provide a space after the forward slashes.



Capitalize the first letter of the first word.

30 Core Java
Module 1
Introduction to Java

The following is the syntax for applying the comments.

Concepts
Syntax:

// Comment text

The following code shows the different ways of using single-line comments in the Java program.

Code Snippet:

Declaring a variable
int a = 32;
int b = 64; // Declaring a variable

1.6.2 Multi-line Comments

A multi-line comment is a comment that spans multiple lines. A multi-line comment starts with a forward
slash and an asterisk (/*). It ends with an asterisk and a forward slash (*/). Anything that appears
between these delimiters is considered to be a comment. Figure 1.14 shows the Java program
documented with multi-line comments.

Figure 1.14: Multi-line Comments

Core Java 31
Module 1
Introduction to Java

The following code shows a Java program using multi-line comments.


Concepts

Code Snippet:

/*
This code performs mathematical
operation of adding two numbers.
*/
int a = 20;
int b = 30;
int c;
c = a + b;

1.6.3 Javadoc Comments

A Javadoc comment is used to document public or protected classes, attributes, and methods. It starts
/** and ends with */. Everything between the delimiters is a comment, even if it spans multiple lines.
The javadoc command can be used for generating Javadoc comments. Figure 1.15 shows the Java
program with Javadoc comment.

Figure 1.15: Javadoc Comments

32 Core Java
Module 1
Introduction to Java

The following code shows the Javadoc comment specified on the method in the Java program.

Concepts
Code Snippet:

/**
This program prints a welcome message
using the println statement.
*/
System.out.println(“Welcome to Java Programming”);

Knowledge Check 6

Which of these statements about comments are true and which statements are false?

A multi-line comment starts with a forward slash and a hash (/#)


A single-line comment is used to document the functionality of a single line of code
A Javadoc comment ends with double asterisk and a forward slash (**/)
A multi-line comment can span several lines
Comment appears within delimiters
Module Overview

Welcome to the module, Variables and Operators. This module focuses on the usage of
variables, data types, and operators in Java programs. This module aims at providing a clear
understanding of the different data types available in Java. It also, discusses the different
operators and their implementation in Java programs. The implicit and explicit data conversion
techniques are also covered in this module.

In this module, you will learn about:

Concepts
Introduction to Variables

Introduction to Data Types

Formatted Output and Input

Operators

Type Casting

2.1 Introduction to Variables

In this first lesson, Introduction to Variables, you will learn to:

Explain variables and their purpose.



Explain the rules and conventions for naming variables.

Explain declaring literals.

2.1.1 Variables

A variable is a location in the computer’s memory where a value is stored and from which the value can
be retrieved later.

Variables are used in a Java program to store data that changes during the execution of the program.
They are the basic units of storage in a Java program. Variables can be declared to store values, such
as names, addresses, and salary details. Variables must be declared, before they can be used.

Core Java page 35


Module 2
Variables and Operators

Figure 2.1 shows the storage of variable in memory.


Concepts

Figure 2.1: Variable Storage in Memory

Syntax:

datatype variableName;

where,

datatype is a valid data type in Java.

variableName is a valid variable name.

The following code shows the declaration of variables.

Code Snippet:

int rollNumber;
char gender;

The statements declare an integer variable called rollNumber, and a character variable called gender.
These statements instruct the operating system to allocate the required amount of memory to each variable
in order to hold the type of data specified for each. Additionally, each statement also provides a name that can
be used within the program to access the values stored in each of the variables.

Values can be assigned to variables by using the assignment operator (=) as follows:

rollNumber = 101;

gender = ‘M’;

page 36 Core Java


Module 2
Variables and Operators

101 and ‘M’ are called literals. You can also assign a value to a variable upon creation, as shown:

Concepts
int rollNumber = 101;

The following code shows the different ways for declaring and initializing variables.

Code Snippet:

Line 0: int x, y, z; // declares three integer variables x, y and z.


Line 1: int a = 5, b, c = 10; // declares three integer variables,
initializes a and c.
Line 2: byte num = 20; // declares a byte variable num and initializes its
value to 20.
Line 3: char c = ‘c’; // declares the character variable c with value ‘c’.
Line 4: int num1 = num2 = 10; // value 10 is stored in num1 and num2.

As shown in the code, Line 0 and Line 1 are examples of comma separated list of variables. Line
4 displays an example of same value assigned to more than one variable at the time of declaration.

2.1.2 Rules and Conventions

Java programming language has its own set of rules and conventions that need to be followed for
naming variables. For a start, variable names should be short and meaningful.

Not adhering to the rules will result in syntax errors. Naming conventions are to be followed as they
ensure good programming practices.

Naming Conventions

The rules and conventions for naming variables are as follows:

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).

Core Java page 37


Module 2
Variables and Operators

If a variable name comprises a single word, the name should be in lowercase (for example,
velocity or ratio).
Concepts


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).

2.1.3 Variable Names

The variable names in Java should start with a letter (A-Z or a-z), dollar sign ($), or underscore (_).

Table 2.1 lists some 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

Table 2.1: Valid and Invalid Java Variable Names

2.1.4 Declaring Literals

A literal signifies a fixed value and is represented directly in the code without requiring computation. For
example, the following code shows assigning of literals in the Java program.

Code Snippet:

Line 1: int val = 50;


Line 2: float num = 35.7F;
Line 3: char x = ‘x’;

A literal is used wherever a value of its type is allowed. However, there are several different types of
literals. Some of them are as follows:

⸀ĀᜀĀᜀ Integer Literals



Integer literals are used to represent an int value, which in Java is a 32-bit integer value.

page 38 Core Java


Module 2
Variables and Operators

In a program, integers are probably the most commonly used type. Any whole number value is an
integer literal.

Concepts
Integers can be expressed as:

Decimal values, expressed in base 10



Octal values, expressed in base 8

Hexadecimal values, expressed in base 16

Each of these have their own literal. 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. Integer numbers can be
represented with an optional uppercase character (‘L’) or lowercase character (‘l’) at the end, which
tells 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.

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

Type suffix D, d, F, or f.

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 variables declared as boolean,
or used in expressions with Boolean operators.

Core Java page 39


Module 2
Variables and Operators

Character Literals

Concepts

Character literals are enclosed in single quotes. All of the visible ASCII characters can be directly
entered inside the quotes, such as ‘g’, ‘$’, and ‘z’. Single characters that cannot be directly entered
are hyphen (-) and backslash (\).

Null Literals

When an object is created, a certain amount of memory is allocated for that object. The starting
address of this memory is stored in an object, 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 as shown in the following example:

obj = null;

String Literals

String literals consist of sequence of characters enclosed in double quotes. The characters can be
printable or non-printable. However, backslash, double quote and non-printable characters are
represented using escape sequences. Following is an example of String literal:

“Welcome to Java”

Knowledge Check 1

Which of these statements about variables are true and which statements are false?

Variables need not be initialized when declared


Variable names $bank_account and _1account_balance are valid
Only one variable can be declared in a statement at a time
Variables can be declared to store any type of values
Variable names must begin with a letter, the dollar sign ($), or the underscore character (_)

page 40 Core Java


Module 2
Variables and Operators

2.2 Introduction to Data Types

Concepts
In this second lesson, Introduction to Data Types, you will learn to:

Identify the different data types and explain their purpose.



State the different primitive data types.

State the different reference data types.

2.2.1 Data Types


When you define a variable in Java, you must tell 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 the variable. The data
type of a variable, therefore, determines the type of data that can be stored in the variable and the
operations that can be performed on this data.

Java is a strongly typed language. This means that every variable has a type, every expression has a
type, and every type is strictly defined. It also means that all assignments, whether explicit or via
parameter passing in method calls, are checked for type compatibility by the Java compiler. Any type
mismatches are considered as errors and need to be corrected before compilation is over.

In Java programming language, data types are mainly divided into two categories and they are as follows:

Primitive data types



Reference data types

2.2.2 Primitive Data Types

The Java programming language provides primitive data types to store and represent data. A primitive
data type, also called built-in data types, stores a single value, normally a literal of some sort, such as a
number or a character.

Table 2.2 lists the primitive data types in Java.

Data Type Description Range


byte 8-bit signed integer -128 to 127
short 16-bit signed integer -32768 to 32767

Core Java page 41


Module 2
Variables and Operators

Data Type Description Range


Concepts

long 64-bit signed integer -9,223,372,036,854,775,808


to
9,223,372,036,854,775,807
int 32-bit signed integer -2,147,483,648 to 2,147,483,647
float 32-bit floating-point variable -3.40292347E+38 to +3.40292347E+38
boolean Stores a true or false value true or false
char 16-bit Unicode character 0 to 65535
double 64-bit floating-point variable -1.79769313486231570E+308
to
1.79769313486231570E+308

Table 2.2: Primitive Data Types in Java

2.2.3 Variables of Primitive Data Types

Whenever a variable is declared, it is either assigned a value (if the variable has been declared and
initialized on the same line) or it holds a default value (if the variable has only been declared and not
initialized). More than one variable of the same data type can be declared in Java by using the comma
(,) separator.

The following code demonstrates the declaration and initialization of variables in Java.

Code Snippet:

int empNumber;
float salary;
char gender = ‘M’;
double shareBalance = 456790.897;
boolean ownVehicle = false;

empNumber = 101;
salary = 6789.50f;

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);

The snippet demonstrates how to declare and initialize variables in Java.

page 42 Core Java


Module 2
Variables and Operators

Here, variables of type int, float, char, double, and boolean are declared. All float values need to
have an f appended at its end. Values are assigned to each of these variables and are displayed using

Concepts
the println() method.

2.2.4 Reference Data Types

A variable of a reference data type holds the reference to the actual value or a set of values represented
by the variable.

Table 2.3 displays three reference data types that are available in Java.

Data Type Description


Array A collection of several items of the same data type such as names of students.
Class A collection of variables and methods. For example, class Student containing the
complete details of the students and the methods that operate on the details.
Interface A type of class in Java used to implement multiple inheritance.

Table 2.3: Reference Data Types in Java

Knowledge Check 2

Can you match the values which will optimally fit with the corresponding data type?

Data Type Value


(A) byte (1) 256
(B) char (2) 50000
(C) int (3) 48999.988
(D) short (4) 126
(E) double (5) ‘F’

Core Java page 43


Strings
Strings are a sequence of characters. In the java programming language, Strings are the objects.
The java platform provides the string class to create and manipulate strings. String class is
encapsulated under java.lang package.

Creating a String Object

The String class is used to represent character strings. Strings are constant, which means their values
cannot be changed after they are created.

In Java, strings are objects. An instance of a String class can be created with the new keyword.

The following code creates a new object of class String, and assigns it to the reference variable, str.
Then, it assigns a value to the string variable.

Code Snippet:

String str = new String();

str = “Hello World”;

The following code snippet demonstrates the usage of String objects.

Code Snippet:

String empName = new String(); //string object, empName


String typeOfWork = new String(); //string object, //typeOfWork

Scanner input = new Scanner(System.in);


System.out.println(“Enter Employee name: “); empName =
input.nextLine(); //accepts employee name
System.out.println(“Enter type of work: “); typeOfWork =
input.nextLine(); //accepts type of work

//Displaying details
System.out.println(“Employee Name: “+empName);
System.out.println(“Type of Work: “+typeOfWork);

The code accepts values into two string variables, empName and typeOfWork and prints them. The
nextLine() method of the Scanner class can be used to input string values.
Output:

Enter Employee name: David Blake


Enter type of work: Programming
Employee Name: David Blake
Type of Work: Programming
Methods:
length():The length() method can be used to find the length of a string.

charAt():The charAt() method can be used to get the character value at the specified index.

concat():The concat() method can be used to concatenate the specified string to the end of a
string.

compareTo(): The compareTo() method compares two particular objects of String class and returns
an integer as the result. The comparison is based on the Unicode value of each character in the strings.

indexOf():This method returns the index of the first occurrence of the specified character or string
within a string. If the character or string is not found, the method returns -1.

lastIndexOf(): The lastIndexOf() method is used to return the index of the last occurrence of a
specified character or string within a string. The specified character or string is searched backwards
that is the search begins from the last character.

replace(): The replace() method replaces all the occurrences of a specified character in the current
string with a given new character. If the specified character does not exist, the reference of original
String is returned.

substring(): The substring() method can be used to retrieve a part of a string, that is, substring
from the given string.

trim(): The trim() method returns a new string by trimming the leading and trailing whitespace from
the current string.

toUpperCase(): The toUpperCase() method converts the characters in the string to upper case.

toLowerCase(): The toLowerCase() method converts the characters in the string to lower case.

toString():The toString() method can be used to return a String object.



Module 2
Variables and Operators

2.3 Formatted Output and Input


Concepts

In this third lesson, Formatted Output and Input, you will learn to:

State the different format specifiers in Java.



Identify the methods for accepting formatted input.

List the various escape sequence characters in Java.

2.3.1 Format Specifiers

Whenever an output is to be displayed on the screen, it needs to be formatted. The formatting can be
done with the help of format specifiers in Java. The printf() method introduced in J2SE 5.0 can be
used to format the numerical output to the console.

Table 2.4 lists some of the format specifiers in Java.

Format Specifier Description


%d Result formatted as a decimal integer
%f Result formatted as a real number
%o Results formatted as an octal number
%e Result formatted as a decimal number in scientific notation
%n Result is displayed in a new line

Table 2.4: Format Specifiers in Java

The following code demonstrates the use of various format specifiers.

Code Snippet:

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);

page 44 Core Java


Module 2
Variables and Operators

Negative infinity q
= -10.0/0.0;

Concepts
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);

Output:

55/22 = 2
21.0/55.0 = 00000.500
5000/3.0 = 1.67e+03
-10.0/0.0 = -Infinity
pi = 3.142, e = 2.7183

In the snippet, ‘%09.3f’ indicates that there will be total 9 digits including decimal point and three places
of decimals. If the number of digits is less than 9, then it will be padded with zeroes. If ‘0’ is omitted from
‘%09.3f’, then it will be padded with spaces.

2.3.2 ‘Scanner’ Class

The Scanner class allows the user to read values of various types. To use the Scanner class, pass the
InputStream object to the constructor.

Scanner input = new Scanner(System.in);

Here, input is an object of Scanner class and System.in is an input stream object.

Table 2.5 lists the different methods of the Scanner class that can be used to accept numerical values
from the user.

Method Description
nextByte() Returns the next token as a byte value
nextInt() Returns the next token as an int value
nextLong() Returns the next token as a long value
nextFloat() Returns the next token as a float value
nextDouble() Returns the next token as a double value

Table 2.5: Methods of Scanner Class

Core Java page 45


Module 2
Variables and Operators

The following code demonstrates the Scanner class methods and how they can be used to accept
values from the user and finally print the output.
Concepts

Code Snippet:

//creates an object and passes the inputstream object


Scanner s = new Scanner(System.in); //Accepts values
from the user
byte byteValue = s.nextByte();
int intValue = s.nextInt();
float floatValue = s.nextFloat();
long longValue = s.nextLong();
double doubleValue = s.nextDouble();

System.out.println(“Values entered are: “);


System.out.println(byteValue + “ “ + intValue + “ “ + floatValue + “ “ +
longValue + “ “ + doubleValue);

Output:

Values entered are:

121 2333 456.789 456 3456.876

Note:

Package

A package is a collection of classes.

Scanner Class

The Scanner class belongs to the java.util package. The Scanner looks for tokens in the input. A
token is a series of characters that ends with delimiters. A delimiter can be a whitespace (default
delimiter for tokens in Scanner class), a tab character, a carriage return, or the end of the file. Thus, if
we read a line that has a series of numbers separated by whitespaces, the scanner will take each
number as a separate token.

Constructor

Constructors are used to create an instance of a class.

page 46 Core Java


Module 2
Variables and Operators

InputStream

Concepts
Characters are read from the keyboard by using System.in.

2.3.3 Escape Sequences

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 connotation in a Java program (such as \
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.

Table 2.6 displays the various escape sequences in Java.

Escape Sequence Description


\b Backspace character
\t Horizontal Tab character
\n New line character
\’ Single quote marks
\\Backslash
\r Carriage Return character
\” Double quote marks
\f Form feed
\xxx Character corresponding to the octal value xxx, where
xxx is between 000 and 0377
\uxxx Unicode corresponding with encoding xxxx, where
is one of four hexadecimal digits. Unicode
escapes are distinct from the other escape types

Table 2.6: Escape Sequences in Java

The following code demonstrates the use of escape sequence characters.

Code Snippet:

use of tab and new line escape sequences


System.out.println(“Java \t Programming \n Language”);
printing Tom “Dick” Harry string

System.out.println(“Tom \“Dick\” Harry”);

Core Java page 47


Module 2
Variables and Operators

Output:
Concepts

Java Programming
Language
Tom “Dick” Harry

To represent a Unicode character, Unicode \u escape sequence can be used anywhere in a Java
program. A Unicode character can be represented using hexadecimal or octal sequences.

The following code demonstrates the use of \xxx and \uxxx escape sequence types.

Code Snippet:

Print ‘Hello’ using hexadecimal escape sequence characters


System.out.println(“\u0048\u0065\u006C\u006C\u006F” + “!\n”);

Print ‘Blake’ using octal escape sequence character for ‘a’


System.out.println(“Bl\141ke\”2007\” “);

The output of Code Snippet 6 is as follows:


Hello!
Blake”2007”

Note: The hexadecimal escape sequence starts with \u followed by 4 hexadecimal digits. The octal
escape sequence comprises 3 digits after back slash. For example,

\xyy

where, x can be any digit from 0 to 3 and y can be any digit from 0 to 7.

Knowledge Check 3

You are trying to use the format specifiers to display the output, “100 * 55.0 = 5500.000”,
“100 * 55.0 = 5500.000000”, “100 * 55.0 = 5.50e+03”, and “100 * 55.0 = 0”.
Which of the following code will help you to achieve this?

page 48 Core Java


Module 2
Variables and Operators

double result = 100 * 55;


int q = 0;

Concepts
System.out.printf (“100 * 55.0 = %1.3f %n”, result);
System.out.printf (“100 * 55.0 = %5f %n”, result);
System.out.printf (“100 * 55.0 = %1.5f %n”, result);
System.out.printf (“100 * 55.0 = %d %n”, q);
double result = 100 *
55; int q = 0;
System.out.printf (“100 * 55.0 = %1.3f %n”, result);
System.out.printf (“100 * 55.0 = %5f %n”, result);
System.out.printf (“100 * 55.0 = %1.2e %n”, result);
System.out.printf (“100 * 55.0 = %d %n”, q);
double result = 100 *
55; int q = 0;
System.out.printf (“100 * 55.0 = %09.3f %n”, result);
System.out.printf (“100 * 55.0 = %5f %n”, result);
System.out.printf (“100 * 55.0 = %f %n”, result);
System.out.printf (“100 * 55.0 = %d %n”, q);
double result = 100 *
55; int q = 0;
System.out.printf (“100 * 55.0 = %3f %n”, result);
System.out.printf (“100 * 55.0 = %5f %n”, result);
System.out.printf (“100 * 55.0 = %1.2e %n”, result);
System.out.printf (“100 * 55.0 = %d %n”, q);

Which of these statements about escape sequences are true and which of these are false?

The escape sequence character \n represents a new line character


The nextDouble() method of Scanner class returns the next token as a byte value
The escape sequence character \r represents a backslash character
The escape sequence character \\ represents a new line character
The nextByte() method of Scanner class returns the next token as a byte value

Core Java page 49


Module 2
Variables and Operators

2.4 Operators
Concepts

In this fourth lesson, Operators, you will learn to:

Describe an operator and explain its purpose.



Identify and explain the use of Assignment, Arithmetic, and Unary operators.

Identify and explain the use of Equality, Relational, and Conditional operators.

Identify and explain the use of Bitwise and Bit Shift operators.

Explain operator precedence.

Explain operator associativity.

2.4.1 Purpose
All programming languages provide some mechanism for performing various operations on the data
stored in variables. The simplest form of operations involves arithmetic (like adding, dividing, or
comparing between two or more variables). A set of symbols is used to indicate the kind of operation to
be performed on data. These symbols are called operators.

Consider the expression:

Z = X + Y

The + symbol in the statement is called the operator and the operation performed is addition. This
operation is performed on the two variables X and Y, which are called operands. The combination of both
the operator and the operands, Z = X + Y, is known as an Expression.
Java provides several categories of operators and they are as follows:

Arithmetic

Relational

Logical

Assignment

Bitwise

page 50 Core Java


Module 2
Variables and Operators

Bit Shift

Concepts
2.4.2 Assignment Operator

The basic assignment operator is a single equal to sign, ‘=’. 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:

int balance = 3456;


char gender = ‘M’;

In the statements, the values 3456 and M are assigned to the variables namely, balance and gender.

In addition to the basic assignment 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.

= 3; X

+= 5;

The second statement stores the value 8, the meaning of the statement is that X = X + 5.

The following code demonstrates the use of different assignment operators.

Code Snippet:

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

2.4.3 Arithmetic Operator

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.

Core Java page 51


Module 2
Variables and Operators

Table 2.7 lists the arithmetic operators.


Concepts

Operator Description
Addition - Returns the sum of the operands.
Subtraction - Returns the difference of two operands.
*Multiplication - Returns the product of operands.
/Division – Returns the result of division operation.
Remainder - Returns the remainder from a division
operation.
Table 2.7: Arithmetic Operators

The following code demonstrates the arithmetic operators.

Code Snippet:

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

2.4.4 Unary Operator

Unary operators require only one operand. They perform various operations, such as incrementing/
decrementing the value of a variable by 1, negating an expression, or inverting the value of a boolean.

Table 2.8 lists the unary operators.

Operator Description
Unary plus - Indicates a positive value.
Unary minus - Negates an expression.
Increment operator - Increments value of a variable by 1.
Decrement operator - Decrements value of a variable by
1.
Logical complement operator - Inverts a boolean value.

Table 2.8: Unary Operators

The ++ and -- operators can be applied before (prefix) or after (postfix) the operand. The statements
++variable and variable++ both result in incrementing the variable value by 1. The only difference
is that the prefix version (++variable) will increment the value before evaluating, whereas the postfix
version (variable++) will first evaluate and then increment the original value.

page 52 Core Java


Module 2
Variables and Operators

The following code demonstrates the unary operators.

Concepts
Code Snippet:

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

2.4.5 Equality and Relational Operators

Equality and relational operators test the relationship between two operands. An expression involving
relational operators always evaluates to a boolean value (that is, either true or false).

Table 2.9 lists the various relational operators.

Operator Description
Equal to - Checks equality of two numbers.
!= Not Equal to - Checks inequality of two values.
Greater than - Checks if value on left is greater than the value on the right.
Less than - Checks if the value on the left is lesser than the value on the right.
>= Greater than or equal to - Checks if the value on the left is greater than or equal to the
value on the right.
<= Less than or equal to – Checks if the value on the left is less than or equal to the value
on the left.

Table 2.9: Relational Operators

The following code demonstrates the relational operators.

Code Snippet:

int value1 = 10;


int value2 = 20;
value1 == value2; //returns false
value1 != value2; //returns true
value1 > value2; //returns false
value1 < value2; //returns true

Core Java page 53


Module 2
Variables and Operators

value1 <= value2; //returns true


Concepts

2.4.6 Conditional Operators

Conditional operators (&& and ||) work on two boolean expressions. These operators exhibit short-
circuiting behavior, which means that the second operand is evaluated only if needed.

Table 2.10 lists the two conditional operators.

Operator Operator
Conditional AND - Returns true only if both the expressions are true.
|| Conditional OR - Returns true if either expression is true or both the expressions are
true.

Table 2.10: Conditional Operators

Ternary operator (?:) is another type of conditional operator; it accepts three operands. The syntax for
the usage of ternary operator is as follows:

expression1 ? expression2 : expression3

where,

expression1: is a boolean condition that returns a true or false value

expression2: is the value returned if expression1 evaluates true

expression3: is the value returned if expression1 evaluates false

The following code demonstrates the conditional operators.

Code Snippet:

int first = 10;


int second = 20;
(first == 30) && (second == 20 ); //returns false
(first == 30) || (second == 20 ); //returns true
(second > first) ? “second number is greater” : “first number greater or
equal” ;
//returns “second number is greater”

page 54 Core Java


Module 2
Variables and Operators

2.4.7 Bitwise and Bit Shift Operators

Concepts
Bitwise operators work on binary representations of data. These operators are used to change individual
bits in an operand. Bitwise shift operators are used to move all the bits in the operand left or right a given
number of times.

Table 2.11 lists the various bitwise operators.

Operator Description
Bitwise AND - compares two bits and generates a result of 1 if both bits are 1; otherwise,
it returns 0.
Bitwise OR - compares two bits and generates a result of 1 if the bits are complementary;
otherwise, it returns 0.
Exclusive OR - compares two bits and generates a result of 1 if either or both bits are 1;
otherwise, it returns 0.
Complement operator - used to invert all of the bits of the operand.
Shift Right operator - Moves all bits in a number to the right by one position retaining the
sign of negative numbers.
Shift Left operator - Moves all the bits in a number to the left by the specified position.

Table 2.11: Bitwise Operators

The following code demonstrates the bitwise operators.

Code Snippet:

int x = 23;
int y = 12;
//23 = 10111 , 12 = 01100
(x & y) // returns 4 , i.e, 4 = 00100
(x | y) //returns 31, i.e 31 = 11111
(x ^ y) //returns 27, i.e 31 = 11011
int a = 43;
int b = 1;
//43 = 010011 , 1 = 000001
(a >> b) // returns 21 , i.e, 21 = 0010101
(a << b) //returns 86 , i.e, 86 = 1010110

Core Java page 55


Module 2
Variables and Operators

2.4.8 Operator Precedence


Concepts

Expressions that are written generally consist of several operators. The rules of precedence decide the
order in which each operator is evaluated in any given expression.

Table 2.12 shows the order of precedence of operators, from highest to lowest in which operators are
evaluated in Java.

Order Operator
Parentheses like ( ).
Unary Operators like +, -, ++, --, ~, !.
Arithmetic and Bitwise Shift operators like *, /, %, +, -, >>, <<.
Relational Operators like >, >=, <, <=, ==, !=.
Conditional and Bitwise Operators like &, ^, |, &&, ||.
Conditional and Assignment Operators like ?:, =, *=, /=, +=,
and -=.

Table 2.12: Precedence of Operators

Parentheses are used to change the order in which an expression is evaluated. Any part of an
expression enclosed in parentheses is evaluated first.

The following code demonstrates the precedence of operators in an expression.

Code Snippet:

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

The evaluation is as shown:

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

First the arithmetic operators are evaluated.

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

Division and Multiplication are evaluated before addition and subtraction.

(6+2) >3 && 3<5 || 10<9

(8 >3) && [3<5] || [10<9]

page 56 Core Java


Module 2
Variables and Operators

Next to be evaluated are the relational operators all of which have the same precedence. These
are therefore evaluated from left to right.

Concepts
(True && True) || False

The last to be evaluated are the logical operators. && takes precedence over ||.

True || False

True

2.4.9 Operator Associativity

When two operators with the same precedence appear in an expression, the expression 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).

Table 2.13 shows the Java operators and their associativity.

Operator Description Associativity


(), ++, -- Parentheses, post increment/decrement Left to right
++, --, +, -, !,~ Pre increment/ decrement unary plus, Right to left
unary minus logical NOT, bitwise NOT
*, /, %, +, - Multiplicative and Additive Left to right
<<, >> Bitwise shift Left to right
<, <, >=, <=, ==, != Relational and Equality operators Left to right
&, ^, | Bitwise AND, XOR, OR Left to right
&&, || Conditional AND, OR Left to right
?: Conditional operator (Ternary) Right to left
=, +=, -=, *=, /=, %=, &=, ^=, |=, <<=, >>= Assignment Right to left

Table 2.13: Java Operators and their Associativity

Core Java page 57


Module 2
Variables and Operators

The following code demonstrates the associativity of operators in an expression.


Concepts

Code Snippet:

Consider the following expression:

2+10+4-5*(7-1)

According to the rules of operator precedence, the ‘*’ has higher precedence than any other
operator in the equation. Since 7-1 is enclosed in parenthesis, it is evaluated first.

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+10+4-30

As ‘+’ and ‘-‘ have the same precedence, the left associativity works out.

12+4-30

Finally, the expression is evaluated from left to right.

16 – 30

The result is -14.

Knowledge Check 4

Can you match the operators in Java against their corresponding description?

Description Operator
(A) Works on boolean expressions (1) Relational
(B) Requires only one operand (2) Arithmetic
(C) Assigns values to identifiers (3) Conditional
(D) Tests the relationship between two operands (4) Assignment
(E) Requires two operands to operate (5) Unary

page 58 Core Java


Module 2
Variables and Operators

You are using various operators to solve an expression. Which of the following statements will
display the output as “true”?

Concepts
int a = 5, b = 4, c = 3,d = 2, e = 1;
System.out.println((a+b/5.0-c*d+1*e > (a*b)) && (b<d));
int a = 5, b = 4, c = 3,d = 2, e = 1;
System.out.println((a*b/5.0+c*d+1*e > (a/b)) && (b>d));
int a = 5, b = 4, c = 3,d = 2, e = 1;
System.out.println((a*b+5.0-c*d+1*e < (a*b)) && (b>d));
int a = 5, b = 4, c = 3,d = 2, e = 1;
System.out.println((a*b/5.0-c*d*1*e > (a*b)) && (b<d));

2.5 Type Casting

In this last lesson, Type Casting, you will learn to:

State the two types of type casting.



Describe implicit type casting.

Describe explicit type casting.

2.5.1 Type Casting

In any application, there may be situations where one data type may need to be converted into another
data type. The type casting feature in Java helps in such conversion. Type conversion or typecasting
refers to changing an entity of one data type into another. This is done to take advantage of certain
features of type hierarchies. For instance, values from a more limited set, such as integers, can be stored
in a more compact format. It can be converted later to a different format enabling operations not
previously possible, such as division with several decimal places worth of accuracy. In object-oriented
programming languages, type conversion allows programs to treat objects of one type as one of their
ancestor types to simplify interacting with them.

If a conversion results in the loss of precision, as in an int value converted to a short, then the compiler
issues an error message unless an explicit cast is made.

The two types of casting are as follows:

Implicit casting

Explicit casting

Core Java page 59


Module 2
Variables and Operators

Figure 2.2 shows the two types of casting.


Concepts

Figure 2.2: Type Casting

2.5.2 Implicit Type Casting

When one type of data is assigned to a variable of another type, then automatic type conversion takes
place, 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.

The primitive numeric data types that can be implicitly cast are as follows:

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.

page 60 Core Java


Module 2
Variables and Operators

Figure 2.3 shows the implicit type casting.

Concepts
Figure 2.3: Implicit Type Casting

The following code demonstrates implicit type conversion.

Code Snippet:

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

Note: The type promotion rules are listed as follows:

All byte and short values are promoted to int type.



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

Core Java page 61


Module 2
Variables and Operators

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


Concepts


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

2.5.3 Explicit Type Casting

A data type with lower precision, such as 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. Otherwise, the compiler will
display an error message.

The following code adds a float value to an int and stores the result as an integer.

Code Snippet:

float a = 21.3476f;
int b = (int) a + 5;

The float value in a variable 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.

Figure 2.4 shows the explicit type casting of data types.

Figure 2.4: Explicit Type Casting

page 62 Core Java


Module 2
Variables and Operators

There are several kinds of explicit conversions. They are as follows:

Concepts
checked

Before the conversion is performed, a runtime check is done to see if the destination type can
hold the source value. If not, an error condition is raised.

unchecked

No check is performed. If the destination type cannot hold the source value, the result is
undefined.

bit pattern

The data is not interpreted at all, and its raw bit representation is copied verbatim. This can also
be achieved via aliasing.

Knowledge Check 5

You want the output to be displayed as, ‘floatTest=1.0’, ‘dblTest=1.0’, and ‘sum=2’. Can
you arrange the steps in sequence to achieve the same?

System.out.println(“dblTest=” + dblTest);
int sum = (int)(dblTest + floatTest);
System.out.println(“sum=” + sum);
boolean boolTest = true;
float floatTest = 3.14f;
System.out.println(“floatTest=” + floatTest);
dblTest = (double)( boolTest?1:0);
double dblTest = 0.000000000000053;

floatTest = (float)(boolTest?1:0);

Core Java page 63


Module 2
Variables and Operators

Module Summary
Concepts

In this module, Variables and Operators, you learnt about:

Variables

Variables store the values required in the program. Variables should be declared, before
they are used. Java programming language has its own set of rules and conventions for
naming variables.

Data Types

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. Primitive data types contain the actual value while reference data
types contain a reference to the actual value.

Formatted Output and Input

The printf() method along with the format specifiers can be used to format the output
displayed on the screen. Scanner class methods can be used to format the program input.
Java uses escape sequences to represent certain special character values.

Operators

Operators are symbols that help to manipulate or perform some sort of function on data.
The symbol used in the expression to perform an operation is called the operator. The
variables on which the operation is performed are called operands. The combination of both
the operator and the operand is known as an expression. Operators can be classified into
arithmetic, assignment, relational, bitwise, unary, and conditional.

Type Casting

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.

page 64 CoreJava

You might also like