Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
33 views181 pages

Aoop - Unit I

Uploaded by

s0m3one675
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)
33 views181 pages

Aoop - Unit I

Uploaded by

s0m3one675
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
You are on page 1/ 181

21CSC206P - ADVANCED OBJECT ORIENTED AND

PROGRAMMING

UNIT – I INTRODUCTION TO JAVA


UNIT - I

• Java programming Environment and Runtime Environment


• Development Platforms -Standard, Enterprise.
• Java Virtual Machine (JVM)
• Java compiler, Bytecode
• Java applet, Java Buzzwords
• Java program structure, Comments,
• Garbage Collection, Lexical Issues.
• Primitive Data types
• Type Conversion and Casting
• Variables, Arrays, Strings
• Vector class.
• Operators - Control Statements
• Selection Statements
• Iteration Statements and Jump Statements.
JAVA PROGRAMMING ENVIRONMENT AND
RUNTIME ENVIRONMENT
The Java Environment

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.

JRE = JVM + Libraries + Other files

What is JVM?

Now will see about JVM


JVM (Java Virtual Machine)
JVM (Java Virtual Machine) executes java code line by line.
Operations of JVM are:
● Class Loader : Loads code

● Byte code Verifier : Verifies code

● Execution Engine : Executes code

● Runtime Data Area: Provides runtime environment

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)

• JDK = JRE + Library Classes (development tools)

• Java Development Kit (JDK) is a software development environment used to develop java applications

• It physically exists

• JDK is an implementation of Java Platform by Oracle corporation(J2SE, J2EE and J2ME)


DEVELOPMENT PLATFORMS - STANDARD,
ENTERPRISE
• A Java platform is a particular environment in which Java programming language applications run.

There are four platforms of the Java programming language:


1. Java Platform, Standard Edition (Java SE)
2. Java Platform, Enterprise Edition (Java EE)
3. Java Platform, Micro Edition (Java ME)
4. JavaFX

• 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

To install the JDK installer, we need to head to Oracle’s website first.


1. Go to the Java Downloads section of the Oracle website, and download the x64 Installer from there.
2. As soon as the download completes, launch the installation file and click on Yes.
3. The JDK installation wizard will be launched. In the dialog box, click on Next.

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

Java program is compiled by javac tool.


Compiler generates bytecode (.class file).

Then byte code executed by interpreter (JVM).


To compile java program we have to set path.
Setting Temporary java Path in Windows
We are not using IDE like eclipse, netbeans etc.
Steps to set the temporary path java:

1. Open the command prompt

1. Copy the path of the JDK/bin directory


2. Write in command prompt: set path

Ex:

set path = C:\Program Files\Java\jdk1.8.0_40\bin;


Another way Setting permanent java Path in Windows
MyComputer -> properties -> advanced system setting -> advanced tab -> Select environment variables -> click new tab of user
variable

Variable name= path

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

• We can execute a Java application by following two steps.


• Compile the Java program
• Execute the application
• Compile the Java application: javac Basic.java
• Execute the Application: java Basic
Step by Step execution of the Java program
Steps
• Write Java code and save the file with .java
• Now, this file will be compiled using the Java compiler, which is javac.
• The Java Compiler will compile the Java file and create a .class file having
byte code ( which is not actually a machine code, unlike the C compiler)
• This generated byte code is a non-executable code, and now it needs an
interpreter to convert it into machine code. Here the JVM handles it.
• Now, JVM will execute this byte code to execute Java byte code on a
machine.
• Now, our program will perform the functionality and gives the desired
output.
JAVA BYTECODE

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

• When we write a program in Java, firstly, the compiler compiles that


program and a bytecode is generated for that piece of code.
• When we wish to run this .class file on any other platform, we can do so.
• After the first compilation, the bytecode generated is now run by the Java
Virtual Machine and not the processor in consideration.
• This essentially means that we only need to have basic java installation on
any platforms that we want to run our code on.
• Resources required to run the bytecode are made available by the Java
Virtual Machine, which calls the processor to allocate the required
resources.
• JVM's are stack-based so they stack implementation to read the codes.
JAVA APPLET
• An applet is a Java program that runs in a Web browser. An applet can be a
fully functional Java application because it has the entire Java API at its
disposal.
• There are some important differences between an applet and a standalone
Java application, including the following −
• An applet is a Java class that extends the java.applet.Applet class.
• A main() method is not invoked on an applet, and an applet class will not
define main().
• Applets are designed to be embedded within an HTML page.
• When a user views an HTML page that contains an applet, the code for the
applet is downloaded to the user's machine.
• A JVM is required to view an applet.
• The JVM can be either a plug-in of the Web browser or a separate runtime
environment.
• The JVM on the user's machine creates an instance of the applet class and
invokes various methods during the applet's lifetime.
• Applets have strict security rules that are enforced by the Web browser.
• The security of an applet is often referred to as sandbox security, comparing
the applet to a child playing in a sandbox with various rules that must be
followed.
• Other classes that the applet needs can be downloaded in a single Java
Archive (JAR) file.
Life Cycle of an Applet
•Four methods in the Applet class gives you the framework on which you build
any serious applet −

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

Following is a simple applet named HelloWorldApplet.java −


import java.applet.*;
import java.awt.*;
public class HelloWorldApplet extends Applet
{
public void paint (Graphics g)
{
g.drawString ("Hello World", 25, 50);
}
}
•These import statements bring the classes into the scope of our applet class −
•java.applet.Applet
•java.awt.Graphics
•Without those import statements, the Java compiler would not recognize the classes
Applet and Graphics, which the applet class refers to.
The Applet Class

• Every applet is an extension of the java.applet.Applet class.


• The base Applet class provides methods that a derived Applet class may call
to obtain information and services from the browser context.
• These include methods that do the following −
• Get applet parameters
• Get the network location of the HTML file that contains the applet
• Get the network location of the applet class directory
• Print a status message in the browser
• Fetch an image
• Fetch an audio clip
• Play an audio clip
• Resize the applet
• Additionally, the Applet class provides an interface by which the viewer or
browser obtains information about the applet and controls the applet's
execution. The viewer may −
• Request information about the author, version, and copyright of the applet
• Request a description of the parameters the applet recognizes
• Initialize the applet
• Destroy the applet
• Start the applet's execution
• Stop the applet's execution
• The Applet class provides default implementations of each of these
methods.
• Those implementations may be overridden as necessary.
• The "Hello, World" applet is complete as it stands.
• The only method overridden is the paint method.
Java Buzzwords or Features of Java
The Java programming language is a high-level language that can be
characterized by all of the following buzzwords:
1. Simple
2. Object-oriented
3. Distributed
4. Interpreted
5. Robust
6. Secure
7. Architecture neutral
8. Portable
9. High performance
10. Multithreaded
11. Dynamic
1. Simple

• 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

• Java is a true object-oriented programming language.


• Almost the “Everything is an Object” paradigm. All program code and data
reside within objects and classes.
• The object model in Java is simple and easy to extend.
• Java comes with an extensive set of classes, arranged in packages that can
be used in our programs through inheritance.
• Object-oriented programming (OOPs) is a methodology that simplifies
software development and maintenance by providing some rules.
The basic concepts of OOPs are:

• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation
3. Distributed

• Java is designed to create distributed applications on networks.


• Java applications can access remote objects on the Internet as easily as they
can do in the local system.
• Java enables multiple programmers at multiple remote locations to
collaborate and work together on a single project.
• Java is designed for the distributed environment of the Internet because it
handles TCP/IP protocols.
4. Compiled and Interpreted

• Usually, a computer language is either compiled or Interpreted. Java


combines both this approach and makes it a two-stage system.
• Compiled: Java enables the creation of cross-platform programs by
compiling them into an intermediate representation called Java Bytecode.
• Interpreted: Bytecode is then interpreted, which generates machine code
that can be directly executed by the machine that provides a Java Virtual
machine.
5. Robust

• It provides many features that make the program execute reliably in a


variety of environments.
• Java is a strictly typed language. It checks code both at compile time and
runtime.
• Java takes care of all memory management problems with garbage
collection.
• Java, with the help of exception handling, captures all types of serious errors
and eliminates any risk of crashing the system.
6. Secure

• Java provides a “firewall” between a networked application and your


computer.
• When a Java Compatible Web browser is used, downloading can be done
safely without fear of viral infection or malicious intent.
• Java achieves this protection by confining a Java program to the Java
execution environment and not allowing it to access other parts of the
computer.
7. Architecture Neutral

• 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

• Java Provides a way to download programs dynamically to all the various


types of platforms connected to the Internet.
• Java is portable because of the Java Virtual Machine (JVM). The JVM is an
abstract computing machine that provides a runtime environment for Java
programs to execute.
• The JVM provides a consistent environment for Java programs to run on,
regardless of the underlying hardware and operating system.
• This means that a Java program can be written on one device and run on any
other device with a JVM installed, without any changes or modifications
9. High Performance

• Java performance is high because of the use of bytecode.


• The bytecode was used so that it can be easily translated into native machine
code.
10. Multithreaded

• Multithreaded Programs handled multiple tasks simultaneously, which was


helpful in creating interactive, networked programs.
• Java run-time system comes with tools that support multiprocess
synchronization used to construct smoothly interactive systems.
11. Dynamic

• Java is capable of linking in new class libraries, methods, and objects.


• Java programs carry with them substantial amounts of run-time type
information that is used to verify and resolve accesses to objects at runtime.
• This makes it possible to dynamically link code in a safe and expedient
manner.
STRUCTURE OF JAVA PROGRAM

• Java is an object-oriented programming, platform-


independent, and secure programming language that makes it popular.

• Using the Java programming language, we can develop a wide variety of


applications.

• So, before diving in depth, it is necessary to understand the basic structure


of Java program in detail.

• In this section, we have discussed the basic structure of a Java program.


At the end of this section, you will able to develop the Hello world Java
program, easily.
Let's see which elements are included in the structure of a Java program.
A typical structure of a Java program contains the following elements:
• Documentation Section

• Package Declaration

• Import Statements

• Interface Section

• Class Definition

• Class Variables and Variables

• Main Method Class

• Methods and Behaviors


Documentation Section

• The documentation section is an important section but optional for a Java


program.
• It includes basic information about a Java program. The information
includes the author's name, date of creation, version, program name,
company name, and description of the program.
• It improves the readability of the program. Whatever we write in the
documentation section, the Java compiler ignores the statements during the
execution of the program.
• To write the statements in the documentation section, we use comments.
The comments may be single-line, multi-
line, and documentation comments.
• Single-line Comment: It starts with a pair of forwarding slash (//).
For example:

//First Java Program


Multi-line Comment: It starts with a /* and ends with */.
We write between these two symbols. For example:
/*It is an example of
multiline comment*/
Documentation Comment: It starts with the delimiter (/**) and ends with */.
For example:
/**It is an example of documentation comment*/
Package Declaration

• The package declaration is optional. It is placed just after the documentation


section.
• In this section, we declare the package name in which the class is placed.
Note that there can be only one package statement in a Java program.
• It must be defined before any class and interface declaration. It is necessary
because a Java class can be placed in different packages and directories
based on the module they are used.
• For all these classes package belongs to a single parent directory. We use
the keyword package to declare the package name. For example:
• package javatpoint; //where javatpoint is the package name
• package com.javatpoint; //where com is the root directory and javatpoint is
the subdirectory
Import Statements

• The package contains the many predefined classes and interfaces.


• If we want to use any class of a particular package, we need to import that
class.
• The import statement represents the class stored in the other package. We
use the import keyword to import the class.
• It is written before the class declaration and after the package statement.
• We use the import statement in two ways, either import a specific class or
import all classes of a particular package. In a Java program, we can use
multiple import statements. For example:
• import java.util.Scanner; //it imports the Scanner class only
• import java.util.*; //it imports all the class of the java.util package
Interface Section

• It is an optional section. We can create an interface in this section if required.


• We use the interface keyword to create an interface. An interface is a slightly different from the
class.
• It contains only constants and method declarations.
• Another difference is that it cannot be instantiated.
• We can use interface in classes by using the implements keyword.
• An interface can also be used with other interfaces by using the extends keyword. For example:
interface car
{
void start();
void stop();
}
Class Definition
• In this section, we define the class. It is vital part of a Java program.
• Without the class, we cannot create any Java program.
• A Java program may conation more than one class definition.
• We use the class keyword to define the class.
• The class is a blueprint of a Java program.
• It contains information about user-defined methods, variables, and
constants.
• Every Java program has at least one class that contains the main() method.
• For example:
class Student //class definition
{
}
Class Variables and Constants
• In this section, we define variables and constants that are to be used later in the
program.
• In a Java program, the variables and constants are defined just after the class
definition. The variables and constants store values of the parameters.
• It is used during the execution of the program. We can also decide and define the
scope of variables by using the modifiers.
• It defines the life of the variables. For example:
class Student //class definition
{
String sname; //variable
int id;
double percentage;
}
Main Method Class

• In this section, we define the main() method.


• It is essential for all Java programs.
• Because the execution of all Java programs starts from the main() method.
In other words, it is an entry point of the class.
• It must be inside the class. Inside the main method, we create objects and
call the methods.
• We use the following statement to define the main() method:
public static void main(String args[])
{

}
For example:

public class Student //class definition


{
public static void main(String args[])
{
//statements
}
}
Methods and Behavior

• 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

• There are three types of comments in Java.


• Single Line Comment
• Multi Line Comment
• Documentation Comment
Java Single Line Comment

• 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

public class CommentExample1


{
public static void main(String[] args)
{
int i=10; // i is a variable with value 10
System.out.println(i); //printing the variable i
}
}

Output: 10
Java Multi Line Comment

• The multi-line comment is used to comment multiple lines of code.


• It can be used to explain a complex code snippet or to comment multiple lines of
code at a time (as it will be difficult to use single-line comments there).
• Multi-line comments are placed between /* and */. Any text between /* and */ is
not executed by Java.
• Syntax:
/*
This
is
multi line
comment
*/
CommentExample2.java
public class CommentExample2
{
public static void main(String[] args)
{
/* Let's declare and
print variable in java. */
int i=10;
System.out.println(i);
/* float j = 5.9;
float k = 4.4;
System.out.println( j + k ); */
}
}

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?

• As we know, Java comments are not executed by the compiler or


interpreter, however, before the lexical transformation of code in compiler,
contents of the code are encoded into ASCII in order to make the processing
easy.
• The above code generate the output because the compiler parses the
Unicode character \u000d as a new line before the lexical transformation,
and thus the code is transformed as shown below:
• Test.java
public class Test
{
public static void main(String[] args)
{
System.out.println("Java comment is executed!!");
}
}
• Thus, the Unicode character shifts the print statement to next line and it is
executed as a normal Java code.
JAVA GARBAGE COLLECTION
• In java, garbage means unreferenced objects.
• Garbage Collection is process of reclaiming the runtime unused memory
automatically. In other words, it is a way to destroy the unused objects.
• To do so, we were using free() function in C language and delete() in C++.
But, in java it is performed automatically. So, java provides better memory
management.
• Advantage of Garbage Collection
• It makes java memory efficient because garbage collector removes the
unreferenced objects from heap memory.
• It is automatically done by the garbage collector(a part of JVM) so we
don't need to make extra efforts.
How can an object be unreferenced?

• There are many ways:


• By nulling the reference
• By assigning a reference to another
• By anonymous object etc.
1) By nulling a reference:
Employee e=new Employee();
e=null;

2) By assigning a reference to another:


Employee e1=new Employee();
Employee e2=new Employee();
e1=e2;//now the first object referred by e1 is available for garbage collection

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

public class TestGarbage1


{
public void finalize()
{
System.out.println("object is garbage collected");
}
public static void main(String args[])
{
TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null;
System.gc();
}
}
Output: object is garbage collected object is garbage collected
LEXICAL ISSUES IN JAVA

• Java programs is a collection of White spaces, Identifiers, comments,


Literals, Operators, Separators and Keywords.

White Spaces
• Java is a free form language.

• This means that you do not need to follow any special indentation rules.

• In java , white spaces is a space , tab or new line.


Identifiers
• Identifiers are used for class names , method names and variable names.
• An identifier may be any descriptive sequence of uppercase and lowercase
letters , numbers or the underscore and dollar sign design.

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.

• The third type of comment is called documentation comment. It is used to


produce an HTML file that documents your program.
• It begins with a/** and ends with a*/.

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.

• These keywords cannot be used as names for a variable , class or method.

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

long 8 bytes Stores whole numbers from -9,223,372,036,854,775,808 to


9,223,372,036,854,775,807. Default Value is 0L.

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.

boolean 1 bit Stores true or false values. Default Value is false.

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


{ • It's because -42.3 is
public static void main(String[] args) a double literal.
{
• To tell the compiler to treat -
float number = -42.3f; 42.3 as float rather than double,
System.out.println(number); // prints -42.3 you need to use f or F.
}
}
7. double

• The double data type is a double-precision 64-bit floating-point.


• It should never be used for precise values such as currency.
• Default value: 0.0 (0.0d)
• Example:

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.

• A variable is assigned with a datatype.

• It is name of reserved area allocated in memory. In other words, it is a name of memory


location.

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

• The following statement expresses the basic form of a variable declaration :

datatype variable [ = value][, variable [ = value] ...] ;

• 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

There are three types of variables in java:


• local variable
• instance variable
• static variable
Local Variable

• Local variables are declared inside the methods, constructors, or blocks.


• Local variables are created when the method, constructor or block is entered
• Local variable will be destroyed once it exits the method, constructor, or block.
• Local variables are visible only within the declared method, constructor, or block.
• Local variables are implemented at stack level internally.
• There is no default value for local variables, so local variables should be declared and an
initial value should be assigned before the first use.
• Access specifiers cannot be used for local variables.
Instance 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.

• Instance variables have default values.


○ numbers, the default value is 0,
○ Booleans it is false,
○ Object references it is null.

• Values can be assigned during the declaration or within the constructor.


• Instance variables cannot be declared as static.
• Instance variables can be accessed directly by calling the variable name inside the class.

• 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

• Default values are same as instance variables.


○ numbers, the default value is 0;
○ Booleans, it is false;
○ Object references, it is null.
• Values can be assigned during the declaration or within the constructor. Additionally,
values can be assigned in special static initializer blocks.
• Static variables cannot be local.
• Static variables can be accessed by calling with the class name ClassName.
VariableName.
• When declaring class variables as public static final, then variable names (constants) are
all in upper case.
• If the static variables are not public and final, the naming syntax is the same as instance
and local variables.
Example for local, instance and static variables:

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.

Disadvantage of Java Array


• Size Limit: We can store only fixed size of elements in the array. It doesn't grow its size at runtime.
• To solve this problem, collection framework is used in java.

Types of Array in java


1. One- Dimensional Array
2. Multidimensional Array
One-Dimensional Arrays

• An array is a group of like-typed variables that are referred to by a common name.


• An array declaration has two components: the type and the name.
• type declares the element type of the array.
• The element type determines the data type of each element that comprises the array.
• We can also create an array of other primitive data types like char, float, double..etc or
user defined data type(objects of a class).
• Thus, the element type for the array determines what type of data the array will hold.

Syntax:
• type var-name[ ];

Instantiation of an Array in java


• array-var = new type [size];
Example:
class Testarray
{
public static void main(String args[]){ Output:
int a[]=new int[5]; //declaration and instantiation 10
a[0]=10; //initialization 20
a[1]=20; 70
a[2]=70; 40
a[3]=40; 50
a[4]=50;
for(int i=0;i<a.length;i++) //length is the property of array
System.out.println(a[i]); //printing array
}
}
Example: Declaration, Instantiation and Initialization of Java Array
class Testarray1
{
public static void main(String args[]) Output:
{ 33
int a[]={33,3,4,5}; //declaration, instantiation and initialization 3
for(int i=0;i<a.length;i++) //length is the property of array 4
System.out.println(a[i]); //printing array 5
}
}
We can pass the java array to method so that we can reuse the same logic on any array.
Example:
class Testarray2
{
static void min(int arr[])
{
int min=arr[0];
for(int i=1;i<arr.length;i++) Output:
if(min>arr[i]) 3
min=arr[i];
System.out.println(min);
}
public static void main(String args[])
{
int a[]={33,3,4,5};
min(a);//passing array to method
}
}
Multidimensional Arrays

• 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

Example: // Demonstrate a two-dimensional array.


class TwoDArray
{
public static void main(String args[])
{
int twoD[][]= new int[4][5];
int i, j, k = 0; Output:
for(i=0; i<4; i++) 01234
{
for(j=0; j<5; j++) 56789
twoD[i][j] = k;
10 11 12 13 14
k++; 15 16 17 18 19
}
for(i=0; i<4; i++)
{
for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}
STRINGS
• In general string is a sequence of characters. String is an object that represents a sequence of characters.
• The java.lang.String class is used to create string object.
• In java, string is basically an object that represents sequence of char values. An array of characters works
same as java string. For example:

• 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 implements Serializable, Comparable and CharSequence interfaces.


• The CharSequence interface is used to represent sequence of characters.
• It is implemented by String, StringBuffer and StringBuilder classes.
• It means can create string in java by using these 3 classes.

The string objects can be created using two ways.


1. By String literal
2. By new Keyword
1. String Literal
• Java String literal is created by using double quotes.
• For Example:
String s=”welcome”;
• Each time you create a string literal, the JVM checks the string constant pool first. If the string
already exists in the pool, a reference to the pooled instance is returned. If string doesn’t exist in
the pool, a new string instance is created and placed in the pool.
• For example:
String s1=”Welcome”;
String s2=”Welcome”;
• In the above example only one object will be created.
• Firstly JVM will not find any string object with the value “Welcome” in string constant pool, so it
will create a new object.
• After that it will find the string with the value “Welcome” in the pool, it will not create new object
but will return the reference to the same instance.
• To make Java more memory efficient.
2. By new keyword

• String s=new String(“Welcome”);


• In such case, JVM will create a new string object in normal (non pool) heap memory and
the literal “Welcome” will be placed in the string constant pool.
• The variable s will refer to the object in heap (non pool).
• The java String is immutable i.e. it cannot be changed.
• Whenever we change any string, a new instance is created.
• For mutable string, you can use StringBuffer and StringBuilder classes.
Example:
public class String_Example
{
public static void main(String args[])
{
String s1=”java”;
char c[]={‘s’,’t’,’r’,’i’,’n’,’g’};
String s2=new String(c);
String s3=new String(“example”);
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}
}
Java String class methods

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

Elements are: [Tiger, Lion, Dog,


Elephant, Rat, Cat, Deer]
OPERATORS

• Operators are symbols used to perform operations on variables and values.


• Operators are special symbols used for
- mathematical functions
- assignment Statements
- logical Comparisons

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

Operator Type Category Precedence


Unary postfix expr++ expr--
prefix ++expr --expr +expr -expr ~ !

Arithmetic multiplicative */%


additive +-
Shift shift << >> >>>
Relational comparison < > <= >= instanceof
equality == !=
Bitwise bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
Logical logical AND &&
logical OR ||
Ternary ternary ?:
Assignment assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=
1. Arithmetic Operators
They are used to perform simple arithmetic operations on primitive data types.

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

• incrementing/decrementing a value by one


• negating an expression
• inverting the value of a Boolean

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 general format of the assignment operator is:


variable = value;

• 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

Some of the relational operators are-

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

Conditional operators are:

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

The general format is:

condition ? if true : if false

// Java program to illustrate max of three numbers using ternary operator.


public class operators {
public static void main(String[] args)
{
int a = 20, b = 10, c = 30, result;
result = ((a > b) ? (a > c) ? a : c : (b > c) ? b : c);
System.out.println("Max of three numbers = "
+ result);
}
}

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-

number shift_op number_of_places_to_shift;

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

• The instance of the operator is used for type checking.


• It can be used to test if an object is an instance of a class, a subclass, or an interface.
• General format-

object instance of class/subclass/interface


Example
class operators
{
public static void main(String[] args)
{
Person obj1 = new Person();
Person obj2 = new Boy();
// As obj is of type person, it is not an // instance of Boy or interface
System.out.println("obj1 instanceof Person: " + (obj1 instanceof Person));
System.out.println("obj1 instanceof Boy: "+ (obj1 instanceof Boy));
System.out.println("obj1 instanceof MyInterface: "+ (obj1 instanceof MyInterface));
System.out.println("obj2 instanceof Person: "+ (obj2 instanceof Person));
System.out.println("obj2 instanceof Boy: "+ (obj2 instanceof Boy));
System.out.println("obj2 instanceof MyInterface: "+ (obj2 instanceof MyInterface));
}
}
class Person Output
{ obj1 instanceof Person: true
} obj1 instanceof Boy: false
class Boy extends Person implements MyInterface
obj1 instanceof MyInterface: false
{
} obj2 instanceof Person: true
interface MyInterface { obj2 instanceof Boy: true
} obj2 instanceof MyInterface: true
CONTROL STATEMENT
• Control statements decide the flow (order or sequence of execution of statements) of a
Java program.
• In Java, statements are parsed from top to bottom.
• Therefore, using the control flow statements can interrupt a particular section of a program
based on a certain condition.one or more clauses.
Conditional / Selection Statements

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

• These are used to execute a block of statements multiple times.


• It means it executes the same code multiple times so it saves code.
• These are also called Iteration statements.

There are three types of iterative control statements:

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.

You might also like