0% found this document useful (0 votes)
8 views47 pages

Basic Syntactical Constructs in Java

Java is a high-level, platform-independent programming language developed by Sun Microsystems, now managed by Oracle. It supports object-oriented programming principles and features like simplicity, security, portability, and robustness. The Java Development Kit (JDK), Java Runtime Environment (JRE), and Java Virtual Machine (JVM) are essential components for compiling and executing Java programs.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views47 pages

Basic Syntactical Constructs in Java

Java is a high-level, platform-independent programming language developed by Sun Microsystems, now managed by Oracle. It supports object-oriented programming principles and features like simplicity, security, portability, and robustness. The Java Development Kit (JDK), Java Runtime Environment (JRE), and Java Virtual Machine (JVM) are essential components for compiling and executing Java programs.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1.1.a.

Introduction to java:
• Java is a high-level programming language and a platform.
• It was developed by the company named Sun MicroSystems which was later acquired
by Oracle Corporation. Now oracle manages and releases different versions of java.
• Java was created by a team led by James Gosling at Sun MicroSystem.
High Level Language :
• A High-Level Language is a computer programming language that uses English like statements
to write the computer instructions.
• High-level languages are most widely programming languages because they are easy to
understand to human being.
History of java:
• Java was created by the company named as Sun MicroSystems. James Gosling is known as the
creator of java language.
• In 1991, a team named Green team, led by James Gosling started working on java language
project.
• Initially their intention was to develop the language that can be used for digital devices like cell
phones, televisions, set-top boxes etc.
• Initially the name of language was Oak.
Q. List any eight features of Java. 2M
Q. Explain four or six features of Java. 4M or 6M
1.1.b. Java Features:
1. Java is Platform Independent

• Java is a platform independent language.


• In java you can write and compile your program on one machine(eg. windows) and then you can
run the compiled code(.class file) on any other machine([Link] or macos).
• That is what the platform independent means in java, program written and compiled on one
machine can be run on any other machine.
2. Java is Object Oriented

• Java is an object oriented programming language because java supports the principles of Object
Oriented.
• Programming(OOPs)like Encapsulation, Inheritance, Abstraction Polymorphism etc.
3. Java is Simple

• Java is a simple language because it's syntaxes are very similar to C++ syntaxes.
• It also provides automatic memory management through garbage collection.
• Java contains a lot of predefined class libraries to support different needs in a program.
4. Java is Secure

• Java is secure because it has features like automatic memory management, no explicit pointer,
bytecode verifier etc that enhances the security of java programs.
• Bytecode verifier ensures that .class files are not edited explicitly, any external edit fails the
program to run.
5. Java is Portable

• Java is portable because the bytecode(.class file) of a program can be run on different machines
without any change in it.

6. Java is Robust

• A language is called robust if it is reliable.


• The reliability comes because java strongly checks for error in program at compile and runtime
both, to eliminate error-prone situations.
• The reliability also comes because java also has the strong memory allocation and automatic
garbage collection mechanism which reduces the probability of crashing a program at runtime.
7. Dynamic:

• Classes in java are linked/loaded only when needed. The code can be downloaded.
• dynamically from anywhere on the network.
8. Interpreted

• Java is a highly interpreted language. At runtime java bytecode is interpreted(converted) into


machine code using java interpreter(part of JVM) in order to run the program.
• Java has the feature of just-in-time compilation(happens at runtime) which reduces the
interpretation time.
[Link] Neutral

• Java can be run on any computer architecture.


• As bytecode are platform independent, it also makes java as an architecture neutral language.
What is bytecode in Java

In java when you compile a program, the java compiler(javac) converts/rewrite your program in
another form/language which we call as bytecode. The .class file that is generated after
compilation is nothing else, it's basically the bytecode instructions of your program. The word
bytecode and .class are used interchangeably, so if someone says bytecode, it simply means the
.class file of program.
1.1.C. Java Runtime Environment:
What is JDK in Java:

• JDK stands for java development kit. As the name itself suggest, JDK helps the programmer in
development(compilation and execution) of java programs.
• It's a software package that contains tools and libraries needed for compilation and execution of
java programs.
• If you are a programmer then you must need to install JDK first in your system in order to start
programming in java.
• For windows OS, this software generally comes in the form of .exe or .zip file.

JDK = JRE + Development tools(eg. javac, javap, java, javadoc etc)


What is JRE in Java:

• JRE stands for java runtime environment. It provides a runtime environment to your program for
it's execution.
• As soon as you start running your program using java command, the job of JRE starts and it
ends when either the program ran successfully or any error is thrown.
JRE = JVM + runtime libraries(contains packages like util, math, lang etc.)+ runtime files
What is JVM in Java:

JVM stands for java virtual machine, a virtual machine which loads and executes java programs
in memory.
The machine loads not only your class(program) but also other required classes and libraries as
well which are needed to execute the program.

Let's see some of the tasks performed by JVM:


