0% found this document useful (0 votes)
11 views32 pages

21OECS62 Module-1 Notes

The document provides an introduction to Java programming, covering its history, evolution, and fundamental concepts such as object-oriented programming principles, including encapsulation, inheritance, and polymorphism. It explains the significance of Java's platform independence through bytecode and the Java Virtual Machine (JVM), and details the structure of Java programs, including the compilation and execution process. Additionally, it presents simple Java program examples to illustrate basic syntax and functionality.

Uploaded by

Dhanya RS
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)
11 views32 pages

21OECS62 Module-1 Notes

The document provides an introduction to Java programming, covering its history, evolution, and fundamental concepts such as object-oriented programming principles, including encapsulation, inheritance, and polymorphism. It explains the significance of Java's platform independence through bytecode and the Java Virtual Machine (JVM), and details the structure of Java programs, including the compilation and execution process. Additionally, it presents simple Java program examples to illustrate basic syntax and functionality.

Uploaded by

Dhanya RS
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/ 32

Introduction to Java Programming - Module-1

Basic concepts of Java


The History and Evolution of java

Computer language innovation and development occurs for two fundamental reasons:

 To adapt to changing environments and uses

 To implement refinements and improvements in the art of programming

The development of Java was driven by both elements in nearly equal measure.

Java is related to C++, which is a direct derivative of C. much of the properties of java is
inherited from these two languages.

 From C, java derives its syntax.

 From C++, java derives object-oriented features.

Java programming language was introduced by James Gosling, Patrick Naughton, Chris
Warth and Ed Frank at Sun Microsystems in 1991. It took eighteen months to develop the
working version. This language was initially called „OAK‟ but was renamed as „Java‟ in
1995. Bill Joy, Arthur van Hoff, Jonathan Payne, Frank Yellin, and Tim Lindholm were key
contributors to the maturing of the original prototype.

The original impetus for Java was not the Internet! Instead, the primary motivation was
the need for a platform-independent (that is, architecture-neutral) language that could be
used to create software to be embedded in various consumer electronic devices, such as
microwave ovens and remote controls.

The trouble with C and C++ is that they are designed to be compiled for a specific target.
Although it is possible to compile a C++ program for just about any type of CPU, to do so
requires a full C++ compiler targeted for that CPU. The problem is that compilers are
expensive and time-consuming to create. An easier—and more cost-efficient—solution was
needed. In an attempt to find such a solution, Gosling and others began work on a portable,
platform-independent language that could be used to produce code that would run on a
variety of CPUs under differing environments. This effort ultimately led to the creation of
Java.

Important factor that played a crucial role in the development of Java was, of course, the
World Wide Web.

The creation of the applet changed Internet programming because it expanded the universe
of objects that can move about freely in cyberspace. Every time you download a “normal”
program, you are taking a risk, because the code you are downloading might contain a
virus, Trojan horse, or other harmful code. At the core of the problem is the fact that
malicious code can cause its damage because it has gained unauthorized access to system
resources. Java achieved this protection by confining an applet to the Java execution
environment and not allowing it access to other parts of the computer.

Java’s Magic: The Bytecode: The key that allows Java to solve both the security and the
portability problems is that the output of a Java compiler is not executable code. Rather, it
is bytecode. Bytecode is a highly optimized set of instructions designed to be executed by
the Java run-time system, which is called the Java Virtual Machine (JVM).

Shobha Chandra K, Asst Professor, CSE, MCE Page 1


Introduction to Java Programming - Module-1
Translating a Java program into bytecode makes it much easier to run a program in a wide
variety of environments because only the JVM needs to be implemented for each platform.
Once the run-time package exists for a given system, any Java program can run on it.

The JVM is the Java run-time system and is the main component of making the java a
platform independent language. For building and running a java application we need
JDK(Java Development Kit) which comes bundled with Java runtime environment(JRE) and
JVM. With the help of JDK the user compiles and runs his java program. As the compilation
of java program starts the Java Bytecode is created i.e. a .class file is created by JRE.
Bytecode is a highly optimized set of instructions designed to be executed by JVM. Now the
JVM comes into play, which is made to read and execute this bytecode. The JVM is linked
with operating system and runs the bytecode to execute the code depending upon operating
system. Therefore, a user can take this class file(Bytecode file) formed to any operating
systemwhich is having a JVM installed and can run his program easily without even touching
the syntax of a program and without actually having the source code. The .class file which
consists of bytecode is not user-understandable and can be interpreted by JVM only to build
it into the machine code.

Usually, when a program is compiled to an intermediate form and then interpreted by a


virtual machine, it runs slower than it would run if compiled to executable code. To improve
the performance, Java provides a Just-in-time (JIT) compiler for bytecode. JIT compilers
alter the role of the JVM a little by directly compiling Java bytecode into native platform
code, thereby relieving the JVM of its need to manually call underlying native system
services. When JIT compiler is installed, instead of the JVM calling the underlying native
operating system, it calls the JIT compiler. The JIT compiler in turn generates native code
that can be passed on to the native operating system for execution. This makes the java
program torun faster than expected.

Object-Oriented Programming (OOP)

Two Paradigms of Programming:

