Download as pdf or txt
Download as pdf or txt
You are on page 1of 32

UNIT I

Introduction to OOP, procedural programming language and object-oriented


language, principles of OOP, applications of OOP, history of java, java features, JVM,
program structure. Variables, primitive data types, identifiers, literals, operators,
expressions, precedence rules and associativity, primitive type conversion and
casting, flow of control.

Introduction to OOP
Everywhere you look in the real world you see objects—people, animals, plants, cars,
planes, buildings, and computers and so on. Humans think in terms of objects.
Telephones, houses, traffic lights, microwave ovens and water coolers are just a few
more objects. We sometimes divide objects into two categories: animate and
inanimate. Animate objects are “alive” in some sense—they move around and do
things. Inanimate objects, on the other hand, do not move on their own. Objects of
both types, however, have some things in common. They all have attributes (e.g.,
size, shape, color and weight), and they all exhibit behaviors (e.g., a ball rolls,
bounces, inflates and deflates; a baby cries, sleep crawls, walks and blinks; a car
accelerates, brakes and turns; a towel absorbs water). We will study the kinds of
attributes and behaviors that software objects have. Humans learn about existing
objects by studying their attributes and observing their behaviors. Different objects
can have similar attributes and can exhibit similar behaviors. Comparisons can be
made, for example, between babies and adults and between humans and
chimpanzees. Object-oriented design provides a natural and intuitive way to view the
software design process—namely, modeling objects by their attributes and behaviors
just as we describe real-world objects. OOD also models communication between
objects. Just as people send messages to one another (e.g., a sergeant commands a
soldier to stand at attention), objects also communicate via messages. A bank
account object may receive a message to decrease its balance by a certain amount
because the customer has withdrawn that amount of money.
Procedural programming language and object-oriented language,
POP OOP
Divided Into Program is divided into small parts called Program is divided into parts
functions. called objects.
Importance Importance is given to functions as well Importance is given to the data rather
as sequence of actions to be done than procedures or functions because it
works as a real world.
Approach It follows Top-down approach. It follows Bottom-up approach.
Data Data can move freely from function to Objects can communicate with each
Moving function in the system other through member functions.
Expansion To add new data and function in POP is It provides an easy way to add new data
not so easy and function.
Data Access Most function uses Global data for Data cannot move easily from function to
sharing that can be accessed freely from function, it can be kept public or private
function to function in the so we can control the access of data.
system
Data Hiding It does not have any proper way for It supports data hiding so provides more
hiding data so it is less secure. security.

1|Page
Overloading In POP, Overloading is not possible. n OOP, overloading is possible in the form
of Function Overloading and Operator
Overloading.
Inheritance No such concept of inheritance in POP Inheritance is allowed in OOP

Access It does not have any access specifiers. It has access specifiers named Public,
Specifiers Private, Protected.

Examples C, BASIC, FORTRAN, Pascal, COBOL C++, JAVA, C#, Smalltalk, Action
Script.

C vs C++ vs JAVA

Principles of OOP,
It is necessary to understand some of the concepts used extensively in object-
object
oriented
programming. These include:
 Object  Data abstraction
 Class  Inheritance
 Encapsulation  Polymorphism
 Dynamic binding  Message passing

Object
Object is the basic run time entity in an object-oriented system. It may represent a
person, a place, a bank account, a table of data, vectors, time and lists. Objects have
states and behaviors.

Example: A dog has states - color, name, breed as well as behaviors – wagging the
tail, barking, eating. An object is an instance of a class.

In OOP, A problem is analyzed in term of objects and the nature of communication


between them. Objects should be chosen such that they match closely with the real-
world objects. Objects take up space in the memory and have an associated address
like a structure in C. When a program is executed, the objects interact by sending
messages to one another.

For example, if “customer” and “account” are to object in a program, then the
customer
object may send a message to the account object requesting for the bank balance.
Each object contain data, and code to manipulate data. Below figure shows two
notations that are popularly used in object-oriented analysis and design.

Class
A class is a collection of similar objects that share the same properties, methods,
relationships and semantics. A class can be defined as a template/blueprint that
describes the behavior/state of the object.

Encapsulation
Definition: The process binding (or wrapping) code and data together into a single
unit is known as Encapsulation.
For example: capsule, it is wrapped with different medicines.

Java supports the feature of Encapsulation using classes.

3|Page
 The data in the class is not accessed by outside world.
 The functions that are defined along with the data within the same class are
allowed to access the data.
 These functions provide the interface between the object’s data and the
program. This insulation of the data from direct access by the program is
called data hiding or information hiding.
 A class defines the structure and behavior (data and code) that will be shared
by a set of objects. Each object of a given class contains the same structure
and behavior defined by the class.
 The objects are referred to as instances of a class. Thus, a class is a logical
construct; an object is physical reality.

Data abstraction
Definition: It a process of providing essential features without providing the
background or implementation details.
For example: It is not important for the user how TV is working internally, and
different components are interconnected. The essential features required to the user
are how to start, how to control volume, and change channels. In java, we use
abstract class and interface to achieve abstraction.
Inheritance
It a process by which an object of one class acquires the properties and methods of
another class. It supports the concept of hierarchical classification. For example, the
bird, ‘robin’ is a part of class ‘flying bird’ which is again a part of the class ‘bird’. The
principal behind this sort of division is that each derived class shares common
characteristics with the class from which it is derived as illustrated in below figure.

In OOP, the concept of inheritance provides the idea of reusability. This means that
we

4|Page
can add additional features to an existing class without modifying it. This is possible
by deriving a new class from the existing one. The new class will have the combined
feature of both the classes. The Class from which the properties are acquired is called
super class, and the class that acquires the properties is called subclass. This is mainly
used for Method Overloading and Code reusability.

Polymorphism
Polymorphism is another important OOP concept. Polymorphism, a Greek term,
means
the ability to take more than one form. An operation may exhibit different behavior is
different instances. The behavior depends upon the types of data used in the
operation.
In Java, we use method overloading and method overriding to achieve
polymorphism.
For example can be to speak something e.g. cat speaks meow, dog barks woof , duck
speaks quack, etc.

Advantages of OOP
OOP offers several benefits to both the program designer and the user. Object-
Orientation contributes to the solution of many problems associated with the
development and quality of software products. The new technology promises greater
programmer productivity, better quality of software and lesser maintenance cost.
The principal advantages are:
 It presents a simple, clear and easy to maintain structure.
 Software complexity can be easily managed.
 It enhances program modularity since each object exists independently.
 New features can be easily added without disturbing the existing one.
 Objects can be reused in another program.
 It allows designing and developing safe programs using the data hiding.
 Through inheritance, we can eliminate redundant code extend the use of
existing classes.
 It is easy to partition the work in a project based on objects.
 Object-oriented system can be easily upgraded from small to large system.
 Message passing techniques for communication between objects makes to
interface descriptions with external systems much simpler.

Applications of OOP,
Applications of OOP are beginning to gain importance in many areas. The most
popular application of object-oriented programming, up to now, has been in the
area of user interface design such as window. Hundreds of windowing systems have
been developed, using the OOP techniques. The promising areas of application of
OOP include:
 Real-time systems
 Simulation and modeling

5|Page
 Object-oriented data bases
 Hypertext, Hypermedia, and Expertext
 AI and expert systems
 Neural networks and Parallel programming
 Decision support and Office automation systems
 CAM/CAD Systems

HISTORY OF JAVA
Java programming Language was written by James Gosling along with two other
team members (team named as Green Team) at Sun Microsystems, Inc. (US) in 1991.
This language was initially designed for small electronics devices and named it
“Greentalk” (.gt was the file extension), after that it was called "Oak" but later it was
renamed to
"Java" in 1995 as Oak was a registered trademark of another company.
Initially, it was an advance model. But it was fit for internet programming. Later, Java
technology as merged by Netscape. Currently, Java is used in web programming,
mobile devices, games, embedded device etc.

In 1990, Sun Microsystems Inc. got a project to develop an application software for
electronics devices that could be managed by remote control.

They named this project as Stealth Project but later it renamed to Green Project. In
1991, Green Team divide project module and James Gosling took the responsibility
to identify the proper programming language for the project and C and C++ was the
best choice for the project. But the problem was that these are system dependent
language and hence they can’t use it in different processors of embedded devices. So
he started developing a new programing language, which was simple and system
independent.

In 1994, the team started developing a java-based Web Browser named Hot Java.
Hot Java was the first Web browser having the potential to execute applets, which
are programs that runs dynamically in internet.

In 1995, Sun Microsystems Inc. formally announced Java and Hot Java. On January
23rd 1996, Sun Microsystems Inc. released the first version of Java i.e., JDK 1.0.

Over time new enhanced versions of Java have been released. The current version of
Java i.e., OpenJDK 10 was released at 20 March 2018 which is also known as Java 9.

Today more than 5 million developers use java and 2 billion devices run java. Thus,
Java saturated the world.

Edition of Java
There are three editions of Java available. Each has its own use. Editions have had

6|Page
many name changes over the years; the current names of the editions are as follows:
 Java Standard Edition (JSE) (Core Java)
JSE can be used to develop client-side standalone applications or applets.
 Java Enterprise Edition (JEE) (Advance Java)
JEE can be used to develop Server-side applications such as java servlets and java
server Pages.
 Java Micro Edition (JME)
JME can be used to develop applications for mobile devices such as cell phones.
In 2010 Oracle Corporation takes over the Sun Microsystems.

JAVA FEATURES
Java has become a popular language for Internet applications because of the
following
features:
 It is simple: Java inherits the syntax of C/C++ and many of the OOPs features
Of C++. Thus, one can understand the concepts of object-oriented language can and
learn Java with minimum effort. Moreover, Java omits the complex and unreliable
codes of C and C++. These codes include operator overloading, pointers and
preprocessor header files. Java provides a short and convenient means to accomplish
a given task.

It can be easily interpreted: Unlike other languages Java uses a system with both a
compiler and an interpreter for program execution. First, the compiler converts the
program code to bytecode which in turn is converted to machine code on any
machine, using the interpreter. The machine code thus generated can be executed
irrespective of the system on which it is being executed.

It has neutral architecture (independent of platform): This feature makes Java very
special. Java programs can run on any platform, which means that they can run on
different CPUs and operating system architectures. The bytecode produced by the
Java compiler can run on any machine which has Java run-time environment.

It is an object-oriented language: Java is an object-oriented language as it bounds


code and data together in the form of objects. The objects and classes contain the
program code and data. The Java object model is easily extensible and classes can be
used anywhere in the program in the form of packages.

It is robust: Java is a robust language because of two main reasons, first, it is a


language typed strictly that checks the code at the time of compilation; second, it
manages memory in an effective way. In C++, the programmer has to manually de-
allocate the dynamic memory used by objects. Java does this automatically (with the
help of a feature known as garbage collector).

It can be distributed: Since Java is not dependent on any platform, it is suitable for

7|Page
developing applications for networks. Java can handle TCP/IP protocols and hence
applications developed in it can access remote objects on the Internet like
any object on a local system.

It is multithreaded: Java supports multithreaded programming which allows us to


write a program that can perform more than one task simultaneously. A user need
not to wait for one program to finish a task, before starting the next task for
example, a user can listen to an audio clip while downloading the applet. This feature
helps to improve the performance of graphical applications.

Its quality of performance is high: As stated earlier, a Java program is converted to


bytecode which is then converted to machine code using an interpreter. Since
bytecode is highly optimized, it enables the JVM to execute programs at a faster rate

It is dynamic: Java programs can link to new class libraries, objects, methods, etc., at
the run-time. Java also provides the facility to include functions of other languages
like C and C++.These are referred toas native methods. These methods are also
linked dynamically at run-time.

JVM,
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides
runtime environment in which java bytecode can be executed.
JVMs are available for many hardware and software platforms (i.e., JVM is platform
dependent).

What is JVM?
1. A specification where working of Java Virtual Machine is specified. But
implementation provider is independent to choose the algorithm. Its
implementation has been provided by Sun and other companies.
2. An implementation is known as JRE (Java Runtime Environment).
3. Runtime Instance Whenever you write java command on the command
prompt to run the java class, an instance of JVM is created.
What it does
The JVM performs following operation:
 Loads code
 Verifies code
 Executes code
 Provides runtime environment
JVM provides definitions for the:
 Memory area
 Class file format
 Register set
 Garbage-collected heap
 Fatal error reporting etc.

8|Page
Internal Architecture of JVM
the JVM is divided into three main subsystems:
1. Class Loader Subsystem
2. Runtime Data Area
3. Execution Engine

1. Class loader Java's dynamic class loading functionality is handled by the class
loader subsystem. It loads, links and initializes the class file when it refers to a
class for the first time at runtime, not compile time
2. Runtime Data Area is divided into 5 major components:
1. Class (Method) All the class level data will be stored here, including static
variables. There is only one method area per JVM, and it is a shared resource
2. Heap All the Objects and their corresponding instance variables and
arrays will be stored here. There is also one Heap Area per JVM. Since the
Method and Heap areas share memory for multiple threads, the data stored is
not thread safe.
3. Stack Java Stack stores frames. It holds local variables and partial results, and
plays a part in method invocation and return.
o Each thread has a private JVM stack, created at the same time as
thread.
o A new frame is created each time a method is invoked. A frame is
destroyed when its method invocation completes.
4. Program Counter (PC) Register Each thread will have separate PC Registers, to
hold the address of current executing instruction once the instruction is
executed the PC register will be updated with the next instruction.
5. Native Method Stack holds native method information. For every thread, a
separate native method stack will be created

3. Execution Engine The byte code which is assigned to the Runtime Data Area will be
executed by the Execution Engine. The Execution Engine reads the byte code and
executes it piece by piece.
1. Interpreter – The interpreter interprets the byte code faster, but executes
slowly. The disadvantage of the interpreter is that when one method is called
multiple times, every time a new interpretation is required.
2. JIT Compiler – The JIT Compiler neutralizes the disadvantage of the interpreter.

9|Page
The Execution Engine will be using the help of the interpreter in converting byte
code, but when it finds repeated code it uses the JIT compiler, which compiles
the entire bytecode and changes it to native code. This native code will be used
directly for repeated method calls, which improve the performance of the system.

Java Native Interface (JNI): JNI will be interacting with the Native Method Libraries
and provides the Native Libraries required for the Execution Engine.

Native Method Libraries: It is a collection of the Native Libraries which is required for
the Execution Engine.

PROGRAM STRUCTURE
A Java program may contain many classes of which only one class defines a main
method. Classes contain data members and methods that operate on the data
members of the class. To write a Java program, we first define classes and put them
together. A java program may contain one or more sections as shown in the figure.

Documentation Section (Optional)


The documentation section consists of a set of comment lines which gives the name
of the program, the author and other details. Comments must explain why and what
type of classes and how of algorithms. Java uses a special type of comment /**…….*/
known as credentials comments. This form of comment is used to generating
comments automatically.

Package statement (Optional)


The first statement in a java file is a package statement. It declares a package name
and inform the compiler that the classes define belong to the same package. This
statement is optional.
Package package_name:
Package pkg1
{
…………………..
}
Package pkg2
{

10 | P a g e
……………..
}
Import statement (optional)
These are similar to # include statement in C or C++, this instructs the interpreter to
load the method or class contained in the package.

Interface statement (optional):


It is a class including a group of method declaration. It is used when multiple
inheritances are implementing.

Class definition
Classes are defining to make the objects of real-world problem. The number of
classes used depends on complexity of the program

Main method class:


It is the starting point and essential part of java programming while executing. It
creates object of various classes and established a communication between them.
Simple Java Program
public class Demo {
public static void main (String args[]) {
System.out.println("Welcome to Java Class");
}
}
Let us discuss the program line by line and understand the unique features that
constitute a Java program.

Class Declaration
The first line class Demo, class is a keyword used to declare the class. As we know
Java is a truly object-oriented language so everything must be placed inside a class.
Demo is the identifier in java that defines the name of the class.

Opening brace
Every class definition in java begins with an opening brace “{” and ends with a
matching closing brace “}”.

The Main Line:


public static void main (String args[])

Every Java program must include the main() method. Java applets does not use
main() method. This line contains a number of keywords public, static and void.

Public: The keyword is an access specifier which represents visibility, it means it is


accessible to all other classes. This is similar to C++ public modifier.

11 | P a g e
Static: Statics a keyword, if we declare any method as static, it is treated as static
method. The static method invoked without creating instance of a class. The main
method is executed by the JVM, so it doesn't require creating an object to call the
main method. So, it saves memory. void: void means nothing. It is the return type.
main method use void as it does not return any value.

String args[]: main method accept some data from user as command line argument
in form of String and this can be achieved by String args[] array.

VARIABLES
A variable is a storage location (container) that stores values that are used in a Java
program. Variables may change during the execution of the program. Every variable
must be declared to use a data type. For example, a variable could be declared to use
one of the eight primitive data types: byte, short, int, long, float, double, char or
boolean and every variable must be given an initial value before it can be used

Variable names consist of alphabets, digits, underscore (_) and dollar ($)
symbol, subject to the following conditions.
1. They must not begin with a digit.
2. Uppercase and lowercase are distinct. This means the variable COUNT
is not same as the count.
3. It should not be a keyword.
4. White space is not allowed.
5. Variable names can be of any length.

Declaration of Variables
Variables are the names of storage location. After designing suitable variable names,
we must declare them to the compiler. Declaration does three things: -
1. It tells the compiler what the variable name is.
2. It specifies what type of data the variable will hold.
3. The place of declaration decides the scope of the variable.

A variable must be declared before it is used in the program. A variable can be used
to store a value of any data type. The general form of declaration of a variable is:
Data type variable1, variable2.................................variableN
Variables are separated by commas. A declaration statement must end with a
semicolon (;).
Some valid declarations are
int a,b,c;
byte x;
char m;
Scope of Variable

12 | P a g e
Every variable has two properties. One is lifetime and another is scope. Life time of a
variable specifies the duration that a variable exists. The scope of a variable specifies
the section of the source program 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 deal locating the memory that was allotted to the
variables when declaring it. We have written a few classes till now. You might have
observed that not all variables are the same. The ones declared in the body of a
method were different from those that were declared in the class itself. There are
three
types of variables in Java

 Local variables
 Instance variables
 Class variables

Local Variables
 The variables which are declare inside a method & inside a block & inside a
constructor is called local variables
 The scope of local variables is inside a method or inside a constructor or
inside a block.
 We are able to use the local variable only inside the method or inside the
constructor or inside the block only
class Test{
public static void main(String[] args){
int a=10; //Local variables
int b=20;
System.out.println (a+b);
}
}
Instance Variable
1. The variables which are declare inside a class and outside of the methods is
called instance variables.
2. We are able to access instance variables only inside the class any number of
methods but these variables are methods can’t be accessed inside static
content.
3. We can declare instance variables without initializing a value to the variable
also for those variables it will take default values of data type.
4. Instance variables can be accessed by using object and using this operator
class Test{
int a=10; // instance variable
int b=20; // instance variable
void add(){
System.out.println(a+b);

13 | P a g e
}
public static void main(String[] args){
Test t=new Test();
System.out.println(t.a+t.b);
t.add();
}
}
Class Variable
The instance variables which are declared as a static modifier such type of variables is
called static variables.
 We are able to access static variables within the class any number of methods.
 We can declare static variables without initializing a value to the variable also
for those variables it will take default values of data type.
 These variables can be accessed by using class name and also using object
name.
class Test{
static int a=10;
static int b=20;
public static void main(String[] args){
System.out.println(a+b);
}
void add(){
System.out.printl(a+b);
}
}

Diff b/w Instance Variables and Static Variables:


Instance Variables:
• Instance Variables are declared without static keyword.
• They are specific to object i.e., for every object, separate memory will
be allocated for each instance Variable.
• They can be accessed only by using the Object.
Static Variables:
• Static Variables are declared with static keyword.
• They are also called as “Class Variables”.
• They are not specific to any object.
• The memory for static Variables will be allocated whenever the class is
loaded in to the memory i.e., memory will be allocated only once which
will be shared by all the objects of the class.

Naming Conventions
Naming conventions specify the rules to be followed by a Java programmer while
writing the names of packages, classes, methods etc.
1. Package names are written in small letters.

14 | P a g e
e.g.: java.io, java.lang, java.awt etc
2. Each word of class name and interface name starts with a capital
e.g.: Sample, AddTwoNumbers
3. Method names start with small letters then each word start with a capital
e.g.: sum (), sumTwoNumbers (), minValue ()
4. Variable names also follow the same above method rule
e.g.: sum, count, totalCount
5. Constants should be written using all capital letters
e.g.: PI, COUNT
6. Keywords are reserved words and are written in small letters.
e.g.: int, short, float, public, void

PRIMITIVE DATA TYPES,


Variables are nothing but reserved memory locations to store values. This means that
when you create a variable you reserve some space in memory. Based on the data
type of a variable, the operating system allocates memory and decides what can be
stored in the reserved memory. Therefore, by assigning different data types to
variables, you can store integers, decimals, or characters in these variables.
There are two data types available in Java:
1. Primitive Data Types
2. Reference/Object Data Types
Primitive Data Types:
There are eight primitive data types supported by Java. Primitive data types are
predefined by the language and named by a key word. Let us now look into detail
about the eight primitive data types.

1. byte:
 Byte data type is a 8-bit signed two's complement integer.
 Minimum value is -128 (-2^7)
 Maximum value is 127 (inclusive)(2^7 -1)
 Default value is 0
 Byte data type is used to save space in large arrays, mainly in place of integers,
since a byte is four times smaller than an int.
Example: byte a = 100, byte b = -50
2. short:
 Short data type is a 16-bit signed two's complement integer.
 Minimum value is -32,768 (-2^15)
 Maximum value is 32,767(inclusive) (2^15 -1)
 Short data type can also be used to save memory as byte data type. A short is
2 times smaller than an int
 Default value is 0.
Example: short s= 10000, short r = -20000
3. int:
 Int data type is a 32-bit signed two's complement integer.

15 | P a g e
 Minimum value is - 2,147,483,648.(-2^31)
 Maximum value is 2,147,483,647(inclusive).(2^31 -1)
 Int is generally used as the default data type for integral values unless there is
a concern about memory.
 The default value is 0.
Example: int a = 100000, int b = -200000
4. long:
 Long data type is a 64-bit signed two's complement integer.
 Minimum value is -9,223,372,036,854,775,808.(-2^63)
 Maximum value is 9,223,372,036,854,775,807 (inclusive). (2^63 -1)
 This type is used when a wider range than int is needed.
 Default value is 0L.
Example: long a = 100000L, int b = -200000L
5. float:
 Float data type is a single-precision 32-bit IEEE 754 floating point.
 Float is mainly used to save memory in large arrays of floating point numbers.
 Default value is 0.0f.
 Float data type is never used for precise values such as currency.
Example: float f1 = 234.5f
6. double:
 double data type is a double-precision 64-bit IEEE 754 floating point.
 This data type is generally used as the default data type for decimal values.
generally, the default choice
 Double data type should never be used for precise values such as currency.
 Default value is 0.0d.
Example: double d1 = 123.4
7. boolean:
 boolean data type represents one bit of information.
 There are only two possible values: true and false.
 This data type is used for simple flags that track true/false conditions.
 Default value is false.
Example: boolean one = true
8. char:
 char data type is a single 16-bit Unicode character.
 Minimum value is '\u0000' (or 0).
 Maximum value is '\uffff' (or 65,535 inclusive).
 Char data type is used to store any character.
Example: char letterA ='A'

IDENTIFIERS,
Identifiers in Java are symbolic names used for identification. They can be a class
name,
variable name, method name, package name, constant name, and more.
Rules for Identifiers in Java

16 | P a g e
If the identifiers are not properly declared, we may get a compile-time error.
Following are some rules and conventions for declaring identifiers:
 A valid identifier must have characters [A-Z] or [a-z] or numbers [0-9], and
underscore (_) or a dollar sign ($).
For example, @sample is not a valid identifier because it contains a special
character which is @.
 There should not be any space in an identifier.
For example, Sample Program is an invalid identifier.
 An identifier should not contain a number at the starting.
For example, 123Sample is an invalid identifier.
 An identifier should be of length 4-15 letters only. However, there is no limit
on its length. But it is good to follow the standard conventions.
 We can't use the Java reserved keywords as an identifier such as int, float,
double, char, etc.
For example, int double is an invalid identifier in Java.
 An identifier should not be any query language keywords such as SELECT,
FROM, COUNT, DELETE, etc

LITERALS,
Any constant value which can be assigned to the variable is called as literal/constant.
// Here 100 is a constant/literal.
int x = 100;
Integral literals
For Integral data types (bye, short, int, long), we can specify literals in 4 ways:-
1. Decimal literals (Base 10): In this form the allowed digits are 0-9.
int x = 101;
1. Octal literals (Base 8): In this form the allowed digits are 0-7.
// the octal number should be prefix with 0.
int x = 0146;
2. Hexa-decimal literals (Base 16): In this form the allowed digits are 0-9 and
characters are a-f. We can use both uppercase and lowercase characters. As
we know that java is a case-sensitive programming language but here java is
not case-sensitive.
3. // The hexa-decimal number should be prefix
// with 0X or 0x.
int x = 0X123Face;
4. Binary literals: From 1.7 onward we can specify literals value even in binary
form also, allowed digits are 0 and 1. Literals value should be prefixed with 0b
or 0B.
int x = 0b1111;

//Java program to illustrate the 101


application of Integer literals 64
public class Test { 64206

17 | P a g e
public static void main(String[] args) { 15
int a = 101; // decimal-form literal
int b = 0100; // octal-form literal
int c = 0xFace; // Hexa-decimal form
literal
int d = 0b1111; // Binary literal
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
}
}

OPERATORS,
Java provides a rich set of operators to manipulate variables. We can divide all the
Java operators into the following groups:
1. Arithmetic Operators 4. Logical Operators
2. Relational Operators 5. Assignment Operators
3. Bitwise Operators 6. Misc Operators

1 Arithmetic Operators
Java arithmetic operators are used to perform addition, subtraction, multiplication,
and
division. They act as basic mathematical operations.
public class Test { Output
public static void main(String args[]) { a + b = 30
int a = 10; a - b = -10
int b = 20; a * b = 200
int c = 25; b/a=2
System.out.println("a + b = " + (a + b)); b%a=0
System.out.println("a - b = " + (a - b)); c%a=5
System.out.println("a * b = " + (a * b));
System.out.println("b / a = " + (b / a));
System.out.println("b % a = " + (b % a));
System.out.println("c % a = " + (c % a));
}
}

2 Relational Operators
Relational operators are used to check the relationship between two operands.
public class Test { Output
public static void main(String args[]) { a == b = false
int a = 10; a != b = true
int b = 20; a > b = false

18 | P a g e
System.out.println("a == b = " + (a == b)); a < b = true
System.out.println("a != b = " + (a != b)); b >= a = true
System.out.println("a > b = " + (a > b)); b <= a = false
System.out.println("a < b = " + (a < b));
System.out.println("b >= a = " + (b >= a));
System.out.println("b <= a = " + (b <= a));
}
}

3. Bitwise Operators
Bitwise operators in Java are used to perform operations on individual bits.
public class Test { Output
public static void main(String args[]) { a & b = 12
int a = 60; /* 60 = 0011 1100 */ a | b = 61
int b = 13; /* 13 = 0000 1101 */ a ^ b = 49
int c = 0; ~a = -61
c = a & b; /* 12 = 0000 1100 */ a << 2 = 240
System.out.println("a & b = " + c ); a >> 2 = 15
c = a | b; /* 61 = 0011 1101 */ a >>> 2 = 15
System.out.println("a | b = " + c );
c = a ^ b; /* 49 = 0011 0001 */
System.out.println("a ^ b = " + c );
c = ~a; /*-61 = 1100 0011 */
System.out.println("~a = " + c );
c = a << 2; /* 240 = 1111 0000 */
System.out.println("a << 2 = " + c );
c = a >> 2; /* 15 = 1111 */
System.out.println("a >> 2 = " + c );
c = a >>> 2; /* 15 = 0000 1111 */
System.out.println("a >>> 2 = " + c );
}
}

4. Logical Operators:
Logical operators are used to check whether an expression is true or false. They are
used in decision making.
public class Test { Output
public static void main(String args[]) { a && b = false
boolean a = true; a || b = true
boolean b = false; !(a && b) = true
System.out.println("a && b = " +
(a&&b));
System.out.println("a || b = " + (a||b));
System.out.println(“! (a && b) = " +! (a

19 | P a g e
&& b));
}
}

5. Assignment Operators:
Assignment operators are used in Java to assign values to variables.
public class Test { Output
public static void main(String args[]) { c = a + b = 30
int a = 10; c += a = 40
int b = 20; c -= a = 30
int c = 0; c *= a = 300
c = a + b; c /= a = 1
System.out.println("c = a + b = " + c); c %= a = 5

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

c -= a;
System.out.println("c -= a = " + c);
c *= a;
System.out.println("c *= a = " + c);
a = 10;
c = 15;
c /= a;
System.out.println("c /= a = " + c);
a = 10;
c = 15;
c %= a;
System.out.println("c %= a = " + c);
}
}

6. Unary Operators
In Java, the unary operator is an operator that can be used only with an operand. It is
used to represent the positive or negative value, increment/decrement the value by
1,
and complement a Boolean value.

Example 1: Java Unary Operator Example: ++ and --


public class OperatorExample{ Output
public static void main(String args[]){ 10
int x=10; 12
System.out.println(x++); 12
System.out.println(++x); 10

20 | P a g e
System.out.println(x--);
System.out.println(--x);
}
}

Example 2: Java Unary Operator Example: ~ and !


public class OperatorExample{ Output
public static void main(String args[]){ -11
int a=10; 9
int b=-10; false
boolean c=true; true
boolean d=false;
System.out.println(~a);
System.out.println(~b);
System.out.println(!c);
System.out.println(!d);
}
}

7. Conditional Operator:
The conditional operator is also called a ternary operator because it requires three
operands. This operator is used for decision making. In this operator, first, we verify a
condition, then we perform one operation out of the two operations based on the
condition result. If the condition is TRUE the first option is performed, if the condition
is FALSE the second option is performed.
Syntax:
Condition ? TRUE Part : FALSE Part;
public class ConditionalOperator { Output:
public static void main(String[] args) { c = 20
int a = 10, b = 20, c;
c = (a>b)? a : b;
System.out.println("c = " + c);
}
}

8. Misc Operators
Instanceof operator:
The java instanceof operator is used to test whether the object is an instanceof the
specified type (class or subclass or interface).

The instanceof in java is also known as type comparison operator because it


compares the instance with type. It returns either true or false. If we apply the
instanceof operator with any variable that has null value, it returns false.

21 | P a g e
class Simple1{ Output:
public static void main(String args[]){ true
Simple1 s=new Simple1();
System.out.println(s instanceof Simple1);
}
}

EXPRESSIONS,
An expression is a collection of operators and operands that represents a specific
value.
• In the above definition, an operator is a symbol that performs tasks like
arithmetic operations, logical operations, and conditional operations,
etc.
• Operands are the values on which the operators perform the task. Here
operand can be a direct value or variable or address of memory
location.

Following are some of the examples for expression


int a =10; //Assignment expression
System.out.println(“Value =”+x);

int result = a+10; //Assignment exp

if(val1<=val2) //Boolean expression


b = a++; //Assignment exp
Expression evaluation is based upon the following Concepts:
Operator precedence Associativity rules

PRECEDENCE RULES AND ASSOCIATIVITY,


All the operators in Java are divided into several groups and are assigned a
precedence level. The operator precedence and associativity rules for the operators
in Java is shown below:

22 | P a g e
Operator precedence
It determines which operator is performed first in an expression with more than one
operator with different precedence.
public class Precedence { Output:
public static void main(String[] args) { 28
System.out.println(3 + 5 * 5); 40
System.out.println((3 + 5) * 5);
}
}

PRIMITIVE TYPE CONVERSION CASTING,


Java supports two type of type Casting – Primitive Data Type Casting & Reference
Type Casting. Reference type casting means assigning one Java object to another
Java object. It comes with very strict rules.
Java Data Type Casting comes with two flavors:
1 Implicit Casting
2 Explicit Casting
1. Implicit Casting (Widening Conversion)
A data type of lower size (requires less memory) is assigned to a data type of higher
memory size. This is done implicitly (automatically) by JVM. The lower size is widened
to higher size. This is also called as automatic type conversion.
Examples:
int x = 10; // occupies 4 bytes
double y = x; // occupies 8 bytes
System.out.println(y); // prints 10.0
In above code 4 byte integer value is assigned to 8 byte double value.
2. Explicit Type Casting (Narrowing Conversion)
A data type of higher size cannot be assigned to a data type of lower size. This is not
done implicitly by JVM and requires explicit casting; a casting is performed manually

23 | P a g e
by the programmer. The higher size is narrowed to lower size.
double x = 10.5; // 8 bytes
int y = x; // 4 bytes; raises compilation error
In above code 8-byte double value is narrowed to 4-byte int value but it will
generate an error. So, this can be done manually as:
double x = 10.5;
int y = (int) x;

Widening Conversion Narrowing Conversion


class Simple{ class Simple{
public static void main(String[] args){ public static void main(String[] args){
int a=10; float f=10.5f;
float f=a; //int a=f;//Compile time error
System.out.println(a); int a=(int)f;
System.out.println(f); System.out.println(f);
}} System.out.println(a);
}}
class Simple{ class Simple{
public static void main(String[] args){ public static void main(String[] args){
int a=10; //Overflow
float f=a; int a=130;
System.out.println(a); byte b=(byte)a;
System.out.println(f); System.out.println(a);
}} System.out.println(b);
}}

FLOW OF CONTROL.
In java, the default execution flow of a program is a sequential order. But the
sequential order of execution flow may not be suitable for all situations. Sometimes,
we may want to jump from line to another line, we may want to skip a part of the
program, or sometimes we may want to execute a part of the program again and
again. To solve this problem, java provides control flow statements.

Types of Control Statements


In java, the control statements are classified as follows.
❖ Selection Control Statements (Decision Making Statements)
❖ Iterative Control Statements (Looping Statements)
❖ Jump Statements

Selection Control Statements


In java, the selection statements are also known as decision making statements or
branching statements. The selection statements are used to select a part of the
program to be executed based on a condition. Java provides the following selection

24 | P a g e
statements.
❖ if statement ❖ nested if statement
❖ if-else statement ❖ switch statement
❖ if-else-if ladder statement

❖ if statement
The if statement checks, the given condition then decides the execution of a block of
statements. If the condition is True, then the block of statements is executed and if it
is False, then the block of statements is ignored.
Syntax:
if(condition){
//code to be executed
}

class IfStatement { Output:


public static void main(String[] args) { Statement outside if block
int number = 10;
if (number < 0) {
System.out.println("The number is negative.");
}
System.out.println("Statement outside if block");
}
}

❖ if-else Statement
The Java if-else statement also tests the condition. It executes the if block if condition
is true otherwise else block is executed.
Syntax:
if(condition){
//code if condition is true
}else{
//code if condition is false
}

class Main { Output:


public static void main(String[] args) { The number is positive
int number = 10;
if (number > 0)
System.out.println("The number is positive.");
else
System.out.println("The number is not positive.");
}
}

25 | P a g e
❖ if-else-if ladder Statement
The if-else-if ladder statement executes one condition from multiple statements.
Syntax:
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}

public class IfElseIfExample { Output:


public static void main(String[] args) { A grade
int marks=85;

if(marks<50){
System.out.println("fail");
}
else if(marks>=50 && marks<60){
System.out.println("D grade");
}
else if(marks>=60 && marks<70){
System.out.println("C grade");
}
else if(marks>=70 && marks<80){
System.out.println("B grade");
}
else if(marks>=80 && marks<90){
System.out.println("A grade");
}else if(marks>=90 && marks<100){
System.out.println("A+ grade");
}else{
System.out.println("Invalid!");
}
}
}

❖ nested if statement
The nested if statement represents the if block within another if block. Here, the inner

26 | P a g e
if block condition executes only when outer if block condition is true.

Syntax:
if(condition){
//code to be executed
if(condition){
//code to be executed
}
}

public class JavaNestedIfExample { Output:


public static void main(String[] args) { You are eligible to donate blood
//Creating two variables for age and
weight
int age=20;
int weight=80;
//applying condition on age and weight
if(age>=18){
if(weight>50){
System.out.println("You are eligible to
donate blood");
}
}
}
}

❖ Switch Statement
The switch statement executes one statement from multiple conditions. It is like if-
else-if ladder statement.
Points to Remember
❖ There can be one or N number of case values for a switch expression.
❖ The case value must be of switch expression type only. The case value must be
literal or constant. It doesn't allow variables.
❖ The case values must be unique. In case of duplicate value, it renders compile-time
error.
❖ The Java switch expression must be of byte, short, int, long (with its Wrapper type),
enums and string.
❖ Each case statement can have a break statement which is optional. When control
reaches to the break statement, it jumps the control after the switch expression. If a
break statement is not found, it executes the next case.
❖ The case value can have a default label which is optional.

Syntax:
switch(expression){

27 | P a g e
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
}

public class SwitchExample { Output:


public static void main(String[] args) { 20
//Declaring a variable for switch
expression
int number=20;
//Switch expression
switch(number){
//Case statements
case 10: System.out.println("10");
break;
case 20: System.out.println("20");
break;
case 30: System.out.println("30");
break;
//Default case statement
default:System.out.println("Not in 10,
20 or 30");
}
}
}

❖ Iterative Control Statements (Looping Statements)


In Java loop is used to iterate a part of the program several times.
A simple for loop is the same as C/C++. We can initialize the variable, check
condition and increment/decrement value. It consists of four parts:

1. Initialization: It is the initial condition which is executed once when the loop starts.
Here, we can initialize the variable, or we can use an already initialized variable. It is
an optional condition.
2. Condition: It is the second condition which is executed each time to test the
condition of the loop. It continues execution until the condition is false. It must
return boolean value either true or false. It is an optional condition.
3. Increment/Decrement: It increments or decrements the variable value. It is an

28 | P a g e
optional condition.
4. Statement: The statement of the loop is executed each time until the second
condition is false.

//Java Program to demonstrate the public class ForExample {


example of for loop public static void main(String[] args) {
//Code of Java for loop
for(int i=1;i<=10;i++){
System.out.println(i);
}
}
}
//Java Program to demonstrate the public class WhileExample {
example of While loop public static void main(String[] args) {
int i=1;
while(i<=10){
System.out.println(i);
i++;
}
}
}
//Java Program to demonstrate the public class DoWhileExample {
example of Do-While loop public static void main(String[] args) {
int i=1;
do{
System.out.println(i);
i++;
}while(i<=10);
}
}

Nested for Loop


If we have a for loop inside another loop, it is known as nested for loop. The inner
loop executes completely whenever outer loop executes.
public class PyramidExample { Output:
public static void main(String[] args) { *
for(int i=1;i<=5;i++){ **
for(int j=1;j<=i;j++){ ***
System.out.print("* "); ****
} *****
System.out.println();//new line
}
}
}

29 | P a g e
Example: ForEachExample.java
//Java For-each loop example which prints the elements of the array
public class ForEachExample { Output:
public static void main(String[] args) { 12
//Declaring an array 23
int arr[]={12,23,44,56,78}; 44
//Printing array using for-each loop 56
for(int i:arr){ 78
System.out.println(i);
}
}
}

Jump Statements
The java programming language supports jump statements that used to transfer
execution control from one line to another line. The java programming language
provides the following
jump statements.
❖ break statement
❖ continue statement
❖ labelled break and continue statements

break statement
The break statement in java is used to terminate a switch or looping statement. That
means the break statement is used to come out of a switch statement and a looping
statement like while, do-while, for, and for-each.

public class JavaBreakStatement { Output:


public static void main(String[] args) { 10
int list[] = {10, 20, 30, 40, 50}; 20
for(int i : list) {
if(i == 30)
break;
System.out.println(i);
}
}
}

Continue Statement
The Java continue statement is used to continue the loop. It continues the current
flow of the program and skips the remaining code at the specified condition. In case
of an inner loop, it continues the inner loop only.

30 | P a g e
We can use Java continue statement in all types of loops such as for loop, while loop
and do while loop
public class ContinueExample { Output:
public static void main(String[] args) { 1
for(int i=1;i<=5;i++){ 2
if(i==3){ 4
continue; //it will skip the rest 5
statement
}
System.out.println(i);
}
}
}

labelled break and continue statements


❖ The java programming language does not support goto statement, alternatively,
the
break and continue statements can be used with label.
❖ The labelled break statement terminates the block with specified label.
❖ The labelled continue statement takes the execution control to the beginning of a
loop with specified label.

public class LabeledForExample { Output:


public static void main(String[] args) { 11
//Using Label for outer and for loop 12
aa: 13
for(int i=1;i<=3;i++){ 21
bb:
for(int j=1;j<=3;j++){
if(i==2&&j==2){
break aa;
}
System.out.println(i+" "+j);
}
}
}
}
public class LabeledForExample { Output:
public static void main(String[] args) { 11
//Using Label for outer and for loop 12
aa: 13
for(int i=1;i<=3;i++){ 21
bb: 31
for(int j=1;j<=3;j++){ 32

31 | P a g e
if(i==2&&j==2){ 33
continue aa;
}
System.out.println(i+" "+j);
}
}
}
}

32 | P a g e

You might also like