0% found this document useful (0 votes)
5 views89 pages

JAVA Unit - 1

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
5 views89 pages

JAVA Unit - 1

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 89

What is Java

 Java is a powerful general-purpose programming language.

 It is a high-level programming language originally developed by Sun Microsystems and released

in 1995.

 Java is a, robust, object-oriented and secure programming language.

 It is used to develop desktop and mobile applications, big data processing, embedded systems.

 James Gosling is known as the father of Java.

 Before Java, its name was Oak.

 Later changed the name from Oak to Java.


History

 Java was originally designed for interactive television, but it was too advanced technology for the
digital cable television industry at the time.

 Java team members, initiated this project to develop a language for digital devices such as set-top
boxes, televisions, etc.

 Currently, Java is used in internet programming, mobile devices, games, e-business solutions, etc.

 Initially it was designed for small, embedded systems in electronic appliances like set-top boxes.

 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.
Why Use Java?

 Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.)

 It is one of the most popular programming language in the world

 It is easy to learn and simple to use

 It is open-source and free

 It is secure, fast and powerful

 It has a huge community support (tens of millions of developers)

 Java is an object oriented language which gives a clear structure to programs and allows code to
be reused, lowering development costs

 As Java is close to C++ and C#, it makes it easy for programmers to switch to Java or vice versa
Features
 The primary objective of Java programming language creation was to make it portable, simple and

secure programming language

 features of Java are also known as Java buzzwords.

1. Simple 7. Secured

2. Object-Oriented 8. Architecture neutral

3. Portable 9. Robust

4. Platform independent 10. High Performance

5. Interpreted 11. Multithreaded

6. Distributed 12. Dynamic


Simple:

 Java is very easy to learn, and its syntax is simple, clean and easy to understand.

 Java has removed many complicated and rarely-used features, for example, explicit pointers,
operator overloading, etc.

 There is no need to remove unreferenced objects because there is an Automatic Garbage


Collection in Java.

Object-oriented:

 Java is an object-oriented programming language. Everything in Java is an object.

 Object-oriented programming (OOPs) is a methodology that simplifies software development and


maintenance by providing some rules.
Platform Independent:

 Java is platform independent because it is different from other languages. Java is a write once,
run anywhere language.

 The Java platform differs from most other platforms in the sense that it is a software-based
platform that runs on top of other hardware-based platforms.

 It has two components:

 Runtime Environment

 API(Application Programming Interface)

 Java code is compiled by the compiler and converted into bytecode.

 This bytecode is a platform-independent code because it can be run on multiple platforms, i.e.,
Write Once and Run Anywhere (WORA).
Secured:

Java is best known for its security. With Java, we can develop virus-free systems. Java is
secured because:

 Java supports access modifiers to check memory access

 No explicit pointer

 Java Programs run inside a virtual machine sandbox-A separate environment that allows users
to execute their applications without affecting the underlying system.

 It has a bytecode verifier that checks the code fragments for any illegal code that violates the
access right.
Robust:

Java is robust because:

 It uses strong memory management.

 There is a lack of pointers that avoids security problems.

 Java provides automatic garbage collection which runs on the Java Virtual Machine to get rid of
objects which are not being used by a Java application anymore.

 There are exception handling and the type checking mechanism in Java. All these points make
Java robust.
Architecture-neutral:
 Java is architecture neutral because there are no implementation dependent features, for example,
the size of primitive types is fixed.
 In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes of
memory for 64-bit architecture.
 However, it occupies 4 bytes of memory for both 32 and 64-bit architectures in Java.

Portable:
 Java is portable because it facilitates you to carry the Java bytecode to any platform.
 It doesn't require any implementation.
High-performance:
 Java is faster than other traditional interpreted programming languages because Java bytecode is
"close" to native code.
 It is still a little bit slower than a compiled language (e.g., C++).
 Java is an interpreted language that is why it is slower than compiled languages, e.g., C, C++, etc.
Dynamic:
 Java is a dynamic language. It supports the dynamic loading of classes.
 It means classes are loaded on demand.
 It also supports functions from its native languages, i.e., C and C++.
Distributed:
 Java is distributed because it facilitates users to create distributed applications in Java.

 RMI and EJB are used for creating distributed applications.

 This feature of Java makes us able to access files by calling the methods from any machine on the

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 doesn't occupy memory for each thread. It shares a

