CJ Unit 1
CJ Unit 1
JAVA
MODULE-1: Introduction and Data Types
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
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 first lesson, Classes and Objects, you will learn to:
Core Java
Module 1
Introduction to Java
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
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).
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.
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.
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
Core Java
Module 1
Introduction to Java
Concepts
Figure 1.3: Comparison of a Class and an Object
Knowledge Check 1
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
In this second lesson, Getting Started with Java, you will learn to:
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:
Core Java
Module 1
Introduction to Java
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:
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
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.
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
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.
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:
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.
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:
where,
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.
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
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.
In this fourth lesson, Writing a Java program, you will learn to:
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’.
class <class_name> {
}
where,
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 {
}
Syntax:
{ }
where,
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.
Core Java
Module 1
Introduction to Java
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.
Knowledge Check 4
Which of these statements about compiling and executing a Java program are true and which
statements are false?
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
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.
Let's see a scenario. If we don't implement Java lambda expression. Here, we are implementing an interface
method without using lambda expression.
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:
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.
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:
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
In this last lesson, Using Comments in Java, you will learn to:
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.
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).
30 Core Java
Module 1
Introduction to Java
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
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.
Core Java 31
Module 1
Introduction to Java
Code Snippet:
/*
This code performs mathematical
operation of adding two numbers.
*/
int a = 20;
int b = 30;
int c;
c = a + b;
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.
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?
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.
Concepts
Introduction to Variables
Introduction to Data Types
Formatted Output and Input
Operators
Type Casting
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.
Syntax:
datatype variableName;
where,
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’;
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:
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.
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).
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).
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.
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:
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:
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:
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.
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.
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?
Concepts
In this second lesson, Introduction to Data Types, you will learn to:
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:
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.
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;
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.
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.
Knowledge Check 2
Can you match the values which will optimally fit with the corresponding data type?
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:
Code Snippet:
//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:
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.
In this third lesson, Formatted Output and Input, you will learn to:
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.
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);
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.
The Scanner class allows the user to read values of various types. To use the Scanner class, pass the
InputStream object to the constructor.
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
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:
Output:
Note:
Package
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
InputStream
Concepts
Characters are read from the keyboard by using System.in.
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.
Code Snippet:
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:
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?
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?
2.4 Operators
Concepts
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.
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
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.
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.
Code Snippet:
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.
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
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
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.
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.
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.
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
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).
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.
Code Snippet:
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.
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.
Ternary operator (?:) is another type of conditional operator; it accepts three operands. The syntax for
the usage of ternary operator is as follows:
where,
Code Snippet:
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.
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.
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
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 -=.
Parentheses are used to change the order in which an expression is evaluated. Any part of an
expression enclosed in parentheses is evaluated first.
Code Snippet:
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
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).
Code Snippet:
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
16 – 30
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
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));
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.
Implicit casting
Explicit 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 primitive numeric data types that can be implicitly cast are as follows:
Concepts
Figure 2.3: Implicit Type Casting
Code Snippet:
If one operand is double then the whole expression is promoted to double.
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.
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);
Module Summary
Concepts
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