Aoop - Unit I
Aoop - Unit I
PROGRAMMING
Here Java Environment refers to JRE (Java Runtime Environment) JRE is set of software tools which are used for
developing java applications.
Main component of JRE are JVM, set of libraries , User interface toolkits, deployment technologies and other files.
What is JVM?
JVMs are available for many hardware and software platforms - JVM is platform dependent.
JVM
JVM (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. JVMs are available for many hardware and software platforms (i.e. JVM is platform dependent).
The JVM performs following operation:
• Loads code
• Verifies code
• Executes code
• Provides runtime environment
JVM provides definitions for the:
• Memory area
• Class file format
• Register set
• Garbage
• collected heap
• Fatal error reporting etc.
Internal Architecture of JVM
1.Classloader
Classloader is a subsystem of JVM that is used to load class files.
2.Class(Method) Area
Class(Method) Area stores per-class structures such as the runtime constant pool, field and method data, the code for methods.
3.Heap
It is the runtime data area in which objects are allocated.
4.Stack
Java Stack stores frames. It holds local variables and partial results, and plays a part in method invocation and return. Each thread has a private
JVM stack, created at the same time as thread.A new frame is created each time a method is invoked. A frame is destroyed when its method
invocation completes.
5.Program Counter Register
PC (program counter) register 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
Contains a virtual processor, Interpreter to read bytecode stream then execute the instructions and Just-In-Time(JIT) compiler 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.
JAVA DEVELOPMENT KIT (JDK)
• Java Development Kit (JDK) is a software development environment used to develop java applications
• It physically exists
• All Java platforms consist of a Java Virtual Machine (VM) and an application programming interface (API).
• The Java Virtual Machine is a program, for a particular hardware and software platform, that runs Java technology applications.
• An API is a collection of software components that you can use to create other software components or applications.
• Each Java platform provides a virtual machine and an API, and this allows applications written for that platform to run on any
compatible system with all the advantages of the Java programming language: platform-independence, power, stability, ease-of-
development, and security
Development Platforms - Standard, Enterprise
Java SE
• Java SE's API provides the core functionality of the Java programming language. It defines everything from the basic types and
objects of the Java programming language to high-level classes that are used for networking, security, database access, graphical user
interface (GUI) development, and XML parsing.
• In addition to the core API, the Java SE platform consists of a virtual machine, development tools, deployment technologies, and
other class libraries and toolkits commonly used in Java technology applications.
Java EE
• The Java EE platform is built on top of the Java SE platform. The Java EE platform provides an API and runtime environment for
developing and running large-scale, multi-tiered, scalable, reliable, and secure network applications.
Java ME
• The Java ME platform provides an API and a small-footprint virtual machine for running Java programming language applications
on small devices, like mobile phones. The API is a subset of the Java SE API, along with special class libraries useful for small
device application development.
JavaFX
• JavaFX is a platform for creating rich internet applications using a lightweight user-interface API. JavaFX applications use
hardware-accelerated graphics and media engines to take advantage of higher-performance clients and a modern look-and-feel as
well as high-level APIs for connecting to networked data sources
INSTALLING JAVA JDK IN WINDOWS 11
4. On the next screen, you’ll be asked for the location of your file. Click on Next.
5. Once the JDK installation is complete, click on Close.
Compilation
Ex:
Variable value=C:\ProgramFiles\Java\jdk1.8.0_40\bin;
Running java:
Open notepad or any text editor type java program and save as file_name.java.
To compile:
open command prompt navigate to java file location javac file_name.java
Now class file will be created. ( i.e byte code)
To execute:
java file_name
java interpreter executes byte code into machine code(instructions) .i.e generates output.
JAVA COMPILER
• Java is an object-oriented, simple, efficient, robust, and general-purpose
programming language.
• It is primarily used for web-based enterprise applications.
• It was initially designed for embedded network applications running on different
platforms.
• When we start learning Java programming, one question arises: whether Java is
interpreted or Compiled, or both.
• Also, this question may be asked by the interviewee in your Java-related
interviews.
• So the answer to this question is Java is both Interpreted and compiled.
• However, it isn't clear whether Java is compiled or interpreted.
• It neither generates machine code after compiling a source file nor interpreted the
source file to execute code instructions line by line.
• To answer this question, we need to understand how Java is a platform-
independent language?
• Which means we can write Java code on a platform and can run on other
platforms such as hardware operating machine, without making any changes.
• So, understanding how Java achieves platform independence will provide a
complete answer to this question.
• Java is completely portable; the same Java code will run identically on different
platforms, regardless of hardware compatibility or operating systems.
• The Java source code first compiled into a binary byte code using Java
compiler, then this byte code runs on the JVM (Java Virtual Machine),
which is a software based interpreter. So Java is considered as both
interpreted and compiled.
• The compiled byte code allows JVM to be small and efficient, and fast
performing.
• Also, this byte code provides portability to the Java programming language.
• It allows executing this code to any JVM that is properly implemented on a
machine, regardless of hardware and software components & configurations
of the machine.
• Almost all web browsers contain JVM to execute the Java applet code.
Simple Java Program and It's Working
• Java bytecode is the instruction set for the Java Virtual Machine.
• It acts similar to an assembler which is an alias representation of a C++
code.
• As soon as a java program is compiled, java bytecode is generated.
• In more apt terms, java bytecode is the machine code in the form of a .class
file.
• With the help of java bytecode we achieve platform independence in java.
How does it works?
init − This method is intended for whatever initialization is needed for your
applet. It is called after the param tags inside the applet tag have been
processed.
start − This method is automatically called after the browser calls the init
method. It is also called whenever the user returns to the page containing the
applet after having gone off to other pages.
Life Cycle of an Applet
stop − This method is automatically called when the user moves off the page
on which the applet sits. It can, therefore, be called repeatedly in the same
applet.
destroy − This method is only called when the browser shuts down normally.
Because applets are meant to live on an HTML page, you should not normally
leave resources behind after a user leaves the page that contains the applet.
paint − Invoked immediately after the start() method, and also any time the
applet needs to repaint itself in the browser. The paint() method is actually
inherited from the java.awt.
A "Hello, World" Applet
• Java was designed to be easy for a professional programmer to learn and use
effectively.
• It’s simple and easy to learn if you already know the basic concepts of
Object Oriented Programming.
• Best of all, if you are an experienced C++ programmer, moving to Java will
require very little effort.
• Because Java inherits the C/C++ syntax and many of the object-oriented
features of C++, most programmers have little trouble learning Java.
• Java has removed many complicated and rarely-used features, for example,
explicit pointers, operator overloading, etc.
2. Object Oriented
• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation
3. Distributed
• Java language and Java Virtual Machine helped in achieving the goal of
“write once; run anywhere, any time, forever.”
• Changes and upgrades in operating systems, processors and system
resources will not force any changes in Java Programs.
8. Portable
• Package Declaration
• Import Statements
• Interface Section
• Class Definition
}
For example:
• In this section, we define the functionality of the program by using the methods.
• The methods are the set of instructions that we want to perform. These instructions execute at
runtime and perform the specified task.
For example:
public class Demo //class definition
{
public static void main(String args[])
{
void display()
{
System.out.println("Welcome to javatpoint");
}
//statements
}
}
When we follow and use the above elements in a Java program, the program
looks like the following.
CheckPalindromeNumber.java
/*Program name: Palindrome*/
//Author's name: Mathew
/*Palindrome is number or string that will remains the same
When we write that in reverse order. Some example of
palindrome is 393, 010, madam, etc.*/
//imports the Scanner class of the java.util package
import java.util.Scanner;
//class definition
public class CheckPalindromeNumber
{
//main method
public static void main(String args[])
{ //variables to be used in program
int r, s=0, temp;
int x; //It is the number variable to be checked for palindrome
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number to check: ");
//reading a number from the user
x=sc.nextInt();
//logic to check if the number id palindrome or not
temp=x;
while(x>0)
{
r=x%10; //finds remainder
s=(s*10)+r;
x=x/10;
}
if(temp==s)
System.out.println("The given number is palindrome.");
else
System.out.println("The given number is not palindrome.");
}
}
JAVA COMMENTS
• The Java comments are the statements in a program that are not executed by
the compiler and interpreter.
• Why do we use comments in a code?
• Comments are used to make the program more readable by adding the
details of the code.
• It makes easy to maintain the code and to find the errors easily.
• The comments can be used to provide information or explanation about
the variable, method, class, or any statement.
• It can also be used to prevent the execution of program code while testing
the alternative code.
Types of Java Comments
• The single-line comment is used to comment only one line of the code. It is
the widely used and easiest way of commenting the statements.
• Single line comments starts with two forward slashes (//). Any text in front
of // is not executed by Java.
• Syntax:
//This is single line comment
CommentExample1.java
Output: 10
Java Multi Line Comment
Output: 10
Java Documentation Comment
• Documentation comments are usually used to write large programs for a project
or software application as it helps to create documentation API.
• These APIs are needed for reference, i.e., which classes, methods, arguments, etc.,
are used in the code.
• To create documentation API, we need to use the javadoc tool.
• The documentation comments are placed between /** and */.
• Syntax:
/**
*
*We can use various tags to depict the parameter
*or heading or author name
*We can also use HTML tags
*
*/
javadoc tags
Calculate.java
import java.io.*;
public class Calculate
{
public int sum(int input1, int input2)
{
return input1 + input2;
}
public static void main(String[] args)
{
Calculate obj = new Calculate();
int result = obj.sum(40, 20);
System.out.println("Addition of numbers: " + result);
}
}
Compile it by javac tool:
• Create Document
Are Java comments executable?
3) By anonymous object:
new Employee();
finalize() method
• The finalize() method is invoked each time before the object is garbage collected.
This method can be used to perform cleanup processing.
• This method is defined in Object class as:
protected void finalize()
{
}
• gc() method
• The gc() method is used to invoke the garbage collector to perform cleanup
processing. The gc() is found in System and Runtime classes.
public static void gc()
{
}
Simple Example of garbage collection in java
White Spaces
• Java is a free form language.
• This means that you do not need to follow any special indentation rules.
Literals
• A constant value in java is created by using a literal representation of it.
• A literal can be used anywhere a value of its type is allowed.
Comments
There are 3 types of comment in java.
• First is single line comment and the second one is multi line comment.
Separators
There are few symbols in java that are used as separators.
• The most commonly used separator in java is the semicolon ' ; '. some other
separators are Parentheses '( )' , Braces ' {} ' , Bracket ' [] ' , Comma ' , '
, Period ' . ' .
Java Keywords
• There are 49 reserved keywords currently defined in java.
• The Keywords are : abstract , assert , boolean , break , byte , case , catch ,
char , class , const , continue , default , do , double , else , extends , final ,
finally , float , for , goto , if , implements , import , instanceof , int interface,
long , native , new , package , private , protected , public , return , short ,
static , strictfp , super , switch , synchronized , this , throw , throws ,
transient , try , void , volatile, while.
Java Class Libraries
• The java environment relies on several built-in class libraries that contain
many built-in methods that provide support for such things as I/O , string
handling , networking and graphics.
• The standard class also provide support for windowed output. Thus java as
a totality is a combination of the java language itself , plus its standard
classes.
PRIMITIVE DATA TYPES
• Primitive data types are those data types that are predefined in the Java
programming language.
• There are a total of eight primitive data types that are predefined in the
Java programming language.
• The size of the primitive data types does not change with changing the
operating system because the Java programming language is independent of
all the operating systems.
• For example: byte, short, int, long, double, float, boolean, char
Data Type Size Description
byte 1 byte Stores whole numbers from -128 to 127. Default Value is 0.
short 2 bytes Stores whole numbers from -32,768 to 32,767. Default Value is 0.
int 4 bytes Stores whole numbers from -2,147,483,648 to 2,147,483,647. Default Value is 0.
float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits. Default Value is
0.0f.
double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits. Default Value is
0.0d.
char 2 bytes Stores a single character/letter or ASCII values. Default Value is '\u0000'
1. boolean
• The boolean data type has two possible values, either true or false.
• Default value: false.
• They are usually used for true/false conditions.
• Example:
class Main
{
public static void main(String[] args)
{
boolean flag = true;
System.out.println(flag); // prints true
}
}
2. byte
• The byte data type can have values from -128 to 127 (8-bit signed two's complement
integer).
• If it's certain that the value of a variable will be within -128 to 127, then it is used instead
of int to save memory.
• Default value: 0
• Example:
class Main
{
public static void main(String[] args)
{
byte range;
range = 124;
System.out.println(range); // prints 124
}
}
3. short
• The short data type in Java can have values from -32768 to 32767 (16-bit signed two's
complement integer).
• If it's certain that the value of a variable will be within -32768 and 32767, then it is used
instead of other integer data types (int, long).
• Default value: 0
• Example:
class Main
{
public static void main(String[] args)
{
short temperature;
temperature = -200;
System.out.println(temperature); // prints -200
}
}
4. int
• The int data type can have values from -231 to 231-1 (32-bit signed two's complement
integer).
• If you are using Java 8 or later, you can use an unsigned 32-bit integer. This will have a
minimum value of 0 and a maximum value of 232-1.
• Default value: 0
• Example:
class Main
{
public static void main(String[] args)
{
int range = -4250000;
System.out.println(range); // print -4250000
}
}
5. long
• The long data type can have values from -263 to 263-1 (64-bit signed two's complement
integer).
• If you are using Java 8 or later, you can use an unsigned 64-bit integer with a minimum
value of 0 and a maximum value of 264-1.
• Default value: 0
• Example:
class LongExample
{
public static void main(String[] args)
{
long range = -42332200000L;
System.out.println(range); // prints -42332200000
}
}
6. float
• he float data type is a single-precision 32-bit floating-point. Learn more about single-
precision and double-precision floating-point if you are interested.
• It should never be used for precise values such as currency.
• Default value: 0.0 (0.0f)
• Example: • Notice that we have used -
instead of -42.3 in the
42.3f
class Main
{
public static void main(String[] args)
{
double number = -42.3;
System.out.println(number); // prints -42.3
}
}
8. char
• It's a 16-bit Unicode character.
• The minimum value of the char data type is '\u0000' (0) and the maximum value of the is
'\uffff'.
• Default value: '\u0000’
• Example:
class Main {
public static void main(String[] args)
{
char letter = '\u0051';
System.out.println(letter); // prints Q
char letter1 = '9';
System.out.println(letter1); // prints 9
char letter2 = 65;
System.out.println(letter2); // prints A
}
}
• Example:
class Main
{
public static void main(String[] args)
{
char letter = '\u0051';
System.out.println(letter); // prints Q
char letter1 = '9';
System.out.println(letter1); // prints 9
char letter2 = 65;
System.out.println(letter2); // prints A
}
}
TYPE CONVERSION AND CASTING
• Type casting is a mechanism in which one data type is converted to another
data type using a casting () operator by a programmer.
• Example:
Narrowing Casting (manually) - converting a larger type to a smaller type
double -> float -> long -> int -> char -> short -> byte
• Type conversion allows a compiler to convert one data type to another data
type at the compile time of a program or code.
• Example:
Widening Casting (automatically) - converting a small type to a larger type
byte -> short -> char -> int -> long -> float -> double
Difference between Type Casting and Type Conversion
VARIABLES
• A variable is the holder that can hold the value while the java program is executed.
• There are three types of variables in java: local, instance and static.
• A variable provides us with named storage that our programs can manipulate.
• Each variable in Java has a specific type, which determines the size and layout of the
variable’s memory; the range of values that can be stored within that memory; and the set
of operations that can be applied to the variable.
• Before using any variable, it must be declared.
• Here data type is one of Java’s data types and variable is the name of the variable.
• To declare more than one variable of the specified type, use a comma-separated list.
Example:
• int a, b, c; // Declaration of variables a, b, and c.
• int a = 20, b = 30; // initialization
• byte B = 22; // Declaration initializes a byte type variable B.
Types of Variable
• A variable declared inside the class but outside the method, is called instance variable.
• Instance variables are declared in a class, but outside a method, constructor or any block.
• A slot for each instance variable value is created when a space is allocated for an object in
the heap.
• Instance variables are created when an object is created with the use of the keyword ‘new’
and destroyed when the object is destroyed.
• Instance variables hold values that must be referenced by more than one method,
constructor or block, or essential parts of an object’s state that must be present throughout
the class.
• Instance variables can be declared in class level before or after use.
• Access modifiers can be given for instance variables.
Instance Variable
• The instance variables are visible for all methods, constructors and block in the class. It is
recommended to make these variables as private. However, visibility for subclasses can
be given for these variables with the use of access modifiers.
• However, within static methods (when instance variables are given accessibility), they
• should be called using the fully qualified name. ObjectReference.VariableName.
Static Variable
• Class variables also known as static variables are declared with the static keyword in a
class, but outside a method, constructor or a block.
• Only one copy of each class variable per class is created, regardless of how many objects
are created from it.
• Static variables are rarely used other than being declared as constants. Constants are
variables that are declared as public/private, final, and static. Constant variables never
change from their initial value.
• Static variables are stored in the static memory. It is rare to use static variables other than
declared final and used as either public or private constants.
• Static variables are created when the program starts and destroyed when the program
stops.
• Visibility is same as instance variables.
• However, most static variables are declared public since they must be available for users
of the class.
Static Variable
class LearningVariables
{
static int x =10; //This is a static variable
int y = 15; // This is an instance variable
void method ( )
{
int z = 20; // This is a local variable
}
}
Example for local variable:
import java.io.*;
public class A
{
public void TeacherAge()
{
int age = 25; // local variable
System.out.println("a = " + age);
}
public static void main(String args[])
{
A obj = new A();
obj.TeacherAge();
}
}
Example for instance variable:
import java.io.*;
class Marks
{
int engMarks; //instance variable
}
class MarksDemo
{
public static void main(String args[])
{
Marks obj = new Marks();
obj.engMarks = 50;
System.out.println("Marks = " + obj.engMarks);
}
}
Example for static variable:
import java.io.*;
class Emp
{
public static double salary; //static variable
public static String name = "Tuhin";
}
public class EmpDemo
{
public static void main(String args[])
{
Emp.salary = 1000;
System.out.println(Emp.name);
System.out.println(Emp.salary);
}
}
ARRAYS
• Array is a collection of similar type of elements that have contiguous memory location.
• In Java all arrays are dynamically allocated.
• Since arrays are objects in Java, we can find their length using member length.
• A Java array variable can also be declared like other variables with [] after the data type.
• The variables in the array are ordered and each have an index beginning from 0.
• Java array can be also be used as a static field, a local variable or a method parameter.
• The size of an array must be specified by an int value and not long or short.
• The direct superclass of an array type is Object.
• Every array type implements the interfaces Cloneable and java.io.Serializable.
Advantage of Java Array
• Code Optimization: It makes the code optimized, we can retrieve or sort the data easily.
• Random access: We can get any data located at any index position.
Syntax:
• type var-name[ ];
• Multidimensional arrays are arrays of arrays with each element of the array holding the
reference of other array.
• These are also known as Jagged Arrays. A multidimensional array is created by
appending one set of square brackets ([]) per dimension.
Syntax:
type var-name[ ][ ]=new type[row-size ][col-size ];
Multidimensional Arrays
• Java String class provides a lot of methods to perform operations on string such as compare(), concat(),
equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.
• The java.lang.String class provides many useful methods to perform operations on sequence of char values.
The following program is an example for String concat function:
class string_method
{
public static void main(String args[]) Output:
{ Java Programming
String s=”Java”;
s=s.concat(“ Programming”);
System.out.println(s);
}
}
VECTOR CLASS
• Vector is like the dynamic array which can grow or shrink its size.
• Unlike array, we can store n-number of elements in it as there is no size limit.
• It is a part of Java Collection framework since Java 1.2.
• It is found in the java.util package and implements the List interface, so we can use all the methods of List
interface here.
• It is recommended to use the Vector class in the thread-safe implementation only.
• If you don't need to use the thread-safe implementation, you should use the ArrayList, the ArrayList will
perform better in such case.
• The Iterators returned by the Vector class are fail-fast.
• In case of concurrent modification, it fails and throws the ConcurrentModificationException.
• It is similar to the ArrayList, but with two differences-
• Vector is synchronized.
• Java Vector contains many legacy methods that are not the part of a collections framework.
Vector Constructor
Vector Methods
Vector Methods
Vector Methods
Vector Methods
Vector Methods
Vector Example
Output:
Examples
3+5 // uses + operator
14+5-4*(5-3) // uses +, -, * operators
Types of operators in Java:
1. Arithmetic Operators
2. Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
8. Shift Operators
9. Instance of operator
Java Operator Precedence
• * : Multiplication
• / : Division
• % : Modulo
• + : Addition
• – : Subtraction
Example
// Arithmetic Operators
import java.io.*;
// Drive Class
class GFG
{
// Main Function
public static void main (String[] args) Output
{
int a = 10;
• Addition:30
int b = 3; • Substraction:10
System.out.println("a + b = " + (a + b));
System.out.println("a - b = " + (a - b));
• Multiplication:200
System.out.println("a * b = " + (a * b)); • Division:2
System.out.println("a / b = " + (a / b));
System.out.println("a % b = " + (a % b));
}
}
2.Unary Operators
The Java unary operators require only one operand. Unary operators are used to perform various operations i.e.:
Example 1 : ++ and –
Output
10
public class OperatorExample 12
{
public static void main(String args[])
12
{ 10
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
}
}
Example 2:
Output:
public class OperatorExample
{
-11
public static void main(String args[]) 9
{ false
int a=10; true
int b=-10;
boolean c=true;
boolean d=false;
System.out.println(~a);//-11 (minus of total positive value which starts from 0)
System.out.println(~b);//9 (positive of total minus, positive starts from 0)
System.out.println(!c);//false (opposite of boolean value)
System.out.println(!d);//true
}
}
3. Assignment Operator
• The assignment operator can be combined with other operators to build a shorter version of the statement
called a Compound Statement.
• +=, for adding the left operand with the right operand and then assigning it to the variable on the left.
• -=, for subtracting the right operand from the left operand and then assigning it to the variable on the left.
• *=, for multiplying the left operand with the right operand and then assigning it to the variable on the left.
• /=, for dividing the left operand by the right operand and then assigning it to the variable on the left.
• %=, for assigning the modulo of the left operand by the right operand and then assigning it to the variable
on the left.
import java.io.*;
Output:
class GFG
{ f += 3: 10
public static void main(String[] args)
f -= 2: 8
{
int f = 7; f *= 4: 32
System.out.println("f += 3: " + (f += 3));
f /= 3: 10
System.out.println("f -= 2: " + (f -= 2));
System.out.println("f *= 4: " + (f *= 4)); f %= 2: 0
System.out.println("f /= 3: " + (f /= 3));
f &= 0b1010: 0
System.out.println("f %= 2: " + (f %= 2));
System.out.println("f &= 0b1010: " + (f &= 0b1010)); f |= 0b1100: 12
System.out.println("f |= 0b1100: " + (f |= 0b1100));
f ^= 0b1010: 6
System.out.println("f ^= 0b1010: " + (f ^= 0b1010));
System.out.println("f <<= 2: " + (f <<= 2)); f <<= 2: 24
System.out.println("f >>= 1: " + (f >>= 1));
f >>= 1: 12
System.out.println("f >>>= 1: " + (f >>>= 1));
} f >>>= 1: 6
}
4. Relational Operators
These operators are used to check for relations like equality, greater than, and less than.
The general format is,
variable relation_operator value
• ==, Equal to returns true if the left-hand side is equal to the right-hand side.
• !=, Not Equal to returns true if the left-hand side is not equal to the right-hand side.
• <, less than: returns true if the left-hand side is less than the right-hand side.
• <=, less than or equal to returns true if the left-hand side is less than or equal to the right-hand side.
• >, Greater than: returns true if the left-hand side is greater than the right-hand side.
• >=, Greater than or equal to returns true if the left-hand side is greater than or equal to the right-hand side.
import java.io.*;
class GFG
{
Output:
public static void main(String[] args)
{ a > b: true
int a = 10; a < b: false
int b = 3; a >= b: true
int c = 5; a <= b: false
System.out.println("a > b: " + (a > b));
a == c: false
System.out.println("a < b: " + (a < b));
System.out.println("a >= b: " + (a >= b)); a != c: true
System.out.println("a <= b: " + (a <= b));
System.out.println("a == c: " + (a == c));
System.out.println("a != c: " + (a != c));
}
}
5. Logical Operators
These operators are used to perform “logical AND” and “logical OR” operations,
i.e., a function similar to AND gate and OR gate in digital electronics.
• &&, Logical AND: returns true when both conditions are true.
• ||, Logical OR: returns true if at least one condition is true.
• !, Logical NOT: returns true when a condition is false and vice-versa
Example:
import java.io.*;
class GFG
{
public static void main (String[] args) Output
{
x && y: false
boolean x = true;
x || y: true
boolean y = false;
!x: false
System.out.println("x && y: " + (x && y));
System.out.println("x || y: " + (x || y));
System.out.println("!x: " + (!x));
}
}
6. Ternary operator
The ternary operator is a shorthand version of the if-else statement. It has three operands and hence the name Ternary.
Output
Max of three numbers = 30
7. Bitwise Operators
• These operators are used to perform the manipulation of individual bits of a number.
• can be used with any of the integer types.
• used when performing update and query operations of the Binary indexed trees.
• &, Bitwise AND operator: returns bit by bit AND of input values.
• |, Bitwise OR operator: returns bit by bit OR of input values.
• ^, Bitwise XOR operator: returns bit-by-bit XOR of input values.
• ~, Bitwise Complement Operator: This is a unary operator which returns the one’s
complement representation of the input value, i.e., with all bits inverted.
import java.io.*;
class GFG
{
public static void main(String[] args) Output :
{
int d = 0b1010; d & e: 8
int e = 0b1100;
System.out.println("d & e: " + (d & e));
d | e: 14
System.out.println("d | e: " + (d | e)); d ^ e: 6
System.out.println("d ^ e: " + (d ^ e));
System.out.println("~d: " + (~d)); ~d: -11
System.out.println("d << 2: " + (d << 2));
System.out.println("e >> 1: " + (e >> 1));
d << 2: 40
System.out.println("e >>> 1: " + (e >>> 1)); e >> 1: 6
}
} e >>> 1: 6
8. Shift Operators
General format-
• <, Left shift operator: shifts the bits of the number to the left and fills 0 on voids left as a result. Similar
effect as multiplying the number with some power of two.
• >>, Signed Right shift operator: shifts the bits of the number to the right and fills 0 on voids left as a
result. The leftmost bit depends on the sign of the initial number. Similar effect to dividing the number
with some power of two.
• >>>, Unsigned Right shift operator: shifts the bits of the number to the right and fills 0 on voids left as a
result. The leftmost bit is set to 0.
import java.io.*;
// Driver Class
class GFG
{
// main function Output
public static void main(String[] args)
a<<1 : 20, a>>1 : 5
{
int a = 10;
System.out.println("a<<1 : " + (a << 1));
System.out.println("a>>1 : " + (a >> 1));
}
}
9. Instance of operator
1) Simple if
2) if-else
3) if-else-if ladder
4) switch
1. Simple if
Syntax :
Example:
if(condition)
public class Student
{
{
statement 1; //executes when condition is true
public static void main(String[] args)
}
{
int x = 10;
int y = 12;
if(x+y > 20)
{
System.out.println("x + y is greater than 20");
}
}
}
Output:
x + y is greater than 20
2. if-else
Syntax: Example:
if(condition) public class Student
{ {
statement 1; //executes when condition is true public static void main(String[] args)
} {
else int x = 10;
{ int y = 12;
statement 2; //executes when condition is false if(x+y < 10)
} {
System.out.println("x + y is less than10");
}
else
{
System.out.println("x + y is greater than 20");
}
}
}
Output:
x + y is greater than 20
3. if-else–if ladder
The if-else-if ladder statement executes one condition from multiple statements.
Example:
public class Student
{
public static void main(String[] args)
Syntax of if-else-if : {
if(condition 1) String city = "Delhi";
if(city == "Meerut")
{
{
statement 1; //executes when condition 1 is true System.out.println("city is meerut");
} }
else if(condition 2) else if (city == "Noida")
{ {
statement 2; //executes when condition 2 is true System.out.println("city is noida");
}
} else if(city == "Agra")
else {
{ System.out.println("city is agra");
statement 2; //executes when all the conditions are false }
} else
{
System.out.println(city);
}
}
}
Output:
Delhi
4. Nested 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
}
Example:
public class JavaNestedIfExample2
{
public static void main(String[] args)
{
int age=25; Output:
int weight=48; You are not eligible to donate blood
if(age>=18)
{
if(weight>50)
{
System.out.println("You are eligible to donate blood");
}
else
{
System.out.println("You are not eligible to donate blood");
}
}
else
{
System.out.println("Age must be greater than 18");
}
}
}
5. Java Switch Statement
• The Java switch statement executes one statement from multiple conditions.
• It is like if-else-if ladder statement.
• The switch statement works with byte, short, int, long, enum types, String and some
wrapper types like Byte, Short, Int, and Long.
• There can be one or N number of case values for a switch expression.
• The case value must be of switch expression type only.
• The case value must be literal or constant. It doesn't allow variables.
• The case values must be unique. In case of duplicate value, it renders compile-time error.
• Each case statement can have a break statement which is optional.
• When control reaches to the break statement, it jumps the control after the switch
expression. If a break statement is not found, it executes the next case.
• The case value can have a default label which is optional.
Syntax:
switch(expression)
{
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
}
Example:
public class SwitchExample
{
public static void main(String[] args)
{
int number=20;
switch(number)
{
case 10: System.out.println("10"); Output:
break; 20
case 20: System.out.println("20");
break;
case 30: System.out.println("30");
break;
default:System.out.println("Not in 10, 20 or 30");
}
}
}
Loop / Iterative Statement
1. For loop
2. While loop
3. Do-while loop
1. for loop
For loop can initialize the variable, check condition and increment/decrement value. It consists
of four parts:
1. Initialization: It is the initial condition which is executed once when the loop starts. Here, we
can initialize the variable, or we can use an already initialized variable. It is an optional
condition.
2. Condition: It is the second condition which is executed each time to test the condition of the
loop. It continues execution until the condition is false. It must return boolean value either true or
false. It is an optional condition.
3. Increment/Decrement: It increments or decrements the variable value. It is an optional
condition.
4. Statement: The statement of the loop is executed each time until the second condition is false.
Syntax:
for(initialization; condition; increment/decrement)
{
//statements (For Body)
}
// Java Program to demonstrate the example of
Output
for loop which prints table of 1 1
public class ForExample 2
{ 3
public static void main(String[] args) 4
5
{
6
for(int i=1;i<=10;i++) 7
{ 8
System.out.println(i); 9
} 10
}
}
Nested for loop
• a for loop inside the another loop, it is known as nested for loop.
• The inner loop executes completely whenever outer loop executes.
public class PyramidExample
{ Output
public static void main(String[] args)
*
{
**
for(int i=1;i<=5;i++) ***
{ ****
for(int j=1;j<=i;j++) *****
{
System.out.print("* ");
}
System.out.println(); //new line
}
}
}
2. while loop
The Java while loop is used to iterate a part of the program repeatedly until the
specified Boolean condition is true. As soon as the Boolean condition becomes false,
the loop automatically stops.
Note: important thing about while loop is that, sometimes it may not even execute. If
the condition to be tested results into false, the loop body is skipped and first
statement after the while loop will be executed.
Syntax:
while (condition)
{
//code to be executed
increment / decrement statement
}
Example:
public class WhileExample Output
{ 1
public static void main(String[] args) 2
{
3
int i=1;
while(i<=10) 4
{ 5
System.out.println(i); 6
i++; 7
}
8
}
} 9
10
3. do while loop
The Java do-while loop is used to iterate a part of the program repeatedly, until the specified condition
is true.
Note: If the number of iteration is not fixed and have to execute the loop at least once, it is
recommended to use a do-while loop.
The different parts of do-while loop:
1. Condition: It is an expression which is tested. If the condition is true, the loop body is executed and
control goes to update expression. As soon as the condition becomes false, loop breaks automatically.
Example:
i <=100
2. Update expression: Every time the loop body is executed, the this expression increments or
decrements loop variable.
Example:
i++;
Syntax do while loop: Example:
do public class DowhileExample Output:
{ { 1
//code to be executed / loop body public static voidW main(String[] args) 2
//update statement { 3
}while (condition); int i=1; 4
do 5
{ 6
System.out.println(i); 7
i++; 8
}while(i<=10); 9
} 10
}
Flow control / Jump Statement
Jumping statements are control statements that transfer execution control from one point to another point in the
program.
There are two Jump statements that are provided in the Java programming language:
1. Break statement.
2. Continue statement.
1. Break statement
Using Break Statement to exit a loop:
• In java, the break statement is used to terminate the execution of the nearest looping statement or switch
statement.
• The break statement is widely used with the switch statement, for loop, while loop, do-while loop.
Syntax:
break;
1. break
Example:
import java.io.*;
class GFG
{ Output
public static void main(String[] args)
{ 0
int n = 10; 1
for (int i = 0; i < n; i++)
{ 2
if (i == 6) 3
break;
System.out.println(i); 4
} 5
}
}
Use Break as a form of goto
class GFG
{
public static void main(String[] args)
• Java does not have a goto {
for (int i = 0; i < 3; i++)
statement because it produces an
{
unstructured way to alter the flow one : { // label one
of program execution. Output:
two : { // label two
three : { // label three
i=0
• Java illustrates an extended form after label one
System.out.println("i=" + i);
of the break statement. This form if (i == 0) i=1
of break works with the label. break one; // break to label one after label two
• The label is the name of a label if (i == 1)
after label one
that identifies a statement or a break two; // break to label two
if (i == 2) i=2
block of code. break three; // break to label three after label three
} after label two
System.out.println("after label three");
Syntax: }
after label one
break label; System.out.println("after label two");
}
System.out.println("after label one");
}
}
}
2. continue
Example:
import java.io.*;
The continue statement pushes the class GFG
next repetition of the loop to take {
place, hopping any code between Output:
public static void main(String[] args)
itself and the conditional 0
expression that controls the loop.
{
1
for (int i = 0; i < 10; i++)
2
{
3
if (i == 6)
4
{
5
System.out.println();
continue;
7
}
8
System.out.println(i);
9
}
}
}
Programs
1. Simple JAVA program using control structures, arrays and Vector Class
2. Sum of series (1 + 2+ 3+…..n,1+1/2+1/3 +……..1/n,12 + 22+ 32 +…….n2)
3. Write a Java program using all the operators.
4. Write a Java program using break and continue.
5. Write a Java program to find given number or text is palindrome or not?
6. Write a Java program to generate Fibonacci series upto given number?
7. Write a Java program to find given number is prime number or not?
8. Write a Java program to find matrix multiplication?
9. Write a Java program to implement all string functions.
10. Write a Java program to implement type casting and conversion.