• Loads code - Loads .class files in memory.
• Verfies code - Verifies the bytecode.
• Interprets code - Converts bytecode into machine specific code.
• Provides runtime environment - Makes availability of dependent classes and libraries.
• Executes code - Executes the code and generate the output.
• Memory management - Manages memory for classes, objects etc. by using garbage collection.

Difference between JDK ,JRE and JVM:

JDK JRE JVM

JDK stands for java development


JRE stands for java runtime
JVM stand for java virtual
kit. environment. machine.

JVM is not a separate software


JDK is a software package. JRE is also a software package.
package, it's part of JRE.

Using JDK you can do both, JVM is part of JRE, responsible


Using JRE you can do only
compilation and execution of for execution of your java
execution of java programs.
java programs. programs.

JDK exists physically in your


JRE also exists physically in
JVM does not exist physically in
computer. your computer. your computer.
You can download and install
JRE can also be dowloaded and
JVM comes as part of JRE.
JDK in your computer. installed in your computer.

JRE is a subset of JDK but


JDK is a superset of JRE. JVM is a subset of JRE.
superset of JVM.

JDK contains tools like javac,


JRE contains runtime tools
JVM doesn't contains any such
javap, java, javadoc etc. like java, javaw etc. tool.

Basic Example programs in Java:

This section contains some basic examples of java programs, specially for beginners to get some
more idea about execution flow in java programs. It also shows you how to pass command line
arguments to java programs and how to call method of a program using object.

Execution flow of java program

class FirstProgramFlow {

public static void main(String [] args) {

[Link]("first ");

[Link]("second ");

[Link]("third ");

}}
Output:

first
second third
Java Syntax:
[Link]
Public class Firstpgm{
Public static void main(String[] args)
{
[Link](“Hello world”);
}
}
Q. Define class and object in java?
1.2.a Java Classes:
• A Class is like an object constructor, or a "blueprint" for creating objects.
• Everything in Java is associated with classes and objects, along with its attributes and methods.
• For example: in real life, a car is an object. The car has attributes, such as weight and color,
and methods, such as drive and brake.

Create a Class:

To create a class, use the keyword class.


class Firstpgm{
Public static void main(String[] args)
{
[Link](“Hello world”);
}
}
Creating object in java:
In Java, we cannot execute any program without creating an object.

o Using new Keyword

Using new Keyword

• Using the new keyword is the most popular way to create an object or instance of the class.
• When we create an instance of the class by using the new keyword, it allocates memory (heap)
for the newly created object and also returns the reference of that object to that memory.
• The new keyword is also used to create an array. The syntax for creating an object is:

ClassName object = new ClassName();


variable in Java:

• A variable is the name of a reserved area allocated in memory.


• In other words, it is a name of the memory location. It is a combination of "vary + able" which
means its value can be changed.
• A variable is a container which holds the value while the Java program is executed.

Syntax for Declaring variable in java:


Datatype variable _name;
Ex: int age;
Syntax Initialization of variable:
Data_type variable_name=value;
Ex: int age=20;
Types of Variables:
There are three types of variables in Java.

• Local variable
• Instance variable
• Static or Class variable

1. Java Local variable:


• Variables defined inside methods, constructors or blocks are called local variables.
• These variables are created in memory(stack memory) when execution of that method,
constructor or block starts in which they are declared.
• Local variables don't have any default values in java, they must be initialized before they can be
used.
2. Java Instance variable:

• Variables defined inside a class but outside any method, constructor or block are known as
instance variable.
• Initialization of instance variable is not compulsory, if not initialized, these variables will have
default values as per their data type.
• Instance variables are created in memory(heap memory) as soon as the object of the class
containing the instance variable is created.
• The Instance variables are accessed using object name like [Link].
• The good practice is to always use the object name for accessing the instance variable.

Example: Instance variable program in java:


class InstanceVariable {
int age = 20; // instance variable age, created inside class
String name = "Rahul"; // instance variable name, created inside class
public static void main(String [] args) {
InstanceVariable iv = new InstanceVariable();
[Link]("Age = " +[Link]);
[Link]("Name = " +[Link]);
}
}

Output:

Age=20

Name=Rahul

3. Class/Static variable in java :

• Variables defined inside a class(not inside method, constructor or block) using static keyword
are known as static or class variables.
• Initialization of class variable is also not compulsory, if not initialized, these variables will have
default values as per their data type.
• These variables are known as class variables because they belong to class, not objects.
• The declaration of static or class variable is same as instance variable, except that they are
declared along with static keyword.

How to declare and access class variable in java:

• The declaration of static or class variable is same as instance variable, except that they are
declared along with static keyword.
• Static variable can be accessed using class name as [Link] or using any of
the object instances as well like [Link].

1.3 Tokens in Java:

• 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. It is useful for compilers to detect errors.

• Remember that the delimiters are not part of the Java tokens.
Types of Tokens:

Java token includes the following:

o Keywords
o Identifiers
o Literals
o Operators
o Separators
o Comments

Keywords: These are the pre-defined reserved words of any programming language.
Each keyword has a special meaning. It is always written in lower case.

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

16. finally 17. float 18. for 19. if 20. implements

21. import 22. instanceof 23. int 24. interface 25. long

26. native 27. new 28. package 29. private 30. protected

31. public 32. return 33. short 34. static 35. super
36. switch 37. synchronized 38. this 39. thro 40. throws

41. transient 42. try 43. void 44. volatile 45. while

46. assert 47. const 48. enum 49. goto 50. strictfp

Identifier: Identifiers are used to name a variable, constant, function, class, and [Link] are
some rules to declare identifiers are:

o The first letter of an identifier must be a letter, underscore or a dollar sign. It cannot start with
digits but may contain digits.
o The whitespace cannot be included in the identifier.
o Identifiers are case sensitive.

Some valid identifiers are:

1. PhoneNumber
2. PRICE
3. radius
4. a
5. a1
6. _phonenumber
7. $circumference
8. jagged_array
9. 12radius //invalid

Literals: In programming literal is a notation that represents a fixed value (constant) in the
source code.

Separators: The separators in Java is also known as punctuators. There are nine separators in
Java, are as follows:

separator <= ; ( ) | { } | [ ]

Comments: Comments allow us to specify information about the program inside our Java code.
Java compiler recognizes these comments as tokens but excludes it form further processing. The
Java compiler treats comments as whitespaces. Java provides the following two types of
comments:
Java Constant:

• Constant is a value that cannot be changed after assigning it. Java does not directly support the
constants.
• There is an alternative way to define the constants in Java by using the non-access modifiers
static and final.

Static and Final Modifiers:

o The purpose to use the static modifier is to manage the memory.


o It also allows the variable to be available without loading any instance of the class in which it is
defined.
o The final modifier represents that the value of the variable cannot be changed. It also makes the
primitive data type immutable or unchangeable.
o The syntax to declare a constant is as follows:

static final datatype identifier_name=value;

For example, price is a variable that we want to make constant.

static final double PRICE=432.78;

[Link] type casting with suitable example?


Type Casting in Java:
• In Java, type casting is a method or process that converts a data type into another data type in
both ways manually and automatically.
• The automatic conversion is done by the compiler and manual conversion performed by the
programmer.
Types of Type Casting:

There are two types of type casting:

o Widening Type Casting


o Narrowing Type Casting

[Link] 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.
• 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
[Link]
1. public class WideningTypeCastingExample
2. {
3. public static void main(String[] args)
4. {
5. int x = 7;
6. //automatically converts the integer type into long type
7. long y = x;
8. //automatically converts the long type into float type
9. float z = y;
10. [Link]("Before conversion, int value "+x);
11. [Link]("After conversion, long value "+y);
12. [Link]("After conversion, float value "+z);
13. }
14. }

Output

Before conversion, the value is: 7


After conversion, the long value is: 7
After conversion, the float value is: 7.0

[Link] 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

[Link]

• public class NarrowingTypeCastingExample


• {
• public static void main(String args[])
• {
• double d = 166.66;
• //converting double data type into long data type
• long l = (long)d;
• //converting long data type into int data type
• int i = (int)l;
• [Link]("Before conversion: "+d);
• //fractional part lost
• [Link]("After conversion into long type: "+l);
• //fractional part lost
• [Link]("After conversion into int type: "+i);
• }
• }
• Output
• Before conversion: 166.66
• After conversion into long type: 166

After conversion into int type: 166

Difference between local, instance and static variable in java:

Features Local variable Instance variable Static variable

Declaration pointInside a method, constructor, or [Link] the class. Inside the class
using static keyword.

Lifetime Created when method, constructor or


Created when Created when the
block is entered or executed. instance of class is
program starts.
created
Destroyed on exit of method, with new keyword. Destroyed when the
program execution
constructor or block. Destroyed when completed.
object is available for
garbage collection.

Scope/Visibility Visible only in the method, Visible to all methodsSame as instance


constructor or block in which they are
in the class. It couldvariable
declared. be visible to other
classes as well
according to it's
access modifier.

Initial value None. Must be assigned a value before


Default value as Same as instance
it's use. per Data Type. 0 for variable.
integers, false for
booleans, or null for
object references etc.

Use of Access
Access Can be used. Can be used
Modifier modifier(public, private, protected)
can not be used with local variables

Access from
Not possible, Local variable can be Instance variables canSame as instance
outside accessed within the method,be accessed outside variable. It can be
constructor or block in which they are
depending upon it's accessed using object or
declared. access modifier. It class name.
can be accessed using
object of that class.

Memory Area Stack memory. Heap memory Heap memory

Use Used for local computations Used when value of


Generally used for
variable must be declaring constants
referenced by more
than one method

Java Program of local, instance and static variable:


class Student {
static String college = "SUMVS"; // static or class variable college
int rollNo; // instance variable rollNo
String name; // instance variable name
public static void main(String [] args){
Student s1 = new Student(); // local variable s1
[Link] = 1;
[Link] = "Ram"
Student s2 = new Student(); // local variable s2
[Link] = 2;
[Link] = "Shyam";
[Link]();
[Link]();
int count = 2; // local variable count
[Link].p;rintln("Total students = "+ count);
}
void printDetail() {
int count2 = 2; // local variable count2
[Link](rollNo +", "+ name+", "+ [Link]+", "+ count2);
}}

Data Types in Java:

There are two types of data types in Java:

1. Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float
and double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces,
and Arrays.

Data Type Default Value Default size

Boolean false 1 bit

Cha\ '\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

[Link] any two logical operators in java with example.4M

1.4 Operator in Java:

An operator is basically a special symbol which tells the computer to perform specific operation
on one, two or three operands and then return a result.

Operand in Java:

An operand is simply a value on which the operation is [Link] can also be


categorized by the number of operands they operate on.

So we can categorize above operators in three types as well :

• Unary operator
• Binary operator
• Ternary operator

unary operator in java:

An operator which operates on one operand is known as unary operator. For example +, -,
++ etc are unary operators, usage example +2, -3, ++a etc.

binary operator in java:

An operator which operates on two operands is known as binary operator. For example +, -,
* etc are binary operators, usage example 2+3, 5-3, a*b etc.

Ternary operator in java :

An operator which operates on three operands is known as ternary operator. There is only one
ternary operator in java which is ?:, also known as if then else operator.

Different types of operators in Java:


1. Assignment operator (=)
2. Arithmetic Operators (+, -, *, /, %)
3. Unary Operators (+, -, ++, --, !)
4. Relational Operators (==, !=, >, >=, <, <=)
5. Conditional Operators (&&, ||, ?:)
6. Bitwise Operators (~, &, ^, |)
7. Bit Shift Operators (<<, >>, >>>)

[Link] operator in java:

• The = operator in java is known as assignment or simple assignment operator. It assigns the
value on its right side to the operand(variable) on its left side.

• For example :

int a = 10;

2. Arithmetic Operators:

• Arithmetic operators are also one of the most used operators in java programming language.

• Arithmetic operators are used to perform arithmetic operations like addition, subtraction,
multiplication and division.

• These operator performs the same operation as they perform in basic mathematics. Table below
shows the list of all arithmetic operators which you can use in your java programs.
Consider a and b as two operands or variables.

Operator Name Example Description

+ Additive operator a+b Adds a and b

- Subtraction operator a-b Subtracts b from a

* Multiplication operator a*b Multiplies a and b


/ Division operator a/b Divides a by b

% Remainder operator a%b Divides a by b and returns the remainder

The table below shows the list of all operators in java which you can use in your programs. For
this table let's assume we have operands or variables a, b and c.

Unary Operators:(Increment & Decrement Operator)

• Unary simply means one, so unary operators are the operators which operates on only one
operand.
• The table below shows the list of all unary operators in java. For this table let's assume we have
an integer variable a and a boolean variable isValid :

Operator Name Example Description

+ Unary plus operator +a, +5 Indicates positive value

- Unary minus operator -a, -3 Negates an expression

++ Increment operator a++, ++a Increments value of a by 1

-- Decrement operator a--, --a Decrements value of a by 1

! Logical complement operator!isValidInverts the value of a boolean

Increment and decrement operators in Java:

• The unary increment(++) operator increments the value of a variable by 1 while unary
decrement(--) operator decrements the value of a variable by 1.
• For example a++ increases the value a by 1 and is same as a = a + 1, similarly a-- decreases the
value of a by 1 and is same as a = a - 1. Both these operators can be used with a variable only,
not with any constant value, expression or method calls.
• In pre increment/decrement, the value of the variable is incremented/decremented first then it is
assigned or evaluated, that is why it is called pre-increment/decrement.
• While in post increment/decrement the current value of the variable is assigned or evaluated,
after that the increment/decrement happens, that is why it is called post increment/decrement.
• Let's understand this by the example below :

• int a = 2, b = 3, c = 4, d = 5;
• int p = a++; // p = 2; first assignment happens then the increment
• p = a; // a = 3, p = 3; // a was increased in previous line
• int q = ++b; // q = 4; first increment happens then the assignment
• int r = c--; // r = 4, first assignment happens then the decrement
• r = c; // c = 3, r = 3; // c was decreased in previous line
• int s = --d; // s = 4; first decrement happens then the assignment

• In case of pre increment/decrement operation, use the incremented/decremented value at the


place of variable while in post increment/decrement, use the current value at the place of
variable.
• Let's understand this with an expression to make it more clear.

• int a = 2;
• int p = a++ + --a - a-- * ++a;

• To understand it clearly let's see step by step how this expression is evaluated.
• Just remember in java an expression is evaluated from left to right.

• a++ + --a - a-- * ++a; // original expression


• 2 + --a - a-- * ++a; // current value of a is 2, so a++ is replaced with 2, then the increment
happens
• 2 + 2 - a-- * ++a; // at --a, the value of a was 3(was incremented with first a++) but pre
decremented as 2
• 2 + 2 - 2 * ++a; // current value of a is 2 so a-- is replaced with 2, then it will be decremented
• 2 + 2 - 2 * 2; // Now current value of a is 1 so ++a will be replaced as 2 as it's a pre increment.
• 2 + 2 - 4; // first multiplication will happen as it has higher precedence over + and -
• 0 // So final value will be 0 which will be assigned in p
• The diagram below demonstrates how the value of variable a is evaluated.

Relational operators in Java:

• Relational operators are used to relate or compare if one operand is greater than, less than, equal
to, or not equal to another operand. Operators like >, >=, < etc are called as relational operators.
• while operator == is called as equality operator. All relational operators along with equality
operator returns either true or false.
• Table below shows the list of all relational operators in java.

List of Relational operators in Java:

Operator Name Example Description

== Equale to Operator a==b Checks if a and b are equal

!= Not equal to Operator a!=b Checks if a and b are not equal

> Greater than Operator a>b Checks if a greater than b

Greater than or equal to


>= a>=b Checks if a greater than or equal to b
Operator
< Less than Operator a<b Checks if a less than b

Less than or equal to


<= a<=b Checks if a less than or equal to b
Operator

Java program of relational operator

class RelationalOperator {
public static void main(String[] args) {
int num1 = 3;
int num2 = 5;
if(num1 == num2)
[Link]("num1 == num2");
if(num1 != num2)
[Link]("num1 != num2");
if(num1 > num2)
[Link]("num1 > num2");
if(num1 >= num2)
[Link]("num1 >= num2");
if(num1 < num2)
[Link]("num1 < num2");
if(num1 <= num2)
[Link]("num1 <= num2");
}
}

Output:

num1 != num2
num1 < num2
num1 <= num2
Conditional operators in Java:

Following operators are conditional operators in java :

Operator Name Example Description

Conditional AND (a==1 && Conditional-AND operator, returns true if both


&&
Operator b==5) expression returns true, else false

Conditional OR Conditional-OR operator, returns true if any of the


|| (a==1 || b==5)
Operator expression returns true, else false

The result of conditional AND and conditional OR operators is also a boolean value which
is true or false.

Java Ternary Operator:

• The ternary operator( ?:) is another conditional operator in java. This operator can be thought as
a short form of if-then-else statement.

• It is known as ternary operator because it uses three operands. Line below shows how to use this
operator.

variable = someCondition ? Expression1 : Expression2;

Here someCondition is a boolean expression that returns either true or false. You can read this
operator as "if someCondition is true, assign the value of Expression1 into the variable else
assign the value of Expression2 into the variable.
Bitwise operators in Java:

As the name itself suggests, bitwise operator performs operation bit by bit wise. Table below
shows the list of all bitwise operators in java.

Consider a and b as two integer type variables.


Operator Name Example Description

Performs bitwise AND operation between bits


& Bitwise AND Operator a&b
of a and b

Performs bitwise OR operation between bits


| Bitwise OR Operator a|b
of a and b

Performs bitwise exclusive OR operation


^ Bitwise XOR Operator a^b
between bits of a and b

Bitwise complement
~ ~a Inverts the bits of variable a
Operator

• All the bitwise operators except complement operator are binary operators.

• The bitwise complement operator is a unary operator, as it requires only one operand to perform
the operation. It belongs to bitwise operator type because it works on bits.

Bitwise AND operator in Java:

• Bitwise AND(&) operator performs bitwise AND operation on corresponding bits of both the
operands.

• It returns 1 if both the bit's are 1 else it returns 0. For example & operation between
two byte variable with value as 53(00110101) and 79(01001111) will result in 5(00000101).

1&1=1
1&0=0
0&1=0
0&0=0
Bitwise OR operator in Java:

• Bitwise OR(|) operator performs bitwise OR operation on corresponding bits of both the
operands. It returns 1 if any of the bit's is 1 else it returns 0.

• For example | operation between two byte variable with value


as 53(00110101) and 79(01001111) will result in 127(01111111).

1|1=1
1|0=1
0|1=1
0|0=0

Bitwise Exclusive OR operator in Java

Bitwise XOR(^) operator performs bitwise exclusive OR operation on corresponding bits of


both the operands.
It returns 1 if both bit's are different else it returns 0. For example XOR operation between
two byte variable with value as 53(00110101) and 79(01001111) will result in 122(01111010).

1|1=0

1|0=1

0|1=1

0|0=0

Bitwise complement operator

The unary bitwise complement operator ~ inverts the bit pattern of an operand. It
converts 0 as 1 and 1 as 0. For example a byte data type contains 8 bits, using this operator with
a byte variable with value whose bit pattern is "00110101" would be changed as "11001010".
Bit Shift operator in Java:

• As the name itself suggests, the bit shift operators shifts the bits of an operand to left or right
depending on the shift operator used.

• In bit shift operator, the bit pattern(operand) is given in left-side while the number of positions
to shift by is given in right side of the operator.

• All bit shift operators are binary operators in java as they requires two operands to operate.
Table below shows the list of all bit shift operators in java.

Operator Name Example Description

Signed left shift


<< a << 2 Left shifts the bits of a by 2 position
Operator

Signed right shift


>> a >> 3 Right shifts the bits of a by 3 position.
Operator

Unsigned right shift Right shifts the bits of a by 2 position and places 0's
>>> a >>> 2
Operator in left side.

Java instanceof Operator:

• The java instanceof operator is used to test whether the object is an instance of 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.

Simple example of java instanceof:

Let's see the simple example of instance operator where it tests the current class.

1. class Simple1{
2. public static void main(String args[]){
3. Simple1 s=new Simple1();
4. [Link](s instanceof Simple1);//true
5. }
6. }

Output:true

Mathematical Function :

Java Math class provides several methods to work on math calculations like min(), max(), avg(),
sin(), cos(), tan(), round(), ceil(), floor(), abs() etc

Java Math Methods:


• The [Link] class contains various methods for performing basic numeric operations
such as the logarithm, cube root, and trigonometric functions etc.
• The various java math methods are as follows:
• Basic Math methods
Method Description

[Link]() It will return the Absolute value of the given value.

[Link]() It returns the Largest of two values.

[Link]() It is used to return the Smallest of two values.

[Link]() It is used to round of the decimal numbers to the nearest value.

[Link]() It is used to return the square root of a number.

[Link]() It is used to return the cube root of a number.

[Link]() It returns the value of first argument raised to the power to second argument.

[Link]() It is used to find the sign of a given value.

Example:

1. public class JavaMathExample1


2. {
3. public static void main(String[] args)
4. {
5. double x = 28;
6. double y = 4;
7. // return the maximum of two numbers
8. [Link]("Maximum number of x and y is: " +[Link](x, y));
9. // return the square root of y
10. [Link]("Square root of y is: " + [Link](y));
11. //returns 28 power of 4 i.e. 28*28*28*28
12. [Link]("Power of x and y is: " + [Link](x, y));
13. }
14. }
15. ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
16. Output:
17. Maximum number of x and y is: 28.0
18. Square root of y is: 2.0
19. Power of x and y is: 614656.0
Operator Precedence in java:

Precedence:
It is meaningful only if an expression has more than one operator with higher or lower
precedence. The operators having higher precedence are evaluated first.
Associativity:
If an expression has more than two operators of the same precedence. In such a case, an
expression can be solved either left-to-right or right-to-left, accordingly.
Precedence Operator Type Associativity

15 () Parentheses Left to Right


[] Arraysubscript
· Member selection

14 ++ Unarypost-increment Right to left


-- Unary post-decrement

13 ++ Unarypre-increment Right to left


-- Unarypre-decrement
+ Unaryplus
- Unaryminus
! Unarylogicalnegation
~ Unarybitwisecomplement
(type) Unary type cast

12 * Multiplication Left to right


/ Division
% Modulus

11 + Addition Left to right


- Subtraction

10 << Bitwiseleftshift Left to right


>> Bitwise right shift with sign extension
>>> Bitwise right shift with zero extension

9 < Relationallessthan Left to right


<= Relationallessthanorequal
> Relationalgreaterthan
>= Relationalgreaterthanorequal
instanceof Type comparison (objects only)

8 == Relational is equal toLeft to right


!= Relational is not equal to

7 & Bitwise AND Left to right

6 ^ Bitwise exclusive OR Left to right

5 | Bitwise inclusive OR Left to right

4 && Logical AND Left to right

3 || Logical OR Left to right

2 ?: Ternary conditional Right to left


1 = Assignment
+= Addition assignment
-= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment

class OperatorPrecedence {
public static void main (String[] args) {
int result = 0;
result = 5 + 2 * 3 - 1;
[Link]("5 + 2 * 3 - 1 = " +result);
result = 5 + 4 / 2 + 6;
[Link]("5 + 4 / 2 + 6 = " +result);

result = 3 + 6 / 2 * 3 - 1 + 2;
[Link]("3 + 6 / 2 * 3 - 1 + 2 = " +result);
result = 6 / 2 * 3 * 2 / 3;
[Link]("6 / 2 * 3 * 2 / 3 = " +result);
int x = 2;
result = x++ + x++ * --x / x++ - --x + 3 >> 1 | 2;
[Link]("result = " +result); }}

Output:

5 + 2 * 3 - 1 = 10
5 + 4 / 2 + 6 = 13
3 + 6 / 2 * 3 - 1 + 2 = 13
6/2*3*2/3=6
result = 2

Mathematical Function :
Java Math class provides several methods to work on math calculations like min(), max(), avg(),
sin(), cos(), tan(), round(), ceil(), floor(), abs() etc

Java Math Methods:


The [Link] class contains various methods for performing basic numeric operations
such as the logarithm, cube root, and trigonometric functions etc. The various java math
methods are as follows:

Basic Math methods


Method Description
[Link]() It will return the Absolute value of the given value.

[Link]() It returns the Largest of two values.

[Link]() It is used to return the Smallest of two values.

[Link]() It is used to round of the decimal numbers to the nearest value.

[Link]() It is used to return the square root of a number.

[Link]() It is used to return the cube root of a number.

[Link]() It returns the value of first argument raised to the power to second argument.

[Link]() It is used to find the sign of a given value.

1. public class JavaMathExample1


2. {
3. public static void main(String[] args)
4. {
5. double x = 28;
6. double y = 4;
7. // return the maximum of two numbers
8. [Link]("Maximum number of x and y is: " +[Link](x, y));
9. // return the square root of y
10. [Link]("Square root of y is: " + [Link](y));
11. //returns 28 power of 4 i.e. 28*28*28*28
12. [Link]("Power of x and y is: " + [Link](x, y));
13. } }
14. ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
15. Output:
16. Maximum number of x and y is: 28.0
17. Square root of y is: 2.0
18. Power of x and y is: 614656.0
1.5 Decision Making statements band Loops:

• Java provides statements that can be used to control the flow of Java code. Such statements are
called control flow statements.
• It is one of the fundamental features of Java, which provides a smooth flow of program.
• Java provides three types of control flow statements.
• Decision Making statements
o if statements
o switch statement
• Loop statements
o do while loop
o while loop
o for loop
o for-each loop
• Jump statements
o break statement
o continue statement

Decision-Making statements:

• Decision-making statements decide which statement to execute and when.


• Decision-making statements evaluate the Boolean expression and control the 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.

1) If Statement:

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

1. [Link] if statement
2. [Link]-else statement
3. if-else-if ladder
4. Nested if-statement

Let's understand the if-statements one by one.

2) 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 of if statement is given below.

1. if(condition) {
2. statement 1; //executes when condition is true
3. }

Consider the following example in which we have used the if statement in the java code.

[Link]

1. public class Student {


2. public static void main(String[] args) {
3. int x = 10;
4. int y = 12;
5. if(x+y > 20) {
6. [Link]("x + y is greater than 20");
7. }
8. }
9. }

Output:

x + y is greater than 20

3) 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:

1. if(condition) {
2. statement 1; //executes when condition is true
3. }
4. else{
5. statement 2; //executes when condition is false
6. }

Consider the following example.

[Link]
1. public class Student {
2. public static void main(String[] args) {
3. int x = 10;
4. int y = 12;
5. if(x+y < 10) {
6. [Link]("x + y is less than 10");
7. } else {
8. [Link]("x + y is greater than 20");
9. }
10. }
11. }

Output:

x + y is greater than 20

4) if-else-if ladder:

• The if-else-if statement contains the if-statement followed by multiple else-if statements.
• In other words, we can say that it is the chain of if-else statements that create a decision tree
where the program may enter in the block of code where the condition is true.
• Syntax of if-else-if statement is given below.

1. if(condition 1) {
2. statement 1; //executes when condition 1 is true
3. }
4. else if(condition 2) {
5. statement 2; //executes when condition 2 is true
6. }
7. else {
8. statement 2; //executes when all the conditions are false
9. }

Consider the following example.

[Link]

1. public class Student {


2. public static void main(String[] args) {
3. String city = "Delhi";
4. if(city == "Meerut") {
5. [Link]("city is meerut");
6. }else if (city == "Noida") {
7. [Link]("city is noida");
8. }else if(city == "Agra") {
9. [Link]("city is agra");
10. }else {
11. [Link](city);
12. }
13. }
14. }

Output:

Delhi

5. 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 of Nested if-statement is given below.

1. if(condition 1) {
2. statement 1; //executes when condition 1 is true
3. if(condition 2) {
4. statement 2; //executes when condition 2 is true
5. }
6. else{
7. statement 2; //executes when condition 2 is false
8. }
9. }

Consider the following example.

[Link]

1. public class Student {


2. public static void main(String[] args) {
3. String address = "Delhi, India";
4. if([Link]("India")) {
5. if([Link]("Meerut")) {
6. [Link]("Your city is Meerut");
7. }else if([Link]("Noida")) {
8. [Link]("Your city is Noida");
9. }else {
10. [Link]([Link](",")[0]);
11. }
12. }else {
13. [Link]("You are not living in India");
14. }
15. }
16. }

Output:

Delhi

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.
• The switch statement is easier to use instead of if-else-if statements. It also enhances the
readability of the program.

Points to be noted about switch statement:

o The case variables can be int, short, byte, char, or enumeration. String type is also supported
since version 7 of Java
o Cases cannot be duplicate
o Default statement is executed when any of the case doesn't match the value of expression. It is
optional.
o Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
o 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.

1. switch (expression){
2. case value1:
3. statement1;
4. break;
5. .
6. .
7. .
8. case valueN:
9. statementN;
10. break;
11. default:
12. default statement;
13. }

Consider the following example to understand the flow of the switch statement.

[Link]

1. public class Student implements Cloneable {


2. public static void main(String[] args) {
3. int num = 1;
4. switch (num){
5. case 0:
6. [Link]("number is 0");
7. break;
8. case 1:
9. [Link]("number is 1");
10. break;
11. default:
12. [Link](num);
13. }
14. }
15. }

Output:

Number is 1
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.

1. for loop
2. while loop
3. do-while loop

Let's understand the loop statements one by one.

[Link] 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.

1. for(initialization, condition, increment/decrement) {


2. //block of statements
3. }

The flow chart for the for-loop is given below.

Consider the following example to understand the proper functioning of the for loop in java.
[Link]

1. public class Calculattion {


2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. int sum = 0;
5. for(int j = 1; j<=10; j++) {
6. sum = sum + j;
7. }
8. [Link]("The sum of first 10 natural numbers is " + sum);
9. }
10. }

Output:

The sum of first 10 natural numbers is 55

[Link] 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.
• The syntax to use the for-each loop in java is given below.

1. for(data_type var : array_name/collection_name){


2. //statements
3. }

Consider the following example to understand the functioning of the for-each loop in Java.

[Link]

1. public class Calculation {


2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. String[] names = {"Java","C","C++","Python","JavaScript"};
5. [Link]("Printing the content of the array names:\n");
6. for(String name:names) {
7. [Link](name);
8. }
9. }
10. }
Output:

Printing the content of the array names:

Java
C
C++
Python
JavaScript

[Link] 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.

The syntax of the while loop is given below.

1. while(condition){
2. /-+]/looping statements
3. }

The flow chart for the while loop is given in the following image.

Consider the following example.


Calculation .java

1. public class Calculation {


2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. int i = 0;
5. [Link]("Printing the list of first 10 even numbers \n");
6. while(i<=10) {
7. [Link](i);
8. i = i + 2;
9. }
10. }
11. }

Output:

Printing the list of first 10 even numbers

0
2
4
6
8
10

[Link] 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. The
syntax of the do-while loop is given below.

1. do
2. {
3. //statements
4. } while (condition);

The flow chart of the do-while loop is given in the following image.
Consider the following example to understand the functioning of the do-while loop in Java.

[Link]

1. public class Calculation {


2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. int i = 0;
5. [Link]("Printing the list of first 10 even numbers \n");
6. do {
7. [Link](i);
8. i = i + 2;
9. }while(i<=10);
10. }
11. }

Output:

Printing the list of first 10 even numbers


0
2
4
6
8
10
Jump Statements:

Jump statements are used to transfer the control of the program to the specific statements. In
other words, jump statements transfer the execution control to the other part of the program.
There are two types of jump statements in Java, i.e., break and continue.

[Link] 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.

The break statement example with for loop

Consider the following example in which we have used the break statement with the for loop.

[Link]

1. public class BreakExample {


2.
3. public static void main(String[] args) {
4. // TODO Auto-generated method stub
5. for(int i = 0; i<= 10; i++) {
6. [Link](i);
7. if(i==6) {
8. break;
9. }
10. }
11. }
12. }

Output:

0
1
2
3
4
5
6

break statement example with labeled for loop


[Link]

1. public class Calculation {


2.
3. public static void main(String[] args) {
4. // TODO Auto-generated method stub
5. a:
6. for(int i = 0; i<= 10; i++) {
7. b:
8. for(int j = 0; j<=15;j++) {
9. c:
10. for (int k = 0; k<=20; k++) {
11. [Link](k);
12. if(k==5) {
13. break a;
14. }
15. }
16. }
17.
18. }
19. }
20.
21.
22. }

Output:

0
1
2
3
4
5
[Link] 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.

Consider the following example to understand the functioning of the continue statement in Java.

1. public class ContinueExample {


2.
3. public static void main(String[] args) {
4. // TODO Auto-generated method stub
5.
6. for(int i = 0; i<= 2; i++) {
7.
8. for (int j = i; j<=5; j++) {
9.
10. if(j == 4) {
11. continue;
12. }
13. [Link](j);
14. }
15. }
16. }
17.
18. }

Output:

0
1
2
3
5
1
2
3
5
2
3
5
Garbage Collector:

• When a program executes in Java, it uses memory in different ways.


• The heap is a part of memory where objects live.
• It's the only part of memory that involved in the garbage collection process.
• It is also known as garbage collectible heap.
• All the garbage collection makes sure that the heap has as much free space as possible. The
function of the garbage collector is to find and delete the objects that cannot be reached.

Important Points About Garbage Collector

o It is controlled by a thread known as Garbage Collector.


o Java provides two methods [Link]() and [Link]() that sends request to the JVM for
garbage collection. Remember, it is not necessary that garbage collection will happen.
o Java programmer are free from memory management. We cannot force the garbage collector to
collect the garbage, it depends on the JVM.
o If the Heap Memory is full, the JVM will not allow to create a new object and shows an
error [Link].
o When garbage collector removes object from the memory, first, the garbage collector thread
calls the finalize() method of that object and then remove.

You might also like