0% found this document useful (0 votes)
4 views

Object Oriented Concepts Using JAVA - Module - 1

The document provides an overview of Object-Oriented Programming (OOP) concepts using Java, detailing its history, fundamental principles, and key features such as classes, objects, inheritance, polymorphism, abstraction, and encapsulation. It highlights the advantages of Java OOP, its applications, and how Java differs from C and C++. Additionally, it discusses the Java support systems, including the Java Development Kit (JDK), Java Virtual Machine (JVM), and Integrated Development Environments (IDEs).

Uploaded by

pikachureo42
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)
4 views

Object Oriented Concepts Using JAVA - Module - 1

The document provides an overview of Object-Oriented Programming (OOP) concepts using Java, detailing its history, fundamental principles, and key features such as classes, objects, inheritance, polymorphism, abstraction, and encapsulation. It highlights the advantages of Java OOP, its applications, and how Java differs from C and C++. Additionally, it discusses the Java support systems, including the Java Development Kit (JDK), Java Virtual Machine (JVM), and Integrated Development Environments (IDEs).

Uploaded by

pikachureo42
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/ 41

Object Oriented Concepts Using Java

Module - 1
By:
Dr. Sudhir S. Anakal
Object-Oriented Paradigm
• The object-oriented (OO) paradigm took its shape from the initial concept of a
new programming approach, while the interest in design and analysis methods
came much later. OO analysis and design paradigm is the logical result of the
wide adoption of OO programming languages.
• The first objectoriented language was Simula (Simulation of real systems) that
was developed in 1960 by researchers at the Norwegian Computing Center.
• In 1970, Alan Kay and his research group at Xerox PARC created a personal
computer named Dynabook and the first pure object-oriented programming
language (OOPL) - Smalltalk, for programming the Dynabook.
• In the 1980s, Grady Booch published a paper titled Object Oriented Design that
mainly presented a design for the programming language, Ada. In the ensuing
editions, he extended his ideas to a complete objectoriented design method.
• In the 1990s, Coad incorporated behavioral ideas to object-oriented methods.
Dept. of B.C.A., Faculty of Computer Applications 2
Introduction to OO Paradigm
• OO paradigm is a significant methodology for the development of any software. Most of the
architecture styles or patterns such as pipe and filter, data repository, and component-based can
be implemented by using this paradigm.
Basic concepts of Object-Oriented Programming
• Object means a real-world entity such as a mobile, book, table, computer, watch, etc. Object-
Oriented Programming is a methodology or paradigm to design a program using classes and
objects. It simplifies software development and maintenance by providing some concepts.

Dept. of B.C.A., Faculty of Computer Applications 3


Java OOPs (Object-Oriented Programming) Concepts
• Class
• Object
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation
Class
• In object-oriented programming, a class is a blueprint from which individual objects are
created (or, we can say, a class is a data type of an object type). In Java, everything is related to
classes and objects. Each class has its methods and attributes that can be accessed and
manipulated through the objects.
• Examples of Class
• If you want to create a class for students. In that case, "Student" will be a class, and student
records (like student1, student2, etc) will be objects.
• We can also consider that class is a factory (user-defined blueprint) to produce objects.
Dept. of B.C.A., Faculty of Computer Applications 4
// create a Student class
public class Student {
// Declaring attributes
String name;
int rollNo;
String section;
// initialize attributes
Student(String name, int rollNo, String section){
this.name= name;
this.rollNo = rollNo;
this.section = section;
}
// print details
public void printDetails() {
System.out.println("Student Details:");
System.out.println(this.name+ ", "+", " + this.rollNo + ", " + section);
}
}
Dept. of B.C.A., Faculty of Computer Applications 5
Object
• In object-oriented programming, an object is an entity that has two characteristics (states and behavior).
Some of the real-world objects are book, mobile, table, computer, etc. An object is a variable of the
type class, it is a basic component of an object-oriented programming system. A class has the methods
and data members (attributes), these methods and data members are accessed through an object. Thus,
an object is an instance of a class.
• Example of Objects
• Continuing with the example of students, let's create some students as objects and print their details.
public static void main(String[] args) {
// create student objects
Student student1 = new Student("Sam", 1, "IX Blue");
Student student2 = new Student("Adi", 2, "IX Red");
Student student3 = new Student("Suthi", 3, "IX Blue");
// print student details
student1.printDetails();
student2.printDetails();
student3.printDetails();
} Dept. of B.C.A., Faculty of Computer Applications 6
Inheritance
• In object-oriented programming, inheritance is a process by which we can reuse the functionalities of
existing classes to new classes. In the concept of inheritance, there are two terms base (parent) class
and derived (child) class. When a class is inherited from another class (base class), it (derived class)
obtains all the properties and behaviors of the base class.
Polymorphism
• The term "polymorphism" means "many forms". In object-oriented programming, polymorphism is
useful when you want to create multiple forms with the same name of a single entity. To implement
polymorphism in Java, we use two concepts method overloading and method overriding.
• The method overloading is performed in the same class where we have multiple methods with the same
name but different parameters, whereas, the method overriding is performed by using the inheritance
where we can have multiple methods with the same name in parent and child classes.
Abstraction
• In object-oriented programming, an abstraction is a technique of hiding internal details and showing
functionalities. The abstract classes and interfaces are used to achieve abstraction in Java.
• The real-world example of an abstraction is a Car, the internal details such as the engine, process of
starting a car, process of shifting gears, etc. are hidden from the user, and features such as the start
button, gears, display, break, etc are given to the user. When we perform any action on these features,
the internal process works.
Dept. of B.C.A., Faculty of Computer Applications 7
Encapsulation
• In an object-oriented approach, encapsulation is a process of binding the data members
(attributes) and methods together. The encapsulation restricts direct access to important data.
The best example of the encapsulation concept is making a class where the data members are
private and methods are public to access through an object. In this case, only methods can
access those private data.
Advantages of Java OOPs
• The following are the advantages of using the OOPs in Java:
• The implementations of OOPs concepts are easier.
• The execution of the OOPs is faster than procedural-oriented programming.
• OOPs provide code reusability so that a programmer can reuse an existing code.
• OOPs help us to keep the important data hidden.

Dept. of B.C.A., Faculty of Computer Applications 8


Applications of OOPs
1. Client-Server Systems
2. Object-Oriented Databases
3. Real-Time System Design
4. Simulation and Modelling Systems
5. Hypertext and Hypermedia
6. Neural Networking and Parallel Programming
7. Office Automation Systems
8. CIM/CAD/CAM Systems
9. AI Expert Systems
10. E-Commerce Systems

Dept. of B.C.A., Faculty of Computer Applications 9


Java Evolution - Java History
• In 1990 Sun Microsystems Inc. (US) has conceived a project to develop software for consumer
electronic devices that could be controlled by a remote. The project was called Stealth Project
later it was renamed to Green Project.
• In 1991 Jan, Bill Joy, James Gosling, Mike Sheradin, Patrick Naughton and several others met
in Aspen to discuss about the project and they got the know the existing programming
languages were platform dependent.
• So they started developing a new language and named it Oak. Since the name was registered
by some other company, later it was renamed to Java.
• First application of Java was WebRunner later renamed to HotJava.
• In 1995 SunWorld conference they Java and HotJava.
• In 1996 Jan 23rd JDK 1.0 was released.
• Today more than 10 million developers use Java and more than 3 billion devices run on Java.

Dept. of B.C.A., Faculty of Computer Applications 10


Java Features
• Java is a high-level, object-oriented programming language. It is known for its platform
independence, reliability, and security. Java Programming language follows the "Write Once,
Run Anywhere" principle. It provides various features like portability, robustness, simplicity,
multithreading, and high performance, which makes it a popular choice for beginners as well
as for developers.
1. Simple Syntax
• Java syntax is very straight forward and very easy to learn. Java removes complex features like
pointers and multiple inheritance, which makes it more beginner friendly.
2. Object Oriented
• Java is a pure object-oriented language. It supports core OOP concepts like Class, Objects,
Inheritance, Encapsulation, Abstraction and Polymorphism.
3. Platform Independent
• Java is platform-independent because of Java Virtual Machine (JVM).
• When we write Java code, it is first compiled by the compiler and then converted into bytecode
(which is platform-independent).
• This byte code can run on any platform which has JVM installed.
Dept. of B.C.A., Faculty of Computer Applications 11
4. Interpreted
• Java code is not directly executed by the computer. It is first compiled into bytecode. This byte
code is then understand by the JVM. This enables Java to run on any platform without
rewriting code.
5. Scalable
• Java is able to handle both small and large-scale applications, features like multithreading and
distributed computing allows developers to manage loads more efficiently.
6. Portable
• Java Byte code can be executed on any platform with the help of JVM. This means once we
write and compile our code, it can be used on different kind of devices without any changes,
making Java programs portable and easy to use anywhere.
7. Secured and Robust
• Java ensures reliability through early error detection, runtime checks, and exception handling.
Java has built-in security features, like preventing the use of pointers and providing a security
manager, which help create safe, tamper-proof applications.

Dept. of B.C.A., Faculty of Computer Applications 12


8. Memory Management
• Memory management in Java is automatically handled by the Java Virtual Machine (JVM).
• Java garbage collector reclaim memory from objects that are no longer needed.
• Memory for objects are allocated in the heap
• Method calls and local variables are stored in the stack.
9. High Performance
• Java is faster than old interpreted languages. Java program is first converted into bytecode which is
faster than interpreted code. It is slower than fully compiled languages like C or C++ because of
interpretation and JIT compilation process. Java performance is improve with the help of Just-In-Time
(JIT) compilation, which makes it faster than many interpreted languages but not as fast as fully
compiled languages.
10. Multithreading
• Multithreading in Java allows multiple threads to run at the same time.
• It improves CPU utilization and enhancing performance in applications that require concurrent task
execution.
• Multithreading is especially important for interactive and high-performance applications, such as
games and real-time systems.
• Java provides build in support for managing multiple threads. A thread is known as the smallest unit of
execution within a process. Dept. of B.C.A., Faculty of Computer Applications 13
How Java differs from C and C++
Metrics C C++ Java
Object-Oriented Pure Object Oriented
Programming Paradigm Procedural language
Programming (OOP) Oriented
Based on assembly
Origin Based on C language Based on C and C++
language

Developer Dennis Ritchie in 1972 Bjarne Stroustrup in 1979 James Gosling in 1991

Interpreted language
Translator Compiler only Compiler only
(Compiler + interpreter)

Platform Dependency Platform Dependent Platform Dependent Platform Independent

Executed by JVM (Java


Code execution Direct Direct
Virtual Machine)

Approach Top-down approach Bottom-up approach Bottom-up approach


File generation .exe files .exe files .class files
Dept. of B.C.A., Faculty of Computer Applications 14
Support header files Supported (#header,
Pre-processor directives Use Packages (import)
(#include, #define) #define)

keywords Support 32 keywords Supports 63 keywords 50 defined keywords


Datatypes (union,
Supported Supported Not supported
structure)
Supported except Multiple
Inheritance No inheritance Supported
inheritance
Support Function
Operator overloading is not
Overloading No overloading overloading
supported
(Polymorphism)
Pointers Supported Supported Not supported
Allocation Use malloc, calloc Use new, delete Garbage collector
Exception Handling Not supported Supported Supported
Templates Not supported Supported Not supported
No constructor neither
Destructors Supported Not supported
destructor
Dept. of B.C.A., Faculty of Computer Applications 15
Multithreading/
Not supported Not supported Supported
Interfaces
Database connectivity Not supported Not supported Supported

Storage Classes Supported ( auto, extern ) Supported ( auto, extern ) Not supported

Java and Internet


Java is strongly associated with the Internet because the first application program written in Java was
HotJava,a browser to run the applet on Internet . So the Internet users use the Java to create the applet
programs and run them locally using a 'Java-enabled browsers' like HotJava.. Java is a platform-
independent, object-oriented programming language (OOP). It is not to be confused with JavaScript, a
scripting language used to create dynamic web pages. Due to its reliability and ease of use, Java is one of
the most popular programming languages in the world.

Dept. of B.C.A., Faculty of Computer Applications 16


JAVA and its Support Systems
• Java support system includes:
1. Java Development Kit (JDK)
• The JDK is a software development kit provided by Oracle Corporation for developing Java
applications.
• It includes the Java compiler (javac) for compiling Java source code into bytecode.
• The JDK also includes other tools and utilities for debugging, documentation generation, and more.
2. Java Virtual Machine (JVM)
• The JVM is a key component of the Java platform. It is responsible for executing Java bytecode.
• It provides platform independence, allowing Java programs to run on any system with a compatible
JVM.
• The JVM handles memory management, garbage collection, and runtime environment for Java
applications.
3. Standard Library
• Java has a rich and comprehensive Standard Library (also known as the Java API) that provides a wide
range of pre-built classes and functions.
• The Standard Library includes classes for data structures, input/output operations, networking,
multithreading, GUI development, and more.
• Developers can leverage these classes to build robust and feature-rich applications without having to
implement everything from scratch. Dept. of B.C.A., Faculty of Computer Applications 17
4. Integrated Development Environments (IDEs)
• IDEs are software applications that provide comprehensive development environments for writing, debugging, and
testing Java code.
• Popular Java IDEs include Eclipse, IntelliJ IDEA, and NetBeans.
• These IDEs offer features like code completion, syntax highlighting, debugging tools, and project management
capabilities.
5. Build Tools
• Java build tools simplify the process of compiling, testing, and packaging Java applications.
• Apache Maven and Gradle are popular build automation tools for Java projects.
• These tools manage dependencies, automate build processes, and enable easy project configuration and deployment.
6. Java Community and Documentation
• Java has a vast and active community of developers, which provides support, forums, tutorials, and open-source
libraries.
• The official Java documentation, including the Java API documentation, is a valuable resource for understanding Java
language features and classes.
7. Enterprise Support
• Java is widely used in enterprise applications, and there are various frameworks and technologies available to support
Java-based enterprise development.
• Java Enterprise Edition (Java EE) provides a set of specifications and APIs for building enterprise-scale applications.
• Frameworks like Spring, JavaServer Faces (JSF), and Java Persistence API (JPA) simplify the development of
enterprise applications.
Dept. of B.C.A., Faculty of Computer Applications 18
Java Environment
• The Java environment refers to the software infrastructure required to develop and run Java
programs. It's comprised of several key components: the Java Development Kit (JDK) for
development, the Java Virtual Machine (JVM) for execution, and the Java Runtime
Environment (JRE) for running Java applications. The JDK includes the JRE and tools for
compiling and debugging Java code. The JVM interprets and executes Java bytecode, while
the JRE provides the necessary libraries and resources for running Java programs on different
operating systems.
1. Java Development Kit (JDK)
2. Java Virtual Machine (JVM)
3. Java Runtime Environment (JRE)
• The JRE is a software layer that provides everything needed to run Java applications. It
includes the JVM, essential libraries, and other resources required by Java programs. The JRE
ensures that Java programs can run consistently across different platforms.
4. Java Language
• Java is a versatile, object-oriented programming language designed for building a wide range
of applications, from web and mobile apps to enterprise systems.
5. Java API (Application Programming Interface)
• The Java API provides a set of classes and interfaces that programmers can use to create and
interact with Java programs. The API includes libraries for tasks like networking, file
input/output, database interaction, Dept.
andof B.C.A.,
more. Faculty of Computer Applications 19
JRE in Java
• Java Runtime Environment (JRE) is an open-access software distribution that has a
Java class library, specific tools, and a separate JVM. In Java, JRE is one of the
interrelated components in the Java Development Kit (JDK). It is the most common
environment available on devices for running Java programs. Java source code is
compiled and converted to Java bytecode. If you want to run this bytecode on any
platform, you need JRE. The JRE loads classes check memory access and get system
resources. JRE acts as a software layer on top of the operating system.
Components of Java JRE
• The components of JRE are mentioned below:
1. Integration libraries include Java Database Connectivity (JDBC)
2. Java Naming, Interface Definition Language (IDL)
3. Directory Interface (JNDI)
4. Remote Method Invocation Over Internet Inter-Orb Protocol (RMI-IIOP)
5. Remote Method Invocation (RMI)
6. Scripting
Dept. of B.C.A., Faculty of Computer Applications 20
Components of Java Runtime Environment (JRE)

Dept. of B.C.A., Faculty of Computer Applications 21


Java Virtual Machine (JVM) consists of Java HotSpot Client and Server Virtual Machine.
• User interface libraries include Swing, Java 2D, Abstract Window Toolkit (AWT),
Accessibility, Image I/O, Print Service, Sound, drag, and Drop (DnD), and input methods.
• Lang and util base libraries, which include lang and util, zip, Collections, Concurrency
Utilities, management, Java Archive (JAR), instrument, reflection, versioning, Preferences
API, Ref Objects, Logging, and Regular Expressions.
• Other base libraries, including Java Management Extensions (JMX), Java Native Interface
(JNI), Math, Networking, international support, input/output (I/O), Beans, Java Override
Mechanism, Security, Serialization, extension mechanism, and Java for XML Processing
(XML JAXP).
• Deployment technologies such as Java Web Start, deployment, and Java plug-in.
Working of JRE
• Java Development Kit (JDK) and Java Runtime Environment (JRE) both interact with each
other to create a sustainable runtime environment that enables Java-based applications to run
seamlessly on any operating system. The JRE runtime architecture consists of the following
elements as listed:
• ClassLoader
• ByteCode verifier
• Interpreter
Dept. of B.C.A., Faculty of Computer Applications 22
Now let us briefly about them as follows:
• ClassLoader: Java ClassLoader dynamically loads all the classes necessary to run a Java
program. Because classes are only loaded into memory whenever they are needed, the JRE
uses ClassLoader will automate this process when needed. During the initialization of the
JVM, three classLoaders are loaded:
• Bootstrap class loader
• Extensions class loader
• System class loader
• Bytecode Verifier: The bytecode checker ensures the format and precision of Java code
before passing it to the interpreter. If the code violates system integrity or access rights, the
class is considered corrupt and will not load.
• Interpreter: After loading the byte code successfully, the Java interpreter creates an object of
the Java virtual machine that allows the Java program to run natively on the underlying
machine.

Dept. of B.C.A., Faculty of Computer Applications 23


Working of JRE

Dept. of B.C.A., Faculty of Computer Applications 24


• JRE has an object of JVM with it, development tools, and library classes. To understand the working of
Java Runtime Environment let us see an example of a simple Java program that prints “Hello World!”.
Example:
class HelloWorld {
public static void main(String[] args) {
System.out.println(“Hello World!");
}
}
• Once you write your Java program, you must save it with a file name with a “.java” extension. Then
after you Compile your program. The output of the Java compiler is byte code which is a platform-
independent code. After compiling, the compiler generates a .class file that contains the byte code.
Bytecode is platform-independent that runs on all devices which contain Java Runtime Environment
(JRE).
Difference between JVM, JRE, and JDK.
• JVM: JVM stands for Java Virtual Machine. JVM is used for running Java bytecode.Java applications
are called WORA (Write Once Run Anywhere). This means a programmer can develop Java code on
one system and can expect it to run on any other Java-enabled system without any adjustment. This is
all possible because of JVM.
• JRE: JRE stands for Java Runtime Environment. JRE is made up of class libraries.
• JDK: JDK stands for Java Development Kit. JDK contains the JRE with compiler, interpreter,
debugger, and other tools. It provides features to run as well as develop Java Programs.
Dept. of B.C.A., Faculty of Computer Applications 25
Overview of Java Language
Java program with structure

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

Dept. of B.C.A., Faculty of Computer Applications 26


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
Dept. of B.C.A., Faculty of Computer Applications 27
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.
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
{ } Dept. of B.C.A., Faculty of Computer Applications 28
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[])
{
}
Dept. of B.C.A., Faculty of Computer Applications 29
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 Javat World!");
}
//statements
}
} Dept. of B.C.A., Faculty of Computer Applications 30
Java tokens
• In Java, Tokens are the smallest elements of a program that is meaningful to the compiler. They are
also known as the fundamental building blocks of the program. Tokens can be classified as follows:
1. Keywords
2. Identifiers
3. Constants/Literals
4. Operators
5. Separators
1. Keyword
• Keywords are pre-defined or reserved words in a programming language. Each keyword is meant to
perform a specific function in a program. Since keywords are referred names for a compiler, they can’t
be used as variable names because by doing so, we are trying to assign a new meaning to the keyword
which is not allowed. Java language supports the following keywords:
• abstract, assert, boolean, break, byte, case, catch, char, class, const, continue, default, do, double, else,
enum, exports, extends, final, finally, float, for, goto, if, implements, import, instanceof, int, interface,
long, module, native, new, open, opens, package, private, protected, provides, public, requires, return,
short, static, strictfp, super, switch, synchronized, this, throw, throws, to, transient, transitive, try, uses,
void, volatile, while, with. Dept. of B.C.A., Faculty of Computer Applications 31
2. Identifier
• Identifiers are used to name a variable, constant, function, class, and array. It usually defined by the
user. It uses letters, underscores, or a dollar sign as the first character. The label is also known as a
special kind of identifier that is used in the goto statement. Remember that the identifier name must be
different from the reserved keywords. There are some rules to declare identifiers are:
• The first letter of an identifier must be a letter, underscore or a dollar sign. It cannot start with digits
but may contain digits.
• The whitespace cannot be included in the identifier.
• Identifiers are case sensitive.
3. Constants/Literals
In programming literal is a notation that represents a fixed value (constant) in the source code. It can be
categorized as an integer literal, string literal, Boolean literal, etc. It is defined by the programmer. Once
it has been defined cannot be changed. Java provides five types of literals are as follows:
• Integer
• Floating Point
• Character
• String
• Boolean
Dept. of B.C.A., Faculty of Computer Applications 32
4. Operators
• In programming, operators are the special symbol that tells the compiler to perform a special
operation. Java provides different types of operators that can be classified according to the
functionality they provide. There are eight types of operators in Java, are as follows:
• Arithmetic Operators Operator Symbols
• Assignment Operators Arithmetic +,-,/,*,%
• Relational Operators Unary ++ , - - , !
• Unary Operators
Assignment = , += , -= , *= , /= , %= , ^=
• Logical Operators
Relational ==, != , < , >, <= , >=
• Ternary Operators
Logical && , ||
• Bitwise Operators
Ternary (Condition) ? (Statement1) : (Statement2);
• Shift Operators
Bitwise &,|,^,~
Shift << , >> , >>>
Dept. of B.C.A., Faculty of Computer Applications 33
5. Separators
• The separators in Java is also known as punctuators.
Symbol Name Purpose
used to contain a list of parameters in method definition and invocation. also used
() Parentheses for defining precedence in expressions in control statements and surrounding cast
types
Used to define a block of code, for classes, methods and local scopes Used to
{} Braces
contain the value of automatically initialised array

[] Brackets declares array types and also used when dereferencing array values

; Semicolon Terminates statements


Used to separates package names from sub-package and class names and also
, Comma
selects a field or method from an object
separates consecutive identifiers in variable declarations also used to chains
. Period
statements in the test, expression of a for loop
: Colon Used after labels
Dept. of B.C.A., Faculty of Computer Applications 34
Java statements
• Statements are roughly equivalent to sentences in natural languages. In general, statements are
just like English sentences that make valid sense. In this section, we will discuss what a
statement is in Java and the types of statements in Java.
What is a statement in Java?
• In Java, a statement is an executable instruction that tells the compiler what to perform. It
forms a complete command to be executed and can include one or more expressions. A
sentence forms a complete idea that can consist of one or more clauses.
Types of Statements
• Java statements can be broadly classified into the following categories:
• Expression Statements
• Declaration Statements
• Control Statements

Dept. of B.C.A., Faculty of Computer Applications 35


Expression Statements
• Expression is an essential building block of any Java program. Generally, it is used to generate a new value.
Sometimes, we can also assign a value to a variable. In Java, expression is the combination of values, variables,
operators, and method calls.
• There are three types of expressions in Java:
• Expressions that produce a value. For example, (6+9), (9%2), (pi*radius) + 2. Note that the expression enclosed
in the parentheses will be evaluate first, after that rest of the expression.
• Expressions that assign a value. For example, number = 90, pi = 3.14.
• Expression that neither produces any result nor assigns a value. For example, increment or decrement a value by
using increment or decrement operator respectively, method invocation, etc. These expressions modify the value
of a variable or state (memory) of a program. For example, count++, int sum = a + b; The expression changes
only the value of the variable sum. The value of variables a and b do not change, so it is also a side effect.
Declaration Statements
• In declaration statements, we declare variables and constants by specifying their data type and name. A variable
holds a value that is going to use in the Java program. For example:
int quantity; boolean flag; String message;
• Also, we can initialize a value to a variable. For example:
int quantity = 20; boolean flag = false; String message = "Hello";
• Java also allows us to declare multiple variables in a single declaration statement. Note that all the variables must
be of the same data type.
int quantity, batch_number, lot_number; boolean flag = false, isContains = true; String message = "Hello“;
Dept. of B.C.A., Faculty of Computer Applications 36
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.

Dept. of B.C.A., Faculty of Computer Applications 37


Java Virtual Machine

Dept. of B.C.A., Faculty of Computer Applications 38


• First of all, the java program is converted into a class file consisting of byte code instructions
by the java compiler. Remember, this java compiler is outside the JVM. Now this class file is
given to the JVM. In JVM, there is a module (or program) called class loader sub system,
which performs the following functions:
• First of all, it loads the class file into memory.
• Then it verifies whether all byte code instructions are proper or not. If it finds any instruction
suspicious, the execution is rejected immediately.
• If the byte instructions are proper, then it allocates necessary memory to execute the program.
This memory in divided into 5 parts, called run time data areas, which contain the data and
results while running the program. These areas are as follows
• Method area: Method area is the memory block, which stores the class code, code of the
variables, and code of the methods in the Java program. (Method means functions written in a
class) Heap: This is the area where objects are created. Whenever JVM loads a class, a method
and a heap ares are immediately created in it.

Dept. of B.C.A., Faculty of Computer Applications 39


• Java Stacks: Method code is stored on Method area. But while running a method, it needs
some more memory to store the deed and Mesults. This memory is allotted on Java stacks. So,
Java stacks are memory areas where Java methods are executed. While executing methods, a
separate frame will be creed where Java mack, where the method is executed. JVM uses a
separate thread for process) to execute each method. PC (Program Counter) registers: These
are the registers (memory areas), which contain memory address of the instructions of the
methods. If there are 3 methods, 3 PC registers will be used to track the instructions of the
methods.
• Native method stacks: Java methods are executed on Java stacks. Similarly, native methods
(for example C/C++ functions) are executed on Native method stacks. To execute the native
methods, generally native method libraries (for example C/C++ header files) are required.
These header files are located and connected to JVM by a program, called Native method
interface.
• Execution engine contains interpreter and JIT (Just In Time) compiler, which are responsible
for converting the byte code instructions into machine code so that the processor will execute
them. Most of the JVM implementations use both the interpreter and JIT compiler
simultaneously to convert the byte code. This technique is also called adaptive optimizer.

Dept. of B.C.A., Faculty of Computer Applications 40


Command Line Arguments
• Java command-line argument is an argument i.e. passed at the time of running the Java
program. In Java, the command line arguments passed from the console can be received in the
Java program and they can be used as input. The users can pass the arguments during the
execution bypassing the command-line arguments inside the main() method.
• Working of Command-Line Arguments
• We need to pass the arguments as space-separated values. We can pass both strings and
primitive data types(int, double, float, char, etc) as command-line arguments. These arguments
convert into a string array and are provided to the main() function as a string array argument.
• When command-line arguments are supplied to JVM, JVM wraps these and supplies them to
args[]. It can be confirmed that they are wrapped up in an args array by checking the length of
args using args.length.
• Internally, JVM wraps up these command-line arguments into the args[ ] array that we pass
into the main() function. We can check these arguments using args.length method. JVM stores
the first command-line argument at args[0], the second at args[1], the third at args[2], and so
on.

Dept. of B.C.A., Faculty of Computer Applications 41

You might also like