Every program contains 2 components code and data.

Two approaches are there to solve the problem and in program writing: Procedure oriented
and object oriented.

Procedure Oriented(Process oriented):

 This approach characterizes a program as a series of linear steps

 Procedure oriented programs are written based on “what’s happening” around,


where the code acts on data. Ex: C etc

 Problems increases in procedure oriented as the program grows larger and more
complex.

Object Oriented:

 Object oriented programs are written based on “Who is being affected” around,
which manages the increasing complexity.

Shobha Chandra K, Asst Professor, CSE, MCE Page 2


Introduction to Java Programming - Module-1
 It organises program around data and well defined interfaces of that data.

 Characterised as data controlling access to code. Ex: C++, JAVA, Small Talk etc

Abstraction

An essential element of object-oriented programming is abstraction. Abstraction in Java is


the process in which we only show essential details/functionality to the user. The non-
essential implementation details are not displayed to the user. (Hiding the implementation
details and showing only functionality to the user)

Abstraction Real-Life Example:

Consider a real-life example of a man driving a car. The man only knows that pressing the
accelerators will increase the speed of a car or applying brakes will stop the car, but he does
not know how on pressing the accelerator the speed is actually increasing, he does not know
about the inner mechanism of the car or the implementation of the accelerator, brakes, etc
in the car. This is what abstraction is.

The Three OOP Principles


The three important features of OOP are:

 Encapsulation

 Inheritence

 Polymorphism

Objects and Classes in Java

An object in Java is the physical as well as a logical entity, whereas, a class in Java is a
logical entity only.

An entity that has state and behavior is known as an object e.g., chair, bike, marker, pen,
table, car, etc. It can be physical or logical

An object has three characteristics:

o State: represents the data (value) of an object.

o Behavior: represents the behavior (functionality) of an object such as deposit,


withdraw, etc.

o Identity: An object identity is typically implemented via a unique ID. The value of
the ID is not visible to the external user. However, it is used internally by the JVM to
identify each object uniquely.

For Example, Pen is an object. Its name is Reynolds; color is white, known as its state. It
is used to write, so writing is its behavior.

A class is a group of objects which have common properties. It is a template or blueprint


from which objects are created. It is a logical entity. It can't be physical.

A class in Java can contain:

Shobha Chandra K, Asst Professor, CSE, MCE Page 3


Introduction to Java Programming - Module-1
o Fields

o Methods

o Constructors

o Blocks

o Nested class and interface

Encapsulation

Encapsulation is the mechanism to bind the data and code working on that data into
a single entity. It provides the security for the data by avoiding outside manipulations. In
Java, encapsulation is achieved using classes.

 A class is a collection of data and code.

 An object is an instance of a class.

 That is, several objects share a common structure (data) and behavior (code) defined
by that class.

 A class is a logical entity (or prototype) and an object is a physical entity.

 The elements inside the class are known as members.

 Specifically, the data or variables inside the class are called as member variables or
instance variables or data members.

 The code that operates on these data is referred to as member methods or methods
(In C++, we term this as member function).

 The method operating on data will define the behavior and interface of a class.

Another purpose of the class is to hide the information from outside manipulation. Class
uses public and private interfaces. The members declared as private can only be accessed
by the members of that class, whereas, the public members can be accessed from outside
the class.

Inheritance

Inheritance allows us to have code re-usability.

It is a process by which one object can acquire the properties of another object. It supports
the concept of hierarchical classification.

For example, consider a large group of animals having few of the abstract attributes like
size, intelligence, skeletal structure etc. and having behavioral aspects like eating, breathing
etc. Mammals have all the properties of Animals and also have their own specific features
like type of teeth, mammary glands etc. that make them different from Reptiles.

Similarly, Cats and Dogs have all the characteristics of mammals, yet with few features
which are unique for themselves. Though Doberman, German-shepherd, Labrador etc. have
the features of Dog class, they have their own unique individuality. This concept can be
depicted using following figure

Shobha Chandra K, Asst Professor, CSE, MCE Page 4


Introduction to Java Programming - Module-1

Figure 1.1 Example of Inheritance

If we apply the above concept for programming, it can be easily understood that a code
written is reusable. Thus, in this mechanism, it is possible for one object to be a specific
instance of a more general case. Using inheritance, an object need only define those
qualities that make it a unique object within its class. It can inherit its general attributes
from its parent. Hence, through inheritance, we can achieve generalization specialization
concept. The top-most parent (or base class or super class) class is the generalized class
and the bottom-most child (or derived class or subclass) class is a more specialized class
with specific characteristics.

Inheritance interacts with encapsulation as well. If a given class encapsulates some


attributes, then any subclass will have the same attributes plus any that it adds as part of
its specialization. This is a key concept that lets object-oriented programs grow in
complexity linearly rather than geometrically. A new subclass inherits all of the attributes of
all of its ancestors. It does not have unpredictable interactions with the majority of the rest
of the code in the system

Polymorphism

Polymorphism (from Greek, meaning “many forms”) is a feature that allows one interface to
be used for a general class of actions. The specific action is determined by the exact nature
of the situation.

Example: A person acts as an employee at work, a father at home, and a customer in


shopping malls.

Polymorphism in Java Example

A superclass named “Shapes” has a method called “area()”. Subclasses of “Shapes” can be
“Triangle”, “circle”, “Rectangle”, etc. Each subclass has its way of calculating area. Using
Inheritance and Polymorphism means, the subclasses can use the “area()” method to find
the area’s formula for that shape.

Polymorphism, Encapsulation and Inheritence work Together

 The 3 principles of OOP Polymorphism, Encapsulation and Inheritence combines


together to make the programming robust and scalable.

 Encapsulation allows to migrate the implementation without disturbing the code that
depends on class.

 Polymorphism allows to create clean, sensible, readable, resilient code.

Shobha Chandra K, Asst Professor, CSE, MCE Page 5


Introduction to Java Programming - Module-1
 Inheritence mainly deals with the code reusability

A First Simple Program


/* This is a simple Java program. Call this file "Example.java". */

class Example {

// Your program begins with a call to main().

public static void main(String args[]) {

System.out.println("This is a simple Java program.");

Entering the Program

In Java, a source file is officially called a compilation unit. It is a text file that contains
one or more class definitions. The Java compiler requires that a source file use the .java
filename extension.

In Java, all code must reside inside a class. By convention, the name of the main class
should match the name of the file that holds the program.

Compiling the Program

To compile the Example program, execute the compiler, javac, specifying the name of the
source file on the command line, as shown here:

C:\>javac Example.java

The javac compiler creates a file called Example.class that contains the bytecode version of
the program.

To actually run the program, you must use the Java application launcher called java. To do
so, pass the class name Example as a command-line argument, as shown here:

C:\>java Example

When the program is run, the following output is displayed:

This is a simple Java program.

A Closer Look at the First Sample Program

Refer Text book

/*

This is a simple Java program.

Call this file "Example.java".

Shobha Chandra K, Asst Professor, CSE, MCE Page 6


Introduction to Java Programming - Module-1
*/

This is a comment. Like most other programming languages, Java lets you enter a
remark into a program’s source file. The contents of a comment are ignored by the
compiler.

class Example { This line uses the keyword class to declare that a new class is being
defined. Example is an identifier that is the name of the class. The entire class
definition, including all of its members, will be between the opening curly brace ({)
and the closing curly brace (}).

The next line in the program is the single-line comment, shown here:

// Your program begins with a call to main().


The next line of code is shown here:

public static void main(String args[ ]) {

 This line begins the main( ) method. This is the line at which the program will
begin executing. All Java applications begin execution by calling main( ).

 The public keyword is an access modifier, which allows the programmer to


control the visibility of class members.

 When a class member is preceded by public, then that member may be


accessed by code outside the class in which it is declared.

 The opposite of public is private, which prevents a member from being used
by code defined outside of its class.

 In this case, main( ) must be declared as public, since it must be called by


code outside of its class when the program is started.

 The keyword static allows main( ) to be called without having to instantiate a


particular instance of the class. This is necessary since main( ) is called by the
Java Virtual Machine before any objects are made.

 The keyword void simply tells the compiler that main( ) does not return a
value

In main( ), there is only one parameter, String args[ ]. It declares a parameter


named args, which is an array of instances of the class String.

args receives any command-line arguments present when the program is executed

System.out.println("This is a simple Java program.");

The line begins with System.out.

 System is a predefined class that provides access to the system

 out is the output stream that is connected to the console

Shobha Chandra K, Asst Professor, CSE, MCE Page 7


Introduction to Java Programming - Module-1
 Output is actually accomplished by the built-in println( ) method

A Second Short Program


/*

Call this file "Example2.java".

*/

class Example2 {

public static void main(String args []) {

int num; // this declares a variable called num

num = 100; // this assigns num the value 100

System.out.println("This is num: " + num);

num = num * 2;

System.out.print("The value of num * 2 is ");

System.out.println(num);

When you run this program, you will see the following output:

This is num: 100

The value of num * 2 is 200

Shobha Chandra K, Asst Professor, CSE, MCE Page 8


Introduction to Java Programming - Module-1

The Java Buzzwords

There are many important fatures of java, they are also known as „Java buzzwords‟.

1. Simple

2. Object-Oriented

3. Portable

4. Platform independent

5. Secured

6. Robust

7. Architectureneutral

8. Dynamic

9. Interpreted

10. HighPerformance

11. Multithreaded

12. Distributed

Simple : According to Sun Microsystems, Java language is simple because syntax is based
on C++ (easier to learn after C++) and removed many confusing features such as explicit
pointers, operator overloading etc and no need to remove unreferenced objects because
there is automatic garbage collection in java.

Object-oriented : Object-oriented programming (OOPS) is a methodology that simplify


software development and maintaince by providing some basic rules of OOPS such as

 Objects

 Class

 Inheritance

 Polymorphism

 Abstraction

 Encapsulation

Platform independent: A platform is the hardware and software environment in which a


program runs. There are two types of platforms : “Software-based‟ and „Hardware based‟.
Java provides software-based platform.

Shobha Chandra K, Asst Professor, CSE, MCE Page 9


Introduction to Java Programming - Module-1
The java platform differs from most other platforms in the sense that it‟s a software based
platform that runs on top of other hardware-based platforms and it has two components.

 Runtime environment

 Application programming interface (API)

Java code can be run on multiple platforms such as Windows, Solaris, Linux, Mac/OS etc.
Java code is compiled by the compiler and converted into „byte code‟. The byte code is a
platform independent code because it can be run on multiple platform i.e „Write once and
run anywhere (WORA)‟.

Secured: Java is secured because “No explicit pointer” and “Program run inside virtual
machine sandbox‟. It is composed of the following:

 Class loader: Adds security by separating the package for classes of local file system
from those that are imported from network sources.

 Byte verifier: Checks the code fragments for illegal code that can violate access
rights to objects.

 Security manager: Determines what resources a class can access such as reading
and writing to local disk.

These securities are provided by java language.

Robust: Robust simply means its strong. Java uses strong memory management. There are
“lack of pointers‟ that avoids security problem. There is “Automatic garbage collection‟ in
Java. There is “Exception handling‟ and “Type checking‟ mechanisms in java.

All these points make java robust.

Architectural neutral: There is no implementation dependent features. Operating system


upgrades, processor upgrades, and changes in core system resources can all combine to
make a program malfunction. The Java designers made several hard decisions in the Java
language and the Java Virtual Machine in an attempt to alter this situation. Their goal was
“write once; run anywhere, anytime, forever.” To a great extent, this goal was
accomplished.

Portable: We may carry the java byte code to any platforms.

High performance: Java is faster than traditional interpretation since byte code is close to
native code.

Distributed: We can create distributed applications in java. RMI and EJB are used for
creating distributed applications. We may access files by calling the methods from any
machine on internet.

Multi-threaded: A thread is like a separate program executing concurrently. We can write


java programs that deal with many tasks at once by defining multiple threads. The main
advantage of multi-threading is that it shares the same memory. Threads are important for
multimedia, web applications etc.

The Evolution of Java

Shobha Chandra K, Asst Professor, CSE, MCE Page 10


Introduction to Java Programming - Module-1
There are many java versions that has been released. Current release of Java is Java SE
22.0.1.

1. JDK Alpha and Beta (1995)

2. JDK 1.0 (23rd Jan, 1996)

3. JDK 1.1 (19th Feb, 1997)

4. J2SE 1.2 (8th Dec, 1998)

5. J2SE 1.3 (8th May, 2000)

6. J2SE 1.4 (6th Feb, 2002)

7. J2SE 5.0 (30th Sep,2004)

8. Java SE 6 (11th Dec,2006)

9. Java SE 7 (28th July, 2011)

10.Java SE 8 (18th March,2014)

Soon after the release of Java 1.0, the designers of Java had already created Java 1.1

Java 1.1 added many new library elements, redefined the way events are handled, and
reconfigured many features of the 1.0 library. It also deprecated (rendered obsolete)
several features originally defined by Java 1.0.

The next major release of Java was Java 2, where the “2” indicates “second generation.”
The first release of Java 2 carried the version number 1.2. With Java 2, Sun repackaged the
Java product as J2SE (Java 2 Platform Standard Edition). Java 2 added support for a
number of new features, such as Swing and the Collections Framework, and it enhanced the
Java Virtual Machine and various programming tools.

J2SE 1.3 was the first major upgrade to the original Java 2 release. For the most part, it
added to existing functionality and “tightened up” the development environment

The release of J2SE 1.4 further enhanced Java. This release contained several important
upgrades, enhancements, and additions. For example, it added the new keyword assert,
chained exceptions, and a channel-based I/O subsystem. It also made changes to the
Collections Framework and the networking classes

The next release of Java was J2SE 1.5. list of its major new features:

 Generics

 Annotations

 Autoboxing and auto-unboxing

 Enumerations

 Enhanced, for-each style for loop

 Variable-length arguments (varargs)

Shobha Chandra K, Asst Professor, CSE, MCE Page 11


Introduction to Java Programming - Module-1
 Static import

 Formatted I/O

 Concurrency utilities

The next release of Java was called Java SE 6. The Java Development Kit was called JDK 6.
The internal, developer version number is 1.6. Java SE 6 added no major features to the
Java language proper, but it did enhance the API libraries, added several new packages, and
offered improvements to the runtime.

Java SE 7 was the next release of Java, with the Java Development Kit being called JDK 7,
and an internal version number of 1.7. Java SE 7 was the first major release of Java since
Sun Microsystems was acquired by Oracle. Java SE 7 contained many new features,
including significant additions to the language and the API libraries. Upgrades to the Java
run-time system that support non-Java languages were also included.

List of the language features added by JDK 7:

• A String can now control a switch statement.

• Binary integer literals.

• Underscores in numeric literals.

• An expanded try statement, called try-with-resources, that supports automatic resource


management. (For example, streams can be closed automatically when they are no longer
needed.)

• Type inference (via the diamond operator) when constructing a generic instance.

• Enhanced exception handling in which two or more exceptions can be caught by a single
catch (multi-catch) and better type checking for exceptions that are rethrown.

• Although not a syntax change, the compiler warnings associated with some types of
varargs methods were improved, and you have more control over the warnings.

JDK 8 represents a very significant upgrade to the Java language because of the inclusion of
a far-reaching new language feature: the lambda expression.

Lexical Issues
Java programs are a collection of whitespace, identifiers, literals, comments, operators,
separators, and keywords

Whitespace

Java is a free-form language. This means that you do not need to follow any special
indentation rules. For instance, the Example program could have been written all on one line
or in any other strange way you felt like typing it, as long as there was at least one
whitespace character between each token that was not already delineated by an operator or
separator. In Java, whitespace is a space, tab, or newline.

Identifiers

Shobha Chandra K, Asst Professor, CSE, MCE Page 12


Introduction to Java Programming - Module-1
Identifiers are used to name things, such as classes, variables, and methods. An identifier
may be any descriptive sequence of uppercase and lowercase letters, numbers, or the
underscore and dollar-sign characters. (The dollar-sign character is not intended for general
use.) Java is case-sensitive, so VALUE is a different identifier than Value. Some examples of
valid identifiers are Avg, Temp, count, a4, $test, this_is_ok

Literals

A constant value in Java is created by using a literal representation of it. For example, here
are some literals:

100 98.6 ‘X’ “This is a test”

Comments

There are three types of comments defined by Java.

Single-line ( // This is Comment )

Multiline ( /* This is Comment */)

The third type is called a documentation comment. This type of comment is used to produce
an HTML file that documents your program. (documentation comment begins with a /** and
ends with a */).

Separators
The most commonly used separator in Java is the semicolon.

The Java Keywords

Shobha Chandra K, Asst Professor, CSE, MCE Page 13


Introduction to Java Programming - Module-1

Data Types
Data types represent the different values to be stored in the variable. In java, there are two
types of data types:

 Primitive datatypes

 Non-primitive datatypes

The Primitive Types

Java defines eight primitive types of data: byte, short, int, long, char, float, double, and
boolean.

These can be put in four groups:

Integers This group includes byte, short, int, and long, which are for whole-valued signed
numbers.

Floating-point numbers This group includes float and double, which represent numbers
with fractional precision.

Characters This group includes char, which represents symbols in a character set, like
letters and numbers.

Shobha Chandra K, Asst Professor, CSE, MCE Page 14


Introduction to Java Programming - Module-1
Boolean This group includes boolean, which is a special type for representing true/false
values

Integers
Java defines four integer types: byte, short, int, and long. All of these are signed, positive
and negative values. Java does not support unsigned, positive-only
integers.

byte
The smallest integer type is byte. This is a signed 8-bit type that has a range from –128 to
127. Variables of type byte are especially useful when you’re working with a stream of data
from a network or file. They are also useful when you’re working with raw binary data that
may not be directly compatible with Java’s other built-in types.

Byte variables are declared by use of the byte keyword. For example, the following declares
two byte variables called b and c:

byte b, c;

short
short is a signed 16-bit type. It has a range from –32,768 to 32,767. It is probably the least
used Java type. Here are some examples of short variable declarations:

short s;

short t;

int
The most commonly used integer type is int. It is a signed 32-bit type that has a range from
–2,147,483,648 to 2,147,483,647

long
long is a signed 64-bit type and is useful for those occasions where an int type is not large
enough to hold the desired value. The range of a long is quite large. This makes it useful
when big, whole numbers are needed. For example, here is a program that computes the
number of miles that light will travel in a specified number of days:

// Compute distance light travels using long variables.

class Light {

public static void main(String args[]) {


Shobha Chandra K, Asst Professor, CSE, MCE Page 15
Introduction to Java Programming - Module-1
int lightspeed;

long days;

long seconds;

long distance;

// approximate speed of light in miles per second

lightspeed = 186000;

days = 1000; // specify number of days here

seconds = days * 24 * 60 * 60; // convert to seconds

distance = lightspeed * seconds; // compute distance

System.out.print("In " + days);

System.out.print(" days light will travel about ");

System.out.println(distance + " miles.");

This program generates the following output:

In 1000 days light will travel about 16070400000000 miles.

Floating-point numbers This group includes float and double, which represent numbers
with fractional precision.

// Compute the area of a circle.

import java.util.Scanner;

class Area {

public static void main(String args[]) {

double pi, r, a;

Scanner input= new Scanner(System.in);

pi = 3.1416; // pi, approximately

System.out.println("Enter radius ");

r=input.nextDouble();

a = pi * r * r; // compute area

System.out.println("Area of circle is " + a);

Shobha Chandra K, Asst Professor, CSE, MCE Page 16


Introduction to Java Programming - Module-1
}

O/P:

Enter radius 10.8

Area of circle is 366.436224

Characters This group includes char, which represents symbols in a character set, like
letters and numbers.

In Java char is a 16-bit type. The range of a char is 0 to 65,535. There are no negative
chars.

// Character variables can be handled like integers.

class CharArithDemo {

public static void main(String[] args) {

char ch;

ch = 'X';

System.out.println("ch contains " + ch);

ch++; // increment ch

System.out.println("ch is now " + ch);

ch = 90; // give ch the value Z

System.out.println("ch is now " + ch);

O/P:

ch contains X

ch is now Y

ch is now Z

Boolean This group includes boolean, which is a special type for representing true/false
values.

// Demonstrate boolean values.

class BoolDemo {

public static void main(String[] args) {

Shobha Chandra K, Asst Professor, CSE, MCE Page 17


Introduction to Java Programming - Module-1
boolean b;

b = false;

System.out.println("b is " + b);

b = true;

System.out.println("b is " + b);

// a boolean value can control the if statement

if(b) System.out.println("This is executed.");

b = false;

if(b) System.out.println("This is not executed.");

// outcome of a relational operator is a boolean value

System.out.println("10 > 9 is " + (10 > 9));

O/P:

b is false b is true

This is executed.

10 > 9 is true

Variables
The variable is the basic unit of storage in a Java program. A variable is defined by the
combination of an identifier, a type, and an optional initializer. In addition, all variables have
a scope, which defines their visibility, and a lifetime.

Declaring a Variable

In Java, all variables must be declared before they can be used. The basic form of a variable
declaration is shown here:

type identifier [ = value ][, identifier [= value ] …];

type is one of Java’s atomic types

The identifier is the name of the variable.

int a, b, c; // declares three ints, a, b, and c.

int d = 3, e, f = 5; // declares three more ints, initializing

// d and f.

Shobha Chandra K, Asst Professor, CSE, MCE Page 18


Introduction to Java Programming - Module-1
byte z = 22; // initializes z.

double pi = 3.14159; // declares an approximation of pi.

char x = 'x'; // the variable x has the value 'x'.

Dynamic Initialization
Java allows variables to be initialized dynamically, using any expression valid at the time the
variable is declared.

// Demonstrate dynamic initialization.

class DynInit {

public static void main(String args[]) {

double a = 3.0, b = 4.0;

// c is dynamically initialized

double c = Math.sqrt(a * a + b * b);

System.out.println("Hypotenuse is " + c);

The Scope and Lifetime of Variables


The scope of a variable defines the section of the code in which the variable is visible. As a
general rule, variables that are defined within a block are not accessible outside that block.
The lifetime of a variable refers to how long the variable exists before it is destroyed.
Destroying variables refers to deallocating the memory that was allotted to the variables
when declaring it. There are three types of variables: instance variables, formal parameters
or argument variables and local variables.

Instance variables

Instance variables are those that are defined within a class itself and not in any method or
constructor of the class. They are known as instance variables because every instance of the
class (object) contains a copy of these variables. The scope of instance variables is
determined by the access specifier that is applied to these variables. The lifetime of these
variables is the same as the lifetime of the object to which it belongs. Object once created
do not exist for ever. They are destroyed by the garbage collector of Java when there are no
more reference to that object.

Argument variables

These are the variables that are defined in the header of constructor or a method. The
scope of these variables is the method or constructor in which they are defined. The lifetime
is limited to the time for which the method keeps executing. Once the method finishes
execution, these variables are destroyed.

Local variables
Shobha Chandra K, Asst Professor, CSE, MCE Page 19
Introduction to Java Programming - Module-1
A local variable is the one that is declared within a method or a constructor (not in the
header). The scope and lifetime are limited to the method itself.

One important distinction between these three types of variables is that access specifiers
can be applied to instance variables only and not to argument or local variables.

In addition to the local variables defined in a method, we also have variables that are
defined in bocks life an if block and an else block. The scope and is the same as that of the
block itself.

Shobha Chandra K, Asst Professor, CSE, MCE Page 20


Introduction to Java Programming - Module-1
Arithmetic Operators

Arithmetic operators are used in mathematical expressions in the same way that they are

used in algebra. The following table lists the arithmetic operators:

The Basic Arithmetic Operators

// Demonstrate the basic arithmetic operators.

class BasicMath {

public static void main(String args[]) {

// arithmetic using integers

System.out.println("Integer Arithmetic");

int a = 1 + 1;

int b = a * 3;

int c = b / 4;

int d = c - a;

int e = -d;

System.out.println("a = " + a);

System.out.println("b = " + b);

System.out.println("c = " + c);

System.out.println("d = " + d);

System.out.println("e = " + e);

// arithmetic using doubles

Shobha Chandra K, Asst Professor, CSE, MCE Page 21


Introduction to Java Programming - Module-1
System.out.println("\nFloating Point Arithmetic");

double da = 1 + 1;

double db = da * 3;

double dc = db / 4;

double dd = dc - a;

double de = -dd;

System.out.println("da = " + da);

System.out.println("db = " + db);

System.out.println("dc = " + dc);

System.out.println("dd = " + dd);

System.out.println("de = " + de);

When you run this program, you will see the following output:

Integer Arithmetic

a=2
b=6
c=1
d = -1
e=1
Floating Point Arithmetic

da = 2.0
db = 6.0
dc = 1.5
dd = -0.5
de = 0.5
The Modulus Operator

The modulus operator, %, returns the remainder of a division operation. It can be applied to
floating-point types as well as integer types. The following example program demonstrates
the %:

// Demonstrate the % operator.

class Modulus {

public static void main(String args[]) {

int x = 42;

double y = 42.25;
Shobha Chandra K, Asst Professor, CSE, MCE Page 22
Introduction to Java Programming - Module-1
System.out.println("x mod 10 = " + x % 10);

System.out.println("y mod 10 = " + y % 10);

When you run this program, you will get the following output:

x mod 10 = 2

y mod 10 = 2.25

Arithmetic Compound Assignment Operators

a = a + 4;

In Java, you can rewrite this statement as shown here:

a += 4;

This version uses the += compound assignment operator. Both statements perform the
same action: they increase the value of a by 4.

Thus, any statement of the form

var = var op expression;

can be rewritten as

var op= expression;

// Demonstrate several assignment operators.

class OpEquals {

public static void main(String args[]) {

int a = 1;

int b = 2;

int c = 3;

a += 5;

b *= 4;

c += a * b;

c %= 6;

System.out.println("a = " + a);

System.out.println("b = " + b);

Shobha Chandra K, Asst Professor, CSE, MCE Page 23


Introduction to Java Programming - Module-1
System.out.println("c = " + c);

The output of this program is shown here:

a=6

b=8

c=3

Increment and Decrement

The ++ and the – – are Java’s increment and decrement operators.

The increment operator increases its operand by one. The decrement operator decreases its
operand by one.

x = x + 1;

can be rewritten like this by use of the increment operator:

x++;

Similarly, this statement:

x = x - 1;

is equivalent to

x--;

These operators are unique in that they can appear both in postfix form, where they follow
the operand, and prefix form, where they precede the operand.

In the prefix form, the operand is incremented or decremented before the value is obtained
for use in the expression. In postfix form, the previous value is obtained for use in the
expression, and then the operand is modified. For example:

x = 42;
y = ++x;

In this case, y is set to 43 as you would expect, because the increment occurs before x is
assigned to y. Thus, the line y = ++x; is the equivalent of these two statements:

x = x + 1;
y = x;
However, when written like this,

x = 42;
y = x++;
the value of x is obtained before the increment operator is executed, so the value of y is 42.

Shobha Chandra K, Asst Professor, CSE, MCE Page 24


Introduction to Java Programming - Module-1
Of course, in both cases x is set to 43. Here, the line y = x++; is the equivalent of these
two statements:

y = x;
x = x + 1;
The following program demonstrates the increment operator.

// Demonstrate ++.

class IncDec {
public static void main(String args[]) {
int a = 1;
int b = 2;
int c;
int d;
c = ++b;
d = a++;
c++;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}
The output of this program follows:
a=2
b=3
c=4
d=1
The Bitwise Operators
Java defines several bitwise operators that can be applied to the integer types: long, int,
short, char, and byte. These operators act upon the individual bits of their operands. They
are summarized in the following table:

Shobha Chandra K, Asst Professor, CSE, MCE Page 25


Introduction to Java Programming - Module-1
The Bitwise Logical Operators
The bitwise logical operators are &, |, ^, and ~. The following table shows the outcome of
each operation.

The following program demonstrates the bitwise logical operators:

// Demonstrate the bitwise logical operators.

class BitLogic {

public static void main(String args[]) {

String binary[] = {

"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111",

"1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"

};

int a = 3; // 0 + 2 + 1 or 0011 in binary

int b = 6; // 4 + 2 + 0 or 0110 in binary

int c = a | b;

int d = a & b;

int e = a ^ b;

int f = (~a & b)|(a & ~b);

int g = ~a & 0x0f;

System.out.println(" a = " + binary[a]);

System.out.println(" b = " + binary[b]);

System.out.println(" a|b = " + binary[c]);

System.out.println(" a&b = " + binary[d]);

System.out.println(" a^b = " + binary[e]);

System.out.println("~a&b|a&~b = " + binary[f]);

System.out.println(" ~a = " + binary[g]);

Shobha Chandra K, Asst Professor, CSE, MCE Page 26


Introduction to Java Programming - Module-1
}

The Left Shift


The left shift operator, <<, shifts all of the bits in a value to the left a specified number of
times. It has this general form:

value << num

Here, num specifies the number of positions to left-shift the value in value. That is, the <<
moves all of the bits in the specified value to the left by the number of bit positions specified
by num. For each shift left, the high-order bit is shifted out (and lost), and a zero is brought
in on the right.

// Left shifting a byte value.

class ByteShift {

public static void main(String args[]) {

byte a = 64, b;

int i;

i = a << 2;

b = (byte) (a << 2);

System.out.println("Original value of a: " + a);

System.out.println("i and b: " + i + " " + b);

The output generated by this program is shown here:

Original value of a: 64

i and b: 256 0

The Right Shift


The right shift operator, >>, shifts all of the bits in a value to the right a specified number
of times. Its general form is shown here:

value >> num

Here, num specifies the number of positions to right-shift the value in value. That is, the >>
moves all of the bits in the specified value to the right the number of bit positions specified
by num.

int a = 32;

a = a >> 2; // a now contains 8

Shobha Chandra K, Asst Professor, CSE, MCE Page 27


Introduction to Java Programming - Module-1
Relational Operators
The relational operators determine the relationship that one operand has to the other.

Boolean Logical Operators

The logical Boolean operators, &, |, and ^, operate on boolean values in the same way that they
operate on the bits of an integer. The logical ! operator inverts the Boolean state: !true == false and
!false == true. The following table shows the effect of each logical operation:

// Demonstrate the boolean logical operators.

class BoolLogic {

public static void main(String args[]) {

boolean a = true;

Shobha Chandra K, Asst Professor, CSE, MCE Page 28


Introduction to Java Programming - Module-1
boolean b = false;

boolean c = a | b;

boolean d = a & b;

boolean e = a ^ b;

boolean f = (!a & b) | (a & !b);

boolean g = !a;

System.out.println(" a = " + a);

System.out.println(" b = " + b);

System.out.println(" a|b = " + c);

System.out.println(" a&b = " + d);

System.out.println(" a^b = " + e);

System.out.println("!a&b|a&!b = " + f);

System.out.println(" !a = " + g);

Short-circuit Logical operators:

These are secondary versions of the Boolean AND and OR operators, and are commonly
known as short-circuit logical operators.

The difference between normal and short-circuit versions is that the normal operands will
always evaluate each operand, but short-circuit versions will evaluate the second operand
only when necessary.

When the right-hand operand depends on the value of the left one in order to function
properly. For example, the following code fragment shows how you can take advantage of
short-circuit logical evaluation to be sure that a division operation will be valid before
evaluating it:

if (denom != 0 && num / denom > 10)

Since the short-circuit form of AND (&&) is used, there is no risk of causing a run-time
exception when denom is zero. If this line of code were written using the single &version of
AND, both sides would be evaluated, causing a run-time exception when denom is zero.

// Demonstrate the short-circuit operators. class SCops {

public static void main(String[] args) {

int n, d, q;

n = 10;

Shobha Chandra K, Asst Professor, CSE, MCE Page 29


Introduction to Java Programming - Module-1
d = 2;

if(d != 0 && (n % d) == 0)

System.out.println(d + " is a factor of " + n);

d = 0; // now, set d to zero

// Since d is zero, the second operand is not evaluated.

if(d != 0 && (n % d) == 0)

System.out.println(d + " is a factor of " + n);

/* Now, try same thing without short-circuit operator.

This will cause a divide-by-zero error.

*/

if(d != 0 & (n % d) == 0)

System.out.println(d + " is a factor of " + n);

Assignment operators:

The assignment operator is the single equal sign, =.

It has this general form:

var = expression;

Here, the type of var must be compatible with the type of expression. int x, y, z;

x = y = z = 100; // set x, y, and z to 100

This fragment sets the variables x, y, and z to 100 using a single statement.

Java provides special operators that can be used to combine an arithmetic operation with an
assignment.

a = a + 4; can rewrite as: a += 4;

There are compound assignment operators for all of the arithmetic, binary operators.

Thus, any statement of the form var = var op expression; can be rewritten as var op=
expression;

The ? Operator
Java includes a special ternary (three-way) operator that can replace certain types of if-then
else statements. This operator is the ?. It can seem somewhat confusing at first, but the ?
can be used very effectively once mastered. The ? has this general form:

Shobha Chandra K, Asst Professor, CSE, MCE Page 30


Introduction to Java Programming - Module-1
expression1 ? expression2 : expression3

Here, expression1 can be any expression that evaluates to a boolean value. If expression1
is true, then expression2 is evaluated; otherwise, expression3 is evaluated. The result of the
? operation is that of the expression evaluated. Both expression2 and expression3 are
required to return the same (or compatible) type, which can’t be void.

Here is an example of the way that the ? is employed:

ratio = denom == 0 ? 0 : num / denom;

// Demonstrate ?.

class Ternary {

public static void main(String args[]) {

int i, k;

i = 10;

k = i < 0 ? -i : i; // get absolute value of i

System.out.print("Absolute value of ");

System.out.println(i + " is " + k);

i = -10;

k = i < 0 ? -i : i; // get absolute value of i

System.out.print("Absolute value of ");

System.out.println(i + " is " + k);

The output generated by the program is shown here:

Absolute value of 10 is 10

Absolute value of -10 is 10

Operator Precedence

The following table shows the order of precedence for Java operators, from highest to
lowest. Operators in the same row are equal in precedence. In binary operations, the order
of evaluation is left to right (except for assignment, which evaluates right to left). Although
they are technically separators, the [ ], ( ), and . can also act like operators. In that
capacity, they would have the highest precedence.

Shobha Chandra K, Asst Professor, CSE, MCE Page 31


Introduction to Java Programming - Module-1

The Precedence of the Java Operators

Using Parentheses

Parentheses raise the precedence of the operations that are inside them.

For example, consider the following expression:

a >> b + 3

This expression first adds 3 to b and then shifts a right by that result. That is, this
expression can be rewritten using redundant parentheses like this:

a >> (b + 3)

However, if you want to first shift a right by b positions and then add 3 to that result, you
will need to parenthesize the expression like this:

(a >> b) + 3

Shobha Chandra K, Asst Professor, CSE, MCE Page 32

You might also like