common memory area.


 Threads are important for multi-media, Web applications, etc.

 Java supports dynamic compilation and automatic memory management (garbage collection).
Java OOPs Concepts
 Object-oriented programming is a method used for designing a program using classes and objects.
Object-oriented programming is also called the core of java.

 Object-oriented programming organizes a program around objects and well-defined interfaces.

 In this type of approach, programmers define the data type of a data structure and the operations
that are applied to the data structure.

some of the concepts:


 Object
 Class
 Abstraction
 Inheritance
 Polymorphism
 Encapsulation
Object:

 Any entity that has state and behaviour is known as an object.

 For example, a chair, pen, table, keyboard, bike, etc. It can be physical or logical.

 An Object can be defined as an instance of a class.

 An object contains an address and takes up some space in memory.

 Objects can communicate without knowing the details of each other's data or code.

 The only necessary thing is the type of message accepted and the type of response returned by the
objects.

 Example: A dog is an object because it has states like color, name, breed, etc. as well as behaviours
like wagging the tail, barking, eating, etc.
Class:

 Collection of objects is called class. It is a logical entity.

 A class can also be defined as a blueprint from which you can create an individual object. Class doesn't
consume any space.

 It represents the set of properties or methods that are common to all objects of one type.

In general, class declarations can include these components:

 Modifiers: A class can be public or has default access.

 Class name: The name should begin with a Capital letter.

 Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the keyword extends. A
class can only extend (subclass) one parent.

 Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any, preceded by the
keyword implements. A class can implement more than one interface.

 Body: The class body surrounded by braces, { }.


Inheritance

Inheritance is an important pillar of OOP. It is the mechanism in java by which one class is
allow to inherit the features(fields and methods) of another class.

some of important terminologies:

 Super Class: The class whose features are inherited is known as superclass(or a base class or a parent
class).

 Sub Class: The class that inherits the other class is known as subclass(or a derived class, extended
class, or child class). The subclass can add its own fields and methods in addition to the superclass
fields and methods.

 Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new
class and there is already a class that includes some of the code that we want, we can derive our new
class from the existing class. By doing this, we are reusing the fields and methods of the existing
class.
Polymorphism:

 If one task is performed in different ways, it is known as polymorphism.

 For example: to convince the customer differently, to draw something, for example, shape,

triangle, rectangle, etc.

 In Java, we use method overloading and method overriding to achieve polymorphism.

Abstraction:

 Hiding internal details and showing functionality is known as abstraction.

 For example phone call, we don't know the internal processing.


Encapsulation:

 Binding (or wrapping) code and data together into a single unit are known as encapsulation. For
example, a capsule, it is wrapped with different medicines.

 Technically in encapsulation, the variables or data of a class is hidden from any other class and can
be accessed only through any member function of own class in which they are declared.

 As in encapsulation, the data in a class is hidden from other classes, so it is also known as data-
hiding.

 Encapsulation can be achieved by Declaring all the variables in the class as private and writing
public methods in the class to set and get the values of variables.
Java Development Kit
 The Java Development Kit (JDK) is a cross-platformed software development environment that
offers a collection of tools and libraries necessary for developing Java-based software applications
and applets

 It includes the JVM, compiler, debugger and other tools for developing Java applets and
applications.

The JDK supplies two primary programs :

 The first is javac , which is the java compiler .It converts our source code into byte code

 The second is java, Sometimes referred to as the application launcher, this is the program we will
use to run a Java program.

 It operates on the byte code, using the JVM to execute your program.
Hello World Example

class Simple

public static void main(String args[])

System.out.println("Hello World");

To compile:

javac Simple.java

To execute:

java Simple
Parameters used

 class keyword is used to declare a class in Java.

 public keyword is an access modifier that 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 creating an object to invoke the
main() method. So, it saves memory.

 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 or String args[] is used for command line argument.

 System.out.println() is used to print statement.

 Here, System is a class, out is an object of the PrintStream class, println() is a method of the
PrintStream class.
Create blocks of code
 Program code in a Java program is contained in a block.

 A block in Java is a group of one or more statements enclosed in braces. A block begins with an
open curly brace ({) symbol and ends with a close curly brace (}) symbol.

 Between the opening and closing braces, you can code one or more statements.

int i, j; i = 100; j = 200;

 Even though a block can be treated as a single statement, you should not end a block with a
semicolon.

 The statements within the block may require semicolons, but the block itself does not.
Java keywords
 Java keywords are also known as reserved words.
 Keywords are particular words that act as a key to a code.
 These are predefined words by Java so they cannot be used as a variable or object name or
class name.
Identifiers
 An identifier is nothing but a name assigned to an element in a program.

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

 However, In Java, There are some reserved words that can not be used as an identifier.
From the example, we have the following Java
identifiers:

 HelloJava (Class name)

 main (main method)

 String (Predefined Class name)

 args (String variables)

 System (Predefined class)

 out (Variable name)

 println (method)
Rules for Identifiers in Java
 A valid identifier must have characters [A-Z] or [a-z] or numbers [0-9], and underscore(_) or a dollar
sign ($). for example, @abc is not a valid identifier because it contains a special character which is @.

 There should not be any space in an identifier. For example, java class is an invalid identifier.

 An identifier should not contain a number at the starting. For example, 123javaclass 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.
java class libraries

 java programming, main two features are supported that is class and object. Basically we know
that class is collection of objects and object is an instance of class.

 java programming supports different type of classes as User defines class.

 And also there are some classes available with java system that provide some important support to
the java programmer for developing their programming logic as well as their programming
architecture with very smooth way.

 These classes are called Library Classes


List of Library Classes in Java

Library classes Purpose of the class


Java.io Use for input and output functions.
Java.lang Use for character and string operation.
Java.awt Use for windows interface.
Java.util Use for develop utility programming.
Java.applet Use for applet.
Java.net Used for network communication.
Java.math Used for various mathematical calculations like power, square root etc.
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.
Primitive Data Types:

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


Boolean Data Type:
 The Boolean data type is used to store only two possible values: true and false.
 This data type is used for simple flags that track true/false conditions.
 The Boolean data type specifies one bit of information.
Example:
Boolean one = false
Byte Data Type:
 The byte data type is an example of primitive data type.
 It is an 8-bit signed two's complement integer.
 Its value-range lies between -128 to 127 (inclusive).
 Its minimum value is -128 and maximum value is 127. Its default value is 0.
 It saves space because a byte is 4 times smaller than an integer. It can also be used in place of "int"
data type.
Example:
byte a = 10, byte b = -20
Short Data Type:
 The short data type is a 16-bit signed two's complement integer.
 Its value-range lies between -32,768 to 32,767 (inclusive).
 Its minimum value is -32,768 and maximum value is 32,767. Its default value is 0.
 The short data type can also be used to save memory just like byte data type.
 A short data type is 2 times smaller than an integer.
Example:
short s = 10000, short r = -5000
Int Data Type:
 The int data type is a 32-bit signed two's complement integer.
 Its value-range lies between - 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive).
 Its minimum value is - 2,147,483,648and maximum value is 2,147,483,647. Its default value is 0.
 The int data type is generally used as a default data type for integral values unless if there is no
problem about memory.
Example:
int a = 100000, int b = -200000
Long Data Type:
 The long data type is a 64-bit two's complement integer.
 Its value-range lies between -9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807 (2^63
-1)(inclusive).
 Its minimum value is - 9,223,372,036,854,775,808 and maximum value is
9,223,372,036,854,775,807.
 Its default value is 0. The long data type is used when you need a range of values more than those
provided by int.
Example:
long a = 100000L, long b = -200000L
Float Data Type:
 The float data type is a single-precision 32-bit IEEE 754 floating point.
 Its value range is unlimited. It is recommended to use a float (instead of double) if you need to save
memory in large arrays of floating point numbers.
 The float data type should never be used for precise values, such as currency. Its default value is 0.0F.
Example:
float f1 = 234.5f
Double Data Type:
 The double data type is a double-precision 64-bit IEEE 754 floating point.
 Its value range is unlimited. The double data type is generally used for decimal values just like
float.
 The double data type also should never be used for precise values, such as currency. Its default
value is 0.0d.
Example:
double d1 = 12.3
Char Data Type:
 The char data type is a single 16-bit Unicode character.
 Its value-range lies between '\u0000' (or 0) to '\uffff' (or 65,535 inclusive).
 The char data type is used to store characters.
Example:
char letterA = 'A'
Literals

 literals are the constant values that appear directly in the program. It can be assigned directly to a
variable. Java has various types of literals.

Types of Literals:

There are the majorly four types of literals in Java:

 Integer Literal

 Character Literal

 Boolean Literal

 String Literal
Integer Literals

Integer literals are sequences of digits. There are three types of integer literals:

 Decimal Integer: These are the set of numbers that consist of digits from 0 to 9. It may have a
positive (+) or negative (-). For example, 5678, +657, -89, etc.

int decVal = 26;

 Octal Integer: It is a combination of number have digits from 0 to 7 with a leading 0. For example,
045, 026,

int octVal = 067;

 Hexa-Decimal: The sequence of digits preceded by 0x or 0X is considered as hexadecimal


integers. It may also include a character from a to f or A to F that represents numbers from 10 to
15, respectively. For example, 0xd, 0xf,

int hexVal = 0x1a;


Character Literals:

 A character literal is expressed as a character or an escape sequence, enclosed in a single quote ('')
mark. It is always a type of char.

 For example, 'a', '%', '\u000d', etc.

String Literals:

 String literal is a sequence of characters that is enclosed between double quotes ("") marks.

 It may be alphabet, numbers, special characters, blank space, etc.

 For example, "Jack", "12345", "\n", etc.

Boolean Literals:

 Boolean literals are the value that is either true or false. It may also have values 0 and 1.

 For example, true, 0, etc.

boolean isEven = true;


Variables

 A variable is a name given to a memory location. It is the basic unit of storage in a program.

 The value stored in a variable can be changed during program execution.

 A variable is only a name given to a memory location, all the operations done on the variable
effects that memory location.

 In Java, all the variables must be declared before use.

 There are three types of variables in java: local, instance and static.

Declaring (Creating) Variables:

type variable = value;


Local Variable:

 A variable declared inside the body of the method is called local variable.

 You can use this variable only within that method and the other methods in the class aren't even
aware that the variable exists.

 A local variable cannot be defined with "static" keyword.

 Scope of a local variable is within the block in which it is declared and the lifetime of a local variable
is until the control leaves the block in which it is declared.

Instance Variable:

 A variable declared inside the class but outside the body of the method, is called an instance variable.
It is not declared as static.

 these variables are created when an object of the class is created and destroyed when the object is
destroyed. The general scope of an instance variable is throughout the class except in static methods
Static variable:

 A variable that is declared as static is called a static variable.

 It cannot be local. You can create a single copy of the static variable and share it among all the
instances of the class.

 Memory allocation for static variables happens only once when the class is loaded in the memory.

 The general scope of a class variable is throughout the class and the lifetime of a class variable is
until the end of the program or as long as the class is loaded in memory.
public class A

static int m=100;//static variable

int data=50;//instance variable

void method()

int n=90;//local variable

public static void main(String args[])

}//end of class
Operators
Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.

There are many types of operators:

 Unary Operator,

 Arithmetic Operator,

 Shift Operator,

 Relational Operator,

 Bitwise Operator,

 Logical Operator,

 Ternary Operator and

 Assignment Operator.
Unary Operator

 unary operators require only one operand. Unary operators are used to perform various operations
i.e. Operator Meaning

 incrementing/decrementing a value by one Unary plus: not


+ necessary to use since
numbers are positive
 negating an expression without using it

- Unary minus: inverts the


 inverting the value of a boolean sign of an expression

++ Increment operator:
increments value by 1

-- Decrement operator:
decrements value by 1

Logical complement
! operator: inverts the
value of a boolean
Example

public class OperatorExample{

public static void main(String args[]){

int x=10;

System.out.println(x++);//10 (11)

System.out.println(++x);//12

System.out.println(x--);//12 (11)

System.out.println(--x);//10

}
Arithmetic Operators
 Arithmetic operators are used to perform addition, subtraction, multiplication, and division.
 They act as basic mathematical operations.

Operator Operation

+ Addition

- Subtraction

* Multiplication

/ Division

Modulo Operation (Remainder after


%
division)
Example:

public class OperatorExample{

public static void main(String args[]){

int a=10; int b=5;

System.out.println(a+b);//15

System.out.println(a-b);//5

System.out.println(a*b);//50

System.out.println(a/b);//2

System.out.println(a%b);//0

}}
Shift Operators
 Java left shift operator << is used to shift all of the bits in a value to the left side of a specified
number of times.

 Java right shift operator >> is used to move the value of the left operand to right by the number of
bits specified by the right operand.

Example:

public class OperatorExample{

public static void main(String args[]){

System.out.println(10<<2);//10*2^2=10*4=40

System.out.println(10>>2);//10/2^2=10/4=2

}}
Relational Operators

Relational operators are used to check the relationship between two operands

Operator Description Example

== Is Equal To 3 == 5 returns false

!= Not Equal To 3 != 5 returns true

> Greater Than 3 > 5 returns false

< Less Than 3 < 5 returns true

>= Greater Than or Equal To 3 >= 5 returns false

<= Less Than or Equal To 3 <= 5 returns true


public class RelationalOperators {

public static void main(String[] args) {

int a = 10;
int b = 20;

System.out.println(a == b);
System.out.println(a != b);
System.out.println(a > b);
System.out.println(a < b);
System.out.println(a >= b);
System.out.println(a <= b);
}}
Bitwise operators
 Bitwise operator works on bits and performs the bit-by-bit operation.

 They can be used with any of the integral types (char, short, int, etc).

 Assume if a = 60 and b = 13; now in binary format they will be as follows −

a = 0011 1100

b = 0000 1101

 a&b = 0000 1100

 a|b = 0011 1101

 a^b = 0011 0001

 ~a = 1100 0011
public class operators {

public static void main(String[] args)

int a = 5;

int b = 7;

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

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

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

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

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

} }
Assignment Operators
Assignment operators are used in Java to assign values to variables:

Operator Example Equivalent to

= a = b; a = b;

+= a += b; a = a + b;

-= a -= b; a = a - b;

*= a *= b; a = a * b;

/= a /= b; a = a / b;

%= a %= b; a = a % b;
class Main {

public static void main(String[] args) {

int a = 4;

int var;

var = a;

System.out.println("var using =: " + var);

var += a;

System.out.println("var using +=: " + var);

var *= a;

System.out.println("var using *=: " + var);

} }
Logical Operators
Logical operators are used to check whether an expression is true or false. They are used in decision
making.

Operator Example Meaning

true only if both


expression1 &&
&& (Logical AND) expression2 expression1 and
expression2 are true

true if either
|| (Logical OR) expression1 || expression1 or
expression2
expression2 is true

! (Logical NOT) !expression true if expression is false


and vice versa
class Main {

public static void main(String[] args) {

System.out.println((5 > 3) && (8 > 5)); // true

System.out.println((5 > 3) && (8 < 5)); // false

System.out.println((5 < 3) || (8 > 5)); // true

System.out.println((5 > 3) || (8 < 5)); // true

System.out.println((5 < 3) || (8 < 5)); // false

System.out.println(!(5 == 3)); // true

System.out.println(!(5 > 3)); // false

}
Ternary Operator
 The ternary operator (conditional operator) is shorthand for the if-then-else statement. For
example,
variable = Expression ? expression1 : expression2
 If the Expression is true, expression1 is assigned to the variable.
 If the Expression is false, expression2 is assigned to the variable.
Example:
class Java {
public static void main(String[] args) {
int februaryDays = 29;
String result;
result = (februaryDays == 28) ? "Not a leap year" : "Leap year";
System.out.println(result);
} }
Type Casting/type conversion

 When you assign a value of one data type to another, the two types might not be compatible with
each other.

 Converting one primitive datatype into another is known as type casting (type conversion).

 Can be done in both ways manually and automatically.

Types of Type Casting:

 Widening Type Casting

 Narrowing Type Casting


Widening Type Casting:

 Converting a lower data type into a higher one is called widening type casting.

 It is also known as implicit conversion or casting down.

 It is done automatically. It is safe because there is no chance to lose data.

It takes place when:

 Both data types must be compatible with each other.

 The target type must be larger than the source type.

byte -> short -> char -> int -> long -> float -> double
public class Main1 {

public static void main(String[] args) {

int m = 9;

double n = m;

System.out.println(m);

System.out.println(n);

}
Narrowing Type Casting

 Converting a higher data type into a lower one is called narrowing type casting.

 It is also known as explicit conversion or casting up.

 It is done manually by the programmer.

 If we do not perform casting then the compiler reports a compile-time error.

double -> float -> long -> int -> char -> short -> byte
public class Main1 {

public static void main(String[] args) {

double m = 9.0;

int n = (int) m;

System.out.println(m);

System.out.println(n);

}
Operators Precedence and Associativity

 When more than one operator has to be evaluated in an expression Java interpreter has to decide
which operator should be evaluated first.

 Java makes this decision on the basis of the precedence and the associativity of the operators.

 The operator precedence is responsible for evaluating the expressions

 There are certain rules defined in Java to specify the order in which the operators in an expression
are evaluated.

 In Java, parentheses() and Array subscript[] have the highest precedence in Java.

 Java operators have two properties those are precedence, and associativity.
 Precedence is the priority order of an operator, if there are two or more operators in an expression
then the operator of highest priority will be executed first then higher, and then high.

 For example, x + y * z is treated as x + (y * z), whereas x * y + z is treated as (x * y) + z because *


operator has highest precedence in comparison of + operator.

 Associativity is a concept related to the operators applied when two operators with the same
precedence come in an expression.

 Suppose we have an expression a + b - c (+ and - operators have the same priority), and this
expression will be treated as ((a + b) - c) because these operators are left to right-associative.
Operators Precedence Associativity

postfix increment and decrement ++ -- left to right

prefix increment and decrement, and


++ -- + - ~ ! right to left
unary
multiplicative */% left to right
additive +- left to right
shift << >> >>> left to right
relational < > <= >= instanceof left to right
equality == != left to right
bitwise AND & left to right
bitwise exclusive OR ^ left to right

bitwise inclusive OR | left to right


logical AND && left to right
logical OR || left to right
ternary ?: right to left

= += -= *= /= %=
assignment right to left
&= ^= |= <<= >>= >>>=
Example:

Expression: x = 4 / 2 + 8 * 4 - ( 5+ 2 ) % 3

 In the above expression, the highest precedence operator is (). So, the parenthesis goes first and
calculates first.

x=4/2+8*4-7%3

 Now, /, * and % operators have the same precedence and highest from the + and - Here, we use
the associativity concept to solve them.

 The associative of these operators are from left to right. So, / operator goes first and
then * and % simultaneously.

x=2+8*4-7%3

x = 2 + 32 - 7 % 3

x = 2 + 32 - 1
 Now, + and - operators both also have the same precedence, and the associativity of these
operators lest to the right.

 So, + operator will go first, and then - will go.

x = 34 - 1

x = 33
Control Statements
 The statements in the java code are executed according to the order in which they appear.
 However, Java provides statements that can be used to control the flow of Java code. Such
statements are called control flow statements.
 Java provides three types of control flow statements.
Decision Making statements:
 if statements
 switch statement
Loop statements:
 do while loop
 while loop
 for loop
 for-each loop
Jump statements:
 break statement
 continue statement
Decision-Making statements:

 As the name suggests, decision-making statements decide which statement to execute and when. It evaluate
program flow depending upon the result of the condition provided.

 There are two types of decision-making statements in Java, i.e., If statement and switch statement.

If Statement:

 In Java, the "if" statement is used to evaluate a condition.

 The control of the program is diverted depending upon the specific condition.

 The condition of the If statement gives a Boolean value, either true or false.

In Java, there are four types of if-statements given below.

 Simple if statement

 if-else statement

 if-else-if ladder

 Nested if-statement
Simple if statement:
 It is the most basic statement among all control flow statements in Java.
 It evaluates a Boolean expression and enables the program to enter a block of code if the expression evaluates
to true.
Syntax:
if(condition) {
statement 1; //executes when condition is true
}
if-else statement
 The if-else statement is an extension to the if-statement, which uses another block of code, i.e., else block.
 The else block is executed if the condition of the if-block is evaluated as false.
Syntax:
if(condition) {
statement 1; //executes when condition is true
}
else{
statement 2; //executes when condition is false }
if-else-if ladder:

The if-else-if statement contains the if-statement followed by multiple else-if statements.

Syntax:

if(condition 1) {

statement 1; //executes when condition 1 is true

else if(condition 2) {

statement 2; //executes when condition 2 is true

else {

statement 2; //executes when all the conditions are false

}
Nested if-statement:

In nested if-statements, the if statement can contain a if or if-else statement inside another if or else-
if statement.

Syntax:

if(condition 1) {

statement 1; //executes when condition 1 is true

if(condition 2) {

statement 2; //executes when condition 2 is true

else{

statement 2; //executes when condition 2 is false

} }
Switch Statement

In Java, Switch statements are similar to if-else-if statements. The switch statement contains
multiple blocks of code called cases and a single case is executed based on the variable which is
being switched.

 Cases cannot be duplicate

 Default statement is executed when any of the case doesn't match the value of expression. It is
optional.

 Break statement terminates the switch block when the condition is satisfied. It is optional, if not
used, next case is executed.

 While using switch statements, we must notice that the case expression will be of the same type as
the variable. However, it will also be a constant value.
The syntax to use the switch statement is given below.
switch (expression){
case value1:
statement1;
break;
.
.
.
case valueN:
statementN;
break;
default:
default statement;
}
Loop Statements

 In programming, sometimes we need to execute the block of code repeatedly while some
condition evaluates to true.

 However, loop statements are used to execute the set of instructions in a repeated order.

 The execution of the set of instructions depends upon a particular condition.

In Java, we have three types of loops that execute similarly. However, there are differences in their
syntax and condition checking time.

 for loop

 while loop

 do-while loop
for loop

 In Java, for loop is similar to C and C++.

 It enables us to initialize the loop variable, check the condition, and increment/decrement in a
single line of code.

 We use the for loop only when we exactly know the number of times, we want to execute the
block of code.

Syntax:

 for(initialization, condition, increment/decrement) {

 //block of statements

}
public class Cal {

public static void main(String[] args) {

int sum = 0;

for(int j = 1; j<=10; j++) {

sum = sum + j;

System.out.println("The sum of first 10 natural numbers is " + sum);

}
for-each loop
 Java provides an enhanced for loop to traverse the data structures like array or collection.
 In the for-each loop, we don't need to update the loop variable.
Syntax:
for(data_type var : array_name/collection_name){
//statements
}

Example:
public class Cal {
public static void main(String[] args) {
String[] names = {"Java","C","C++","Python","JavaScript"};
System.out.println("Printing the content of the array names:\n");
for(String name:names) {
System.out.println(name);
} } }
while loop:

 The while loop is also used to iterate over the number of statements multiple times.

 However, if we don't know the number of iterations in advance, it is recommended to use a while loop.

 Unlike for loop, the initialization and increment/decrement doesn't take place inside the loop statement
in while loop.

 It is also known as the entry-controlled loop since the condition is checked at the start of the loop. If
the condition is true, then the loop body will be executed; otherwise, the statements after the loop will
be executed.

 Syntax:

while(condition){

//looping statements

}:
public class Calculation {

public static void main(String[] args) {

// TODO Auto-generated method stub

int i = 0;

System.out.println("Printing the list of first 10 even numbers \n");

while(i<=10) {

System.out.println(i);

i = i + 2;

}
do-while loop:

 The do-while loop checks the condition at the end of the loop after executing the loop statements.

 When the number of iteration is not known and we have to execute the loop at least once, we can
use do-while loop.

 It is also known as the exit-controlled loop since the condition is not checked in advance.

Syntax:

do

//statements

} while (condition);
public class Cal {

public static void main(String[] args) {

int i = 0;

System.out.println("Printing the list of first 10 even numbers \n");

do {

System.out.println(i);

i = i + 2;

}while(i<=10);

}
Jump Statements

 Jump statements are used to transfer the control of the program to the specific statements.

 There are two types of jump statements in Java, i.e., break and continue.

break statement:

 As the name suggests, the break statement is used to break the current flow of the program and
transfer the control to the next statement outside a loop or switch statement.

 However, it breaks only the inner loop in the case of the nested loop.

 The break statement cannot be used independently in the Java program, i.e., it can only be written
inside the loop or switch statement.
public class BreakExample {

public static void main(String[] args) {

for(int i = 0; i<= 10; i++) {

System.out.println(i);

if(i==6) {

break;

}
continue statement:

Unlike break statement, the continue statement doesn't break the loop, whereas, it skips the specific
part of the loop and jumps to the next iteration of the loop immediately.

Example:

public class Continue {

public static void main(String[] args) {

for(int i = 0; i<= 2; i++) {

for (int j = i; j<=5; j++) {

if(j == 4) {

continue;

} System.out.println(j);

} } } }

You might also like