0% found this document useful (0 votes)
4 views110 pages

B21DA0302_Unit1

The document provides an overview of Java programming, including its history, features, and differences from C and C++. It discusses the Java environment setup, types of Java applications, and the structure of a Java program. Additionally, it covers Java tokens and statements, explaining their roles in Java programming.

Uploaded by

sanketraikar78
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views110 pages

B21DA0302_Unit1

The document provides an overview of Java programming, including its history, features, and differences from C and C++. It discusses the Java environment setup, types of Java applications, and the structure of a Java program. Additionally, it covers Java tokens and statements, explaining their roles in Java programming.

Uploaded by

sanketraikar78
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 110

JAVA PROGRAMMING

B21DA0302- Academic Year-2022-2023- sem III ODD Semester

BCA, School of CSA


MANJU.B
Assistant Professor
JAVA PROGRAMMING (UNIT
1)
1. Introduction to Java: JAVA Evolution: Java History, Java Features,
How Java Differs from C and C++, Java Environment. Overview
of JAVA Language: Introduction, Java Program structure, Java
Tokens, Java Statements, Java Virtual Machine, Command Line
Arguments, Constants, Variables, and Data Types Scope of
variables, Type Casting, Operators and Expressions; Arithmetic
Expressions, Evaluation of Expressions, Precedence of Arithmetic
Operators, Type conversion and associability, Mathematical
Functions. Decision Making and Branching: Decision Making
Statement and Looping: while, do, for Statement.
TOPICS TO BE LEARNED FROM
THIS CLASS

History of JAVA

Java Version History

Features of JAVA
INTRODUCTION TO JAVA
History of JAVA

• Java was originally designed for interactive television

• The history of Java starts with the Green Team.

• Java team members (also known as Green Team), initiated this project to

develop a language for digital devices such as set-top boxes, televisions,

etc.

• The principles for creating Java programming were "Simple, Robust,

Portable, Platform-independent, Secured, High Performance,

Multithreaded, Object-Oriented, Interpreted, and Dynamic".


INTRODUCTION TO JAVA
History of JAVA

• Java was developed by James Gosling, who is known as the father of


Java.

• James Gosling and his team members started the project in the
early '90s.

• Currently, Java is used in internet programming, mobile


devices, games, e-business solutions, etc.

• Firstly, it was called "Greentalk" by James Gosling, and the file


extension was
.gt.

• After that, it was called Oak and was developed as a part of the
Green project.
INTRODUCTION TO JAVA
History of JAVA

• Why Java was named as


"Oak"?

• Oak is a symbol of strength and chosen as a national tree of many


countries like the U.S.A., France, Germany, Romania, etc.

• In 1995, Oak was renamed as "Java" because it was already


a trademark by Oak Technologies.
INTRODUCTION TO JAVA
History of JAVA

Why Java Programming named "Java"?


□ The suggested words were "dynamic", "revolutionary", "Silk", "jolt",
"DNA", etc.
□ Java is an island of Indonesia where the first coffee was
produced (called java coffee).
□ Notice that Java is just a name, not an acronym.
□ Initially developed by James Gosling at Sun Microsystems(it is a
product) (which is now a subsidiary of Oracle Corporation) and
released in 1995.
INTRODUCTION TO JAVA
History of JAVA

□ JDK 1.0 released in(January 23, 1996). After the first release of
Java, there have been many additional features added to the
language.

□ Now Java is being used in Windows applications, Web


applications, enterprise applications, mobile applications, cards,
etc. Each new version adds new features in Java.

□ Java divided into 3


□ 1. core java: developing the software
□ 2. advance java : web sites
□ 3. android java: mobile apps
INTRODUCTION TO JAVA

JAVA VERSION □J2SE 5.0 (30th Sep 2004)


HISTORY
□Java SE 6 (11th Dec 2006)
□JDK Alpha and Beta
(1995)
□Java SE 7 (28th July 2011)
□JDK 1.0 (23rd Jan 1996)
□Java SE 8 (18th Mar 2014)
□JDK 1.1 (19th Feb 1997)
□Java SE 9 (21st Sep 2017)
□J2SE 1.2 (8th Dec 1998)
□Java SE 10 (20th Mar
□J2SE 1.3 (8th May 2000) 2018)

□J2SE 1.4 (6th Feb 2002)


INTRODUCTION TO JAVA

FEATURES OF JAVA
□ Simple

□ Object-Oriented

□ Portable

□ Platform
independent

□ Secured

□ Robust
FEATURES OF JAVA
□ Simple

□ Object-Oriented

□ Portable

□ Platform
independent

□ Secured

□ Robust
TOPICS DISCUSSED IN PREVIOUS
CLASS

History of JAVA

Java Version History

Features of JAVA
TOPICS TO BE LEARNED FROM
THIS CLASS

How JAVA Differ from C and C++

JAVA Environment
HOW JAVA DIFFER
FROM C
□ Java does not include the C unique statement keywords sizeof, and typedef.
□ Java does not contain the data type struct and union.
□ Java does not define the type modifiers keywords auto, extern, register,
signed and
unsigned.
□ Java does not support an explicit pointer type.

□ Java does not have a preprocessor and therefore we cannot use # define, #
include, and # ifdef statements.
□ Java requires that the functions with no arguments must be declared
with empty parenthesis and not with the void keyword as done in C.
□ Java adds new operators such as instanceof and >>>.

□ Java adds labelled break and continue statements. Java adds many features
required for object-oriented programming.
HOW JAVA DIFFER
FROM C++
□ Platform-independent □ Structure and Union
□ Mainly used for
□ Thread Support
□ Design Goal
□ Goto □ Documentation comment
□ Multiple inheritance □ Virtual Keyword
□ Operator Overloading □ unsigned right shift >>>
□ Pointers
□ Inheritance Tree
□ Compiler and Interpreter
□ Hardware
□ Call by Value and Call by reference
□ Object-oriented
JAVA
ENVIRONMENT
□ An Environment variable is a dynamic "object" on a computer that stores a value,
which can be referenced by one or more software programs in Windows.

□ Like for Java, we will set an environment variable with name "java" and its value will
be the path of the /bin directory present in Java directory.

□ So whenever a program will require Java environment, it will look for the java
environment variable which will give it the path to the execution directory.
JAVA
ENVIRONMENT
1. Local Environment Setup
□ Setting Up the Path for Windows

□ Setting Up the Path for Linux, UNIX, Solaris,


FreeBSD

□ Popular Java Editors


TOPICS DISCUSSED IN PREVIOUS
CLASS

How JAVA Differ from C and C++

JAVA Environment
TOPICS TO BE LEARNED FROM
THIS CLASS

Overview of JAVA Language

JAVA Program Structure


OVERVIEW OF JAVA
LANGUAGE
□ VERSIONS
□ WHY JAVA?
□ FEATURES OF JAVA?
□ Introduction to Java
Technology □ DRAWBACKS OF
JAVA?
□ History of Java
OVERVIEW OF JAVA
LANGUAGE
Application
According to Sun, 3 billion devices run Java. There are many devices
where Java is currently used. Some of them are as follows:
1. Desktop Applications such as acrobat reader, media player, antivirus, etc.
2. Enterprise Applications such as banking applications.
3. Mobile
4. Embedded System
5. Smart Card
6. Robotics
7. Games, etc.
OVERVIEW OF JAVA
LANGUAGE
Types of Java Applications
There are mainly 4 types of applications that can be created using Java programming:
1) Standalone Application:
Standalone applications are also known as desktop applications or window-based
applications. These are traditional software that we need to install on every machine.
Examples of standalone application are Media player, antivirus, etc. AWT and Swing
are used in Java for creating standalone applications.

2) Web Application:
An application that runs on the server side and creates a dynamic page is called a web
application. Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF, etc. technologies
are used for creating web applications in Java.
OVERVIEW OF JAVA
LANGUAGE
3) Enterprise Application
An application that is distributed in nature, such as banking applications, etc. is called
enterprise application. It has advantages of the high-level security, load balancing, and
clustering.
In Java, EJB is used for creating enterprise applications.

4) Mobile Application
An application which is created for mobile devices is called a mobile
application. Currently, Android and Java ME are used for creating mobile
applications.
OVERVIEW OF JAVA
LANGUAGE
Java Platforms / Editions
1) Java SE (Java Standard Edition)
It is a Java programming platform. It includes Java programming APIs such as
java.lang, java.io, java.net, java.util, java.sql, java.math etc.
It includes core topics like OOPs, String, Regex, Exception, Inner classes,
Multithreading, I/O Stream, Networking, AWT, Swing, Reflection, Collection, etc.

2) Java EE (Java Enterprise Edition)


It is an enterprise platform which is mainly used to develop web and enterprise
applications. It is built on the top of the Java SE platform. It includes topics like Servlet,
JSP, Web Services, EJB, JPA, etc.
OVERVIEW OF JAVA
LANGUAGE

Java Platforms / Editions

3) Java ME (Java Micro Edition)


It is a micro platform which is mainly used to develop mobile applications.

4) JavaFX
It is used to develop rich internet applications. It uses a light-weight user interface
API.
JAVA Program
Structure

• The requirement for Java Simple Example

□For executing any java program, you need to


□Install the JDK if you don't have installed it, download
and install it.
□Set path of the jdk/bin directory. Create the java
program
□Compile and run the java program
JAVA Program
Structure

class Simple{

public static void main(String

args[])
}
{ System.out.println("Hello
}
ToJava");
compile: javac
Simple.java
To execute: java Simple
JAVA Program
Structure

• Parameters used in First Java Program

• class keyword is used to declare a class in java.

• public keyword is an access modifier which represents visibility. It


means it is visible to all.

• static is a keyword. If we declare any method as static, it is known as


the static method. The core advantage of the static method is that there
is no need to create an object to invoke the static method. The main
method is executed by the JVM, so it doesn't require to create an object
to invoke the main method. So it saves memory.
JAVA Program
Structure
• Parameters used in First Java Program

• void is the return type of the method. It means it doesn't return any
value.

• main represents the starting point of the program.

• String[] args is used for command line argument. We will learn it


later.

• System.out.println() is used to print statement. Here, System is a


class, out is the object of PrintStream class, println() is the method of
PrintStream class. We will learn about the internal working of
System.out.println statement later.
Compilation Flow:

In Java, programs are not compiled into executable files,


they are compiled into bytecode (as discussed earlier), which the JVM
(Java Virtual Machine) then executes at runtime.
Java source code is compiled into bytecode when we use the javac compiler.
Compilation Flow:
When we compile Java program using javac tool, java compiler converts the source
code into byte code.
TOPICS TO BE LEARNED FROM
THIS CLASS

JAVA Tokens

JAVA Statements
What is
token
□ The Java compiler breaks the line of code into text
(words) is called Java tokens.

□ These are the smallest element of the Java program.

□ The Java compiler identified these words as tokens.

□ These tokens are separated by the delimiters.


What is
token
□It is useful for compilers to detect errors.

□ Remember that the delimiters are not part of


the Java tokens.

Tokens can be classified as follows:

1.Keywords

2.Identifiers

3.Constants

4.Special

Symbols
Types of
token
1.Keywords:

Keywords are pre-defined in a programming language. Each keyword is meant


to perform a specific function in a program.

Java language supports following keywords:

01.abstract 02.boolean 03. byte 04. break 05. class

06. case 07. catch 08. char 09. continue 10. default

11. do 12. double 13. else 14. extends 15. final


_

Types of
token
2. Identifiers:

Identifiers are used to name a variable, constant, function, class,


and array. It usually defined by the user. It uses letters,
underscores, or a dollar sign as the first character. The label is also
finown as a special fiind of identifier. Remember that the identifier
name must be different from the reserved fieywords.
Examples of valid identifiers : Examples of invalid identifiers :
MyVariable My Variable // contains a space
MYVARIABLE 123geeks // Begins with a digit
myvariable variable-2 // hyphen is not an alphanumeric
character sum_&_difference // ampersand
myvariable is not an alphanumeric character
$myvariable
_

Types of
token
3.Constants/Literals:

Constants are also like normal variables. But the only difference is, their values
can not be modified by the program once they are defined. Constants refer to
fixed values.

4.Special Symbols or Separator:

The separators in Java is also finown as punctuators. There are nine


separators in Java, are as follows:

separator <= ; | , | . | ( | ) | { | } | [ | ]
_

Types of
token
• Square Bracfiets []: It is used to define array elements. A pair of square
brackets represents the single-dimensional array, two pairs of square
brackets represent the two-dimensional array.

• Parentheses (): It is used to call the functions and parsing the parameters.

• Curly Braces {}: The curly braces denote the starting and ending of a code
block.

• Comma (,): It is used to separate two values, statements, and parameters.

• Assignment Operator (=): It is used to assign a variable and constant.

• Semicolon (;): It is the symbol that can be found at end of the statements.
It separates the two statements.

• Period (.): It separates the package name form the sub-packages and class.
_

Types of
token
5. Operators:

Java provides many types of operators which can be used according to the
need. They are classified based on the functionality they provide.
_

Java Statements

A statement specifies an action in a Java program.


For example, a statement may tell to add a values of x and y and assign
their sum to the variable z. Then it prints a message to the standard
output.

Java statements can be broadly classified into three categories:

1. Declaration statement

2. Expression statement

3. Control flow statement


_

Java Statements

1vDeclaration statement:
A declaration statement is used to declare a
variable.
For example:
int ,

num;
int num2 =
100; String
str;

2v Java Expression Statement:


An expression with a semicolon at the end is called an
expression statement.

For example:
_

Java Statements
/Increment and decrement expressions
num++;
++num;
num--; ,

--num;
/ Assignment expressions num = 100;
num *= 10;
/ Method invocation expressions
Systemvoutvprintln("This is a statement");
_

Java Statements

3. Java Flow Control Statement:


When we want to execute a set of statements repeatedly for a number of times
or as long as a particul, ar condition is truev
The if statementç while loop statement and for loop statement are examples of
control flow statementsv
TOPICS DISCUSSED IN THE
PREVIOUS CLASS

Overview of JAVA Language

JAVA Program Structure


TOPICS TO BE LEARNED FROM
THIS CLASS

JAVA Development Kit

Command Line Arguments


JDK: Java Development Kit

JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a
software development environment which is used to develop java applications and applets.
It physically exists. It contains JRE + development tools.
JDK is an implementation of any one of the below given Java Platforms released by Oracle
corporation:
∙ Standard Edition Java Platform
∙ Enterprise Edition Java Platform
∙ Micro Edition Java Platform
JDK: Java Development Kit

The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an
interpreter/loader (Java), a compiler (javac), an archive (jar), a documentation generator (Javadoc) etc.
to complete the development of a Java Application.
COMPONENTS OF JDK
Following is a list of primary components of
JDK:
appletviewer: This tool is used to run and debug Java applets without a web browser.

The loader for Java applications. This tool is an interpreter and can interpret the class files generated by
java: the javac compiler. Now a single launcher is used for both development and deployment. The old
deployment launcher, jre, no longer comes with Sun JDK, and instead it has been replaced by this new
java loader.
javac: It specifies the Java compiler, which converts source code into Java bytecode.

javadoc: The documentation generator, which automatically generates documentation from source code comments

The specifies the archiver, which packages related class libraries into a single JAR file. This tool also helps
jar:
manage JAR files.
javap: the class file disassembler.
jdb: the debugger.
JAVA VIRTUAL MACHINE
□ JVM (Java Virtual Machine) is an abstract machine. It is a
specification that provides runtime environment in which java
bytecode can be executed.

□ What is JVM

□A specification

□An implementation

□Runtime Instance
JAVA VIRTUAL MACHINE

□ What it
does
□Loads code
□Verifies code
□Executes code
□Provides
runtime
environment
JRE
□The Java Runtime Environment is a set
of software tools which are used for
developing Java applications.

□It is used to provide the


runtime environment.

□It is the implementation of JVM.

□It contains a set of libraries + other


files that JVM uses at runtime.
JVM ARCHITECTURE
JVM
ARCHITECTURE

1. Classloader
Classloader is a subsystem of JVM which is used to load class files. Whenever we run
the java program, it is loaded first by the classloader. There are three built-in class
loaders in Java.

1. Bootstrap Class Loader


2. Extension Class Loader
3. System/Application Class Loader
JVM
ARCHITECTURE
1.Bootstrap Class Loader: This is the first class loader which is the super class of
Extension class loader. It loads the rt.jar file which contains all class files of Java
Standard Edition like java.lang package classes, java.net package classes, java.util
package classes, java.io package classes, java.sql package classes etc.

2.Extension Class Loader: This is the child class loader of Bootstrap and parent class loader of
System class loader. It loaders the jar files located inside $JAVA_HOME/jre/lib/ext
directory.
3.System/Application Class Loader: This is the child class loader of Extension class loader.
It loads the class files from class path. By default, class path is set to current directory.
JVM
ARCHITECTURE
2. Class Area
The area of the memory which holds the statement of currently executing method and
also static data members of classes that are loaded.

3. Heap
The area of the memory which holds the objects created during program run.

4. Stack
The area of the memory which holds local variables of the methods, which is currently
being executed.
It clears up when the execution of method ends.
JVM ARCHITECTURE

5. Program Counter Register


PC (program counter) It keeps track of which instruction is being executed and what the
next instruction will be. Which contains the address of the Java virtual machine instruction
currently being executed.
6. Native Method Stack
It contains all the native methods used in the application.

7. Execution Engine
It contains:
8. A virtual processor
9. Interpreter: Read bytecode stream then execute the instructions.
JVM
ARCHITECTURE
3. Just-In-Time (JIT) compiler: It is used to improve the performance. JIT compiles parts of
the byte code that have similar functionality at the same time, and hence reduces the
amount of time needed for compilation. Here, the term "compiler" refers to a translator
from the instruction set of a Java virtual machine (JVM) to the instruction set of a specific
CPU.

8. NativeMethod Interface
Java Native Interface (JNI) is a framework which provides an interface to communicate
with another application written in another language like C, C++, and Assembly etc.
Java uses JNI framework to send output to the Console or interact with OS libraries.
JAVA COMMAND LINE ARGUMENTS

□ The java command-line argument is an argument i.e. passed at


the time of running the java program.

□ The arguments passed from the console can be received in


the java program and it can be used as an input.

□ it provides a convenient way to check the behavior of the


program for the different values. You can pass N (1,2,3 and so
on) numbers of arguments from the command prompt.
JAVA COMMAND LINE ARGUMENTS

class CommandLineExample{

public static void main(String args[])

{ System.out.println("Your first argument is:

"+args[0]);

}
TOPICS TO BE LEARNED FROM
THIS CLASS

Data types

Variables and Constants


DATA TYPES IN JAVA

□ Data types specify the different sizes and values that


can be stored in the variable.

□ There are two types of data types in Java:

□Primitive data types: The primitive data types include boolean, char, byte, short,
int, long, float and double.

□Non-primitive data types: The non-primitive data types include Classes,


Interfaces, and Arrays.
DATA TYPES IN JAVA

PRIMITIVE DATA TYPES


□ Primitive data types are the building blocks of data
manipulation.

□ There are 8 types of primitive data types:


• boolean data type
• byte data type
• char data type
• short data type
• int data type
• long data type
• Float data type
• Double data type
DATA TYPES IN JAVA

PRIMITIVE DATA TYPES


DATA TYPES IN JAVA

PRIMITIVE DATA TYPES


Data Type Default Value Default size
boolean false 1 bit
char '\u0000' 2 byte
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
float 0.0f 4 byte
double 0.0d 8 byte
Java Variables

□ A variable is a container which holds the value while the Java


program is executed.
□ A variable is assigned with a data type.
□ Variable is a name of memory location.

□ There are three types of variables in

java: local,

instanc

static.
Variable

□ Variable is name of reserved area allocated in memory.


□ It is a combination of "vary + able" that means its value can be changed
Types of Variables

□ There are three types of variables in


Java

• local variable

• instance variable

• static variable
1) Local Variable

A variable defined within a block or method or constructor is called local variable.


∙ These variable are created when the block in entered or the function is called
and destroyed after exiting from the block or when the call returns from the
function.
∙ The scope of these variables exists only within the block in which the variable is declared.
i.e. we can access these variable only within that block.

∙Initialization of Local Variable is Mandatory.

Class Employee {
public static void main(String args[]){

Int companyId=1001; //local variable


2) Instance Variable

Instance variables are non-static variables and are declared in a class


outside any method, constructor or block.
∙ As instance variables are declared in a class, these variables are
created when an object of the class is created and destroyed when
the object is destroyed.
∙ Unlike local variables, we may use access specifiers for instance
variables. If we do not specify any access specifier then the default
access specifier will be used.
∙ Initialization of Instance Variable is not Mandatory. Its default value
is 0
∙Instance Variable can be accessed only by creating objects.
Class Employee {
private int companyId; // instance variable

public static void main(String args[])

{ Employee e1=new Employee();

System.out.println(e1.companyId);
}
}
3) Static variable

Static variables are also known as Class variables.


∙ These variables are declared similarly as instance variables, the difference is that static
variables are declared using the static keyword within a class outside any method
constructor or block.
∙ Unlike instance variables, we can only have one copy of a static variable per class
irrespective of how many objects we create.
∙ Static variables are created at the start of program execution and
destroyed automatically when execution ends.
∙ Initialization of Static Variable is not Mandatory. Its default value is 0
∙ If we access the static variable like Instance variable (through an object), the
compiler will show the warning message and it won’t halt the program. The
compiler will replace the object name to class name automatically.
∙ If we access the static variable without the class name, Compiler will
automatically append the class name.
To access static variables, we need not create an object of that class, we can simply
access the variable as
class_name.variable_name;
Class Employee {
static int companyId=1001; // static
variable

public static void main(String args[])

{ Employee e1=new Employee();

System.out.println(e1.companyID);
}
}
Constants in
JAVA

□ A constant is a variable whose value cannot change once it has


been

assigned. Java doesn't have built-in support for constants.

□ To define a variable as a constant, we just need to add the

keyword “final” in front of the variable declaration.

□ Syntax:

final float pi = 3.14f;


TOPICS TO BE LEARNED FROM
THIS CLASS

Scope of variables

Type Casting
SCOPE OF VARIABLES Example
public class Test
□ Scope of a variable is the part {
// All variables defined directly inside
of the program where the a class
variable is accessible.
int a;
□ Java programs are organized in private String b
the form of classes. void method1()
□ Member Variables (Class {....}
int method2()
Level Scope)
□These variables must be declared inside
} {....} char c;
class (outside any function).
□They can be directly accessed anywhere in
class.
SCOPE OF VARIABLES
Modifier Package Subclass World
□ We can declare class
variables anywhere in public Yes Yes Yes

class, but outside


protected Yes Yes No
methods.

□ Access specified of member Default Yes No No


(no
variables doesn’t effect scope of modifier)
them within a class. private No No No

□ Member variables can be


accessed outside a class with
following rules
SCOPE OF VARIABLES
Local Variables (Method Level Scope)
□ Variables declared inside a method
have method level scope and can’t Example
be accessed outside the method. public class Test
{
□ Local variables don’t exist after void method1()
method’s execution is over. {
Loop Variables (Block Scope) // Local variable (Method level
scope)
□ A variable declared inside pair of int x;
brackets “{” and “}” in a method has }
scope withing the brackets only. }
TYPE CASTING

□ Casting is a process of changing one type value to


another type.

Type conversion in Java

□ Widening or Automatic Type Conversion

□ Narrowing or Explicit Conversion


TYPE CASTING
Example
Widening or Automatic Type class Test
Conversion
□ Widening conversion takes place when
{ public static void main(String[] args)
two
{
data types are automatically converted.
int i = 100;
□ This happens when: // automatic type conversion
□ The two data types are compatible. long l = i;
// automatic type conversion
□ When we assign value of a smaller data
type to a bigger data type. System.out.println("Int value "+i);
System.out.println("Long value "+l);

}
}
TYPE CASTING
Narrowing or Explicit Conversion
class Test
{
□ If we want to assign a value of larger data public static void main(String[]
type to a smaller data type we perform args)
{
explicit type casting or narrowing double d = 100.04;
□ This is useful for incompatible data types where //explicit type
automatic conversion cannot be done. casting long l =
(long)d;
□ Here, target-type specifies the desired type System.out.println("Double value
to convert the specified value to. "+d);
}
}
TOPICS TO BE LEARNED FROM
THIS CLASS

Operators in JAVA
OPERATORS IN JAVA

□ Operator in Java is a symbol which is used to


perform operations. For example: +, -, *, / etc.
□ There are many types of operators in Java which
are given below:
1. Unary Operator,
5. Bitwise Operator,
2. Arithmetic
6. Logical Operator,
Operator,
3. Shift Operator, 7. Ternary Operator
and
4. Relational
Operator, 8. Assignment
Operator.
Java Operator Precedence
Operator Type Category Precedence
postfix expr++ expr--
Unary
prefix ++expr --expr +expr -expr ~ !
multiplicative */%
Arithmetic
additive +-
Shift shift << >> >>>
comparison < > <= >= instanceof
Relational
equality == !=
bitwise AND &
Bitwise bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
Logical
logical OR ||
Ternary ternary ?:
Assignment assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=
JAVA UNARY
OPERATOR
class OperatorExample{
□ The Java unary operators
public static void main(String args[]
require only one operand. ){
int x=10; System.out.println(x++);//10 (11)
Unary operators are used to System.out.println(++x);//12 System.out.println(x--);//12
(11) System.out.println(--x);//10
perform various operations
}}
i.e.:
□ incrementing/decrementing a value by
one
□ negating an expression
□ inverting the value of a boolean
JAVA ARITHMETIC OPERATORS

□ Java arithmatic class OperatorExample{


public static void main(String
operators are used to
args[]){ int a=10;
perform addition, int b=5;
subtraction, System.out.println(a+b);
//15
multiplication, and System.out.println(a-
division. They act as b);//5
System.out.println(a*b);/
basic mathematical
/50
operations. System.out.println(a/b);//
2 System.out.println(a
%b);//0
JAVA LEFT SHIFT OPERATOR

□ The Java left shift class OperatorExample{


operator public static void main(String args[])
<< is used to shift all {
of the bits in a value to System.out.println(10<<2);//10*2^2=10
the left side of a *4=40
specified number of System.out.println(10<<3);//10*2^3=10

times. *8=80
System.out.println(20<<2);//20*2^2=20
*4=80
System.out.println(15<<4);//
JAVA SHIFT OPERATOR EXAMPLE: >> VS
>>>
class OperatorExample{
public static void main(String args[]){
//For positive number, >> and >>>
works same
System.out.println(20>>2);
System.out.println(20>>>2);
//For negative number, >>> changes parity bit
(MSB) to 0 System.out.println(-20>>2);
System.out.println(-20>>>2);
}}
LOGICAL && AND BITWISE &
class OperatorExample{
□ The logical && operator
public static void main(String
doesn't check second
args[]){ int a=10;
condition if first
int
condition is false.
b=5;
□ It checks second int
condition only if first c=20;
one is true. System.out.println(a<b&&a<c);//false &&
true = false
□ The bitwise & System.out.println(a<b&a<c);//false &
true = fa lse
operator always
}}
checks both
conditions whether
LOGICAL || AND
BITWISE | class OperatorExample{
□ The logical || operator public static void main(String
doesn't check second args[]){ int a=10;
condition if first int

condition is true. It b=5;


int
checks second
c=20;
condition only if first one System.out.println(a>b||a<c);//true ||
is false. true = true System.out.println(a>b|
a<c);//true | true = true
□ The bitwise | operator
//|| vs |
always checks both System.out.println(a>b||a++<c);//true || true = true
conditions whether System.out.println(a);//10 because second condition is
first condition is true not checked System.out.println(a>b|a++<c);//true |

or false. true = true System.out.println(a);//11 because second


JAVA TERNARY OPERATOR

class OperatorExample{
□ Java Ternary operator is
public static void main(String
used as one liner
replacement for args[]){ int a=10;
if-then-else statement and int b=5;
used a lot in Java int min=(a<b)?a:b;
programming. System.out.println(m
in);
□ it is the only conditional
}}
operator which takes three
operands.
JAVA ASSIGNMENT
OPERATOR
□ Java assignment class OperatorExample{
public static void main(String[]
operator is one of the args){ int a=10;
a+=3;//10+3
most common operator.
System.out.println(
a); a-=4;//13-4
□ It is used to assign the System.out.println(
value on its right to the a); a*=2;//9*2
System.out.println(
operand on its left. a); a/=2;//18/2
System.out.println(
a);
}}
TOPICS TO BE LEARNED FROM
THIS CLASS

Expressions
EXPRESSIO
NS
□ We have understood variables and operators,
statements.

□ It's time to learn about expressions, and blocks.

□ Operators may be used in building expressions, which


compute values;

□ Expressions are the core components of statements;

□ Statements may be grouped into blocks.


Expressions

□ An expression is a construct int cadence = 0;


made up of variables, anArray[0] = 100;
operators, and method System.out.println("Element 1 at index
invocations, which are 0: " + anArray[0]);
constructed according to the int result = 1 + 2; // result is now 3
syntax of the language, that if (value1 == value2)
evaluates to a single value. System.out.println("value1 == value2");
□ The data type of the value
returned by an expression
depends on the elements
used in the expression.
ARITHMETIC EXPRESSIONS

class example
□ An assignment statement or {
public static void main ( String[] args )
expression changes the value
{
that is held in a variable. long x ; //a declaration without an
□ Here is a program that uses an initial value
x = 123; //an assignment statement
assignment statement:
System.out.println("The variable
x contains: " + x );
}
}
ARITHMETIC EXPRESSIONS

□ Java Arithmetic expressions use int x, y, z; // Three integer variables declared at the same time.
arithmetic operators such as +, -, /, x = 10;
*, and %. y = 12;
z = y / x; // z is assigned the value of y divided by x.
□ The % operator is the remainder // Here z will have value 1.
or modulo operator. z = x + y; // z is assigned the value of x+y
□assign
Arithmetic expressions
arithmetic arevariables.
values to used to Here z will have value 22.
z = y % x // z is assigned the value of remainder when y
□ An expression is a
combination of literals,
operators, variables, and
parentheses used to calculate a
value.
TOPICS TO BE LEARNED FROM
THIS CLASS

Java operator associativity

Mathematical Functions
JAVA OPERATOR ASSOCIATIVITY
Operator Type Category Precedence Associativity
postfix expr++ expr-- Left to Right
Unary
prefix ++expr --expr +expr -expr ~ ! Left to Right
multiplicative */% Left to Right
Arithmetic
additive +- Left to Right
Shift shift << >> >>> Left to Right
comparison < > <= >= instanceof Left to Right
Relational
equality == != Left to Right
bitwise AND & Left to Right
Bitwise bitwise exclusive OR ^ Left to Right
bitwise inclusive OR | Left to Right
logical AND && Left to Right
Logical
logical OR || Left to Right
Ternary ternary ?: Left to Right
= += -= *= /= %= &= ^= |= <<=
Assignment assignment >>= >>>= Left to Right
Java Math
class

□ Java Math class provides several methods to work on math calculations


like min(), max(), avg(), sin(), cos(), tan(), round(), ceil(), floor(), abs()
etc.
□ If the size is int or long and the results overflow the range of value, the
methods addExact(), subtractExact(), multiplyExact(), and toIntExact()
throw
an ArithmeticException.
□ For other arithmetic operations like increment, decrement, divide,
absolute value, and negation overflow occur only with a specific
minimum or maximum value. It should be checked against the
maximum and minimum value as appropriate.
□ Example Program
TOPICS TO BE LEARNED FROM
THIS CLASS

Decision Making

Branching
DECISION MAKING
□ Decision making structures
have one
or more conditions to be
evaluated or tested by the
program, along with a statement
or statements that are to be
executed if the condition is
determined to be true, and
optionally, other statements to
Decision
Making
Decision
Making
Java if
Statement
□ The Java if statement is used to test the condition.
It checks boolean condition: true or false. There
are various types of if statement in Java.
if statement
if-else statement
if-else-if ladder
nested if statement
□ The Java if statement tests the condition. It executes the
if block if condition is true.
Syntax:
if(condition){
//code to be executed
}

Example Program
Java 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
}

Example Program
Using Ternary
Operator
□ We can also use ternary operator (? :) to public class IfElseTernaryExample
perform the task of if...else statement. It { public static void main(String[]
is a shorthand way to check the args) {
condition. If the condition is true, the
result of ? is returned. But, if the int number=13;
condition is false, the result of : is //Using ternary operator
returned. String output=(number
%2==0)?"eve n number":"odd
number";
System.out.println(output);
}
}
Java if-else-if ladder
Statement
□ The if-else-if ladder statement executes one n
conditio 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
}
Example Program
Java Nested if
statement
□ The nested if statement represents the
if block within another if block. Here,
the inner 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
}
}
□ Example Program

You might also like