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

Unit I Notes

The document provides an overview of Object-Oriented Programming (OOP), detailing its fundamental concepts such as classes, objects, encapsulation, abstraction, polymorphism, and inheritance. It discusses the advantages and disadvantages of OOP, its applications in various fields, and highlights the features of Java, a prominent OOP language. Additionally, it compares Java with C and C++, explaining Java's architecture, including its compilation and interpretation process through the Java Virtual Machine (JVM).

Uploaded by

dangihitesh32
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Unit I Notes

The document provides an overview of Object-Oriented Programming (OOP), detailing its fundamental concepts such as classes, objects, encapsulation, abstraction, polymorphism, and inheritance. It discusses the advantages and disadvantages of OOP, its applications in various fields, and highlights the features of Java, a prominent OOP language. Additionally, it compares Java with C and C++, explaining Java's architecture, including its compilation and interpretation process through the Java Virtual Machine (JVM).

Uploaded by

dangihitesh32
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

Unit I

Object Oriented Programming Object-oriented programming – As the name suggests uses


objects in programming. Object-oriented programming aims to implement real-world entities
like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind
together the data and the functions that operate on them so that no other part of the code can
access this data except that function.

There are some basic concepts that act as the building blocks of OOPs i.e.

1. Class
2. Objects
3. Encapsulation
4. Abstraction
5. Polymorphism
6. Inheritance
7. Message Passing

Class

The building block of Object-Oriented programming is a Class. It is a user-defined data type,


which holds its own data members and member functions, which can be accessed and used by
creating an instance of that class. A class is like a blueprint for an object. For Example:
Consider the Class of Cars. There may be many cars with different names and brands but all
of them will share some common properties like all of them will have 4 wheels, Speed Limit,
Mileage range, etc. So here, the Car is the class, and wheels, speed limits, and mileage are
their properties.

 A Class is a user-defined data type that has data members and member functions.
 Data members are the data variables and member functions are the functions used to
manipulate these variables together these data members and member functions define
the properties and behavior of the objects in a Class.
 In the above example of class Car, the data member will be speed limit, mileage, etc
and member functions can apply brakes, increase speed, etc.

Class is a blueprint representing a group of objects which shares some common properties
and behaviors.

Object

An Object is an identifiable entity with some characteristics and behavior. An Object is an


instance of a Class. When a class is defined, no memory is allocated but when it is
instantiated (i.e. an object is created) memory is allocated.

Objects take up space in memory and have an associated address. When a program is
executed the objects interact by sending messages to one another. Each object contains data
and code to manipulate the data. Objects can interact without having to know details of each
other’s data or code, it is sufficient to know the type of message accepted and the type of
response returned by the objects.
Encapsulation

In normal terms, Encapsulation is defined as wrapping up data and information under a single
unit. In Object-Oriented Programming, Encapsulation is defined as binding together the data
and the functions that manipulate them. Consider a real-life example of encapsulation, in a
company, there are different sections like the accounts section, finance section, sales section,
etc. The finance section handles all the financial transactions and keeps records of all the data
related to finance. Similarly, the sales section handles all the sales-related activities and keeps
records of all the sales. Now there may arise a situation when for some reason an official
from the finance section needs all the data about sales in a particular month. In this case, he is
not allowed to directly access the data of the sales section. He will first have to contact some
other officer in the sales section and then request him to give the particular data. This is what
encapsulation is. Here the data of the sales section and the employees that can manipulate
them are wrapped under a single name “sales section”.

Encapsulation

Encapsulation also leads to data abstraction or data hiding. Using encapsulation also hides
the data. In the above example, the data of any of the sections like sales, finance, or accounts
are hidden from any other section.

Abstraction

Data abstraction is one of the most essential and important features of object-oriented
programming. Abstraction means displaying only essential information and hiding the details.
Data abstraction refers to providing only essential information about the data to the outside
world, hiding the background details or implementation. Consider a real-life example of a
man driving a car. The man only knows that pressing the accelerator will increase the speed
of the car or applying brakes will stop the car but he does not know how on pressing the
accelerator the speed is actually increasing, he does not know about the inner mechanism of
the car or the implementation of an accelerator, brakes, etc. in the car. This is what
abstraction is.

 Abstraction using Classes: We can implement Abstraction using classes. The class
helps us to group data members and member functions using available access
specifiers. A Class can decide which data member will be visible to the outside world
and which is not.
 Abstraction in Header files: One more type of abstraction can be header files. For
example, consider the pow() method present in math.h header file. Whenever we need
to calculate the power of a number, we simply call the function pow() present in the
math.h header file and pass the numbers as arguments without knowing the
underlying algorithm according to which the function is actually calculating the
power of numbers.
Polymorphism

The word polymorphism means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form. A person at
the same time can have different characteristics. A man at the same time is a father, a
husband, and an employee. So the same person possesses different behavior in different
situations. This is called polymorphism. An operation may exhibit different behaviors in
different instances. The behavior depends upon the types of data used in the operation.

 Operator Overloading: The process of making an operator exhibit different behaviors


in different instances is known as operator overloading.
 Function Overloading: Function overloading is using a single function name to
perform different types of tasks. Polymorphism is extensively used in implementing
inheritance.

Example: Suppose we have to write a function to add some integers, sometimes there are 2
integers, and sometimes there are 3 integers. We can write the Addition Method with the
same name having different parameters, the concerned method will be called according to
parameters.

Polymorphism

Inheritance

The capability of a class to derive properties and characteristics from another class is called
Inheritance. Inheritance is one of the most important features of Object-Oriented
Programming.

 Sub Class: The class that inherits properties from another class is called Sub class or
Derived Class.
 Super Class: The class whose properties are inherited by a sub-class is called Base
Class or Superclass.
 Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to
create a new class and there is already a class that includes some of the code that we
want, we can derive our new class from the existing class. By doing this, we are
reusing the fields and methods of the existing class.

Example: Dog, Cat, Cow can be Derived Class of Animal Base Class.
Inheritance

Message Passing

Objects communicate with one another by sending and receiving information. A message for
an object is a request for the execution of a procedure and therefore will invoke a function in
the receiving object that generates the desired results. Message passing involves specifying
the name of the object, the name of the function, and the information to be sent.

Advantages and Disadvantages of OOP


Benefits of OOP

 We can build the programs from standard working modules that communicate with
one another, rather than having to start writing the code from scratch which leads to
saving of development time and higher productivity,
 OOP language allows to break the program into the bit-sized problems that can be
solved easily (one object at a time).
 The new technology promises greater programmer productivity, better quality of
software and lesser maintenance cost.
 It is very easy to partition the work in a project based on objects.
 It is possible to map the objects in problem domain to those in the program.
 The principle of data hiding helps the programmer to build secure programs which
cannot be invaded by the code in other parts of the program.
 By using inheritance, we can eliminate redundant code and extend the use of existing
classes.
 Message passing techniques is used for communication between objects which makes
the interface descriptions with external systems much simpler.
 The data-centered design approach enables us to capture more details of model in an
implementable form.
Disadvantages of OOP

 The length of the programmes developed using OOP language is much larger than the
procedural approach. Since the programme becomes larger in size, it requires more
time to be executed that leads to slower execution of the programme.
 We can not apply OOP everywhere as it is not a universal language. It is applied only
when it is required. It is not suitable for all types of problems.
 Programmers need to have brilliant designing skill and programming skill along with
proper planning because using OOP is little bit tricky.
 OOPs take time to get used to it. The thought process involved in object-oriented
programming may not be natural for some people.
 Everything is treated as object in OOP so before applying it we need to have excellent
thinking in terms of objects.

Applications Of Object Oriented Programming


1. Stimulation and Modeling Systems

Complex systems are challenging to model because variables have different specifications.
Complex systems stimulation requires precise modeling and knowledge of the interaction.
OOP offers a suitable method for streamlining these complex structures.

2. Hypertext and Hypermedia

Hypertext is a cross-referencing tool that connects to other texts in a non-linear, multi-


sequential manner. Contrarily, hypermedia is a superset of hypertext. OOP also contributes to
the development of the hypertext and hypermedia framework.

3. AI Expert System

These are computer programs created to address complicated issues that are much beyond the
human brain's capabilities. The following characteristics of OOP, which aid in developing an
AI expert system, include dependability, high responsiveness, high performance, and
understandability.

4. Object-oriented Database

To preserve the object's integrity and identity, databases maintain a close correlation between
database objects and their counterparts in the physical world.

5. Neural Networking and Parallel Programming

A neural network is a collection of algorithms that aims to identify underlying links in a piece
of data using a method that imitates how the human brain functions.

In parallel programming, an issue is split into smaller subproblems that may all be worked on
simultaneously utilizing different computing resources. Oops, are used to streamline the
procedure by simplifying the network's capacity for approximation and prediction.
6. Client Server System

Clients in client-server systems communicate with a centralized server to request resources or


services from the server, which processes the requests and provides responses as necessary.
Modularity, code reuse, and maintainability can all be enhanced by using OOP when creating
the software components for a client-server system.

7. Computer Aided Designs

OOP can be used in CAD software to develop classes that represent different design
components including lines, curves, surfaces, and solids. The class's relationships,
behaviours, and properties can be described through attributes and methods. Code reuse and
modularity are made possible by inheritance, which can be used to construct relationships
between various sorts of design elements.

8. Office Automation Systems

Office automation systems leverage object-oriented programming to develop modular,


reusable programming components. It helps in the creation of classes for entities like
workers, documents, and tasks, facilitating effective management, teamwork, and automation
of work-related operations.

9. Software Development

OOP facilitates modular and reusable code, making it ideal for developing complex software
systems. It enhances code organization, maintenance, and collaboration among developers.

10. Graphical User Interface (GUI) Development

OOP enables the creation of user-friendly interfaces with features like encapsulation,
inheritance, and polymorphism. Frameworks like JavaFX and Qt utilize OOP concepts for
GUI development.

Java
Java is a general purpose, high-level programming language developed by James Gosling and
his team at Sun Microsystems. The Java programming language was developed by a small
team of engineers, known as the Green Team, who initiated the language in 1991. The
language was originally called OAK, and at the time it was designed for handheld devices and
set-top boxes. Oak was unsuccessful and in 1995 Sun changed the name to Java and modified
the language to take advantage of the burgeoning World Wide Web.
Later, in 2009, Oracle Corporation acquired Sun Microsystems and took ownership of two
key Sun software assets: Java and Solaris.
Features of Java
The prime reason behind creation of Java was to bring portability and security feature into a
computer language. Beside these two major features, there were many other features that
played an important role in moulding out the final form of this outstanding language. Those
features are:
1) Simple
Java is easy to learn and its syntax is quite simple, clean and easy to understand. The
confusing and ambiguous concepts of C++ are either left out in Java or they have been re-
implemented in a cleaner way.
Eg : Pointers and Operator Overloading are not there in java but were an important part of C+
+.
2) Object Oriented
In java everything is Object which has some data and behaviour. Java can be easily extended
as it is based on Object Model.
3) Robust
Java makes an effort to eliminate error prone codes by emphasizing mainly on compile time
error checking and runtime checking. But the main areas which Java improved were Memory
Management and mishandled Exceptions by introducing automatic Garbage
Collector and Exception Handling.
4) Platform Independent
Unlike other programming languages such as C, C++ etc which are compiled into platform
specific machines. Java is guaranteed to be write-once, run-anywhere language.
On compilation Java program is compiled into bytecode. This bytecode is platform
independent and can be run on any machine, plus this bytecode format also provide security.
Any machine with Java Runtime Environment can run Java Programs.

5) Secure
When it comes to security, Java is always the first choice. With java secure features it enable
us to develop virus free, temper free system. Java program always runs in Java runtime
environment with almost null interaction with system OS, hence it is more secure.
6) Multi Threading
Java multithreading feature makes it possible to write program that can do many tasks
simultaneously. Benefit of multithreading is that it utilizes same memory and other resources
to execute multiple threads at the same time, like While typing, grammatical errors are
checked along.
7) Architectural Neutral
Compiler generates bytecodes, which have nothing to do with a particular computer
architecture, hence a Java program is easy to intrepret on any machine.
8) Portable
Java Byte code can be carried to any platform. No implementation dependent features.
Everything related to storage is predefined, example: size of primitive data types
9) High Performance
Java is an interpreted language, so it will never be as fast as a compiled language like C or C+
+. But, Java enables high performance with the use of just-in-time compiler.
Comparison among Java, C, C++

COMPARISON C C++ Java


PARAMETER

Developed by Dennis M. Ritchie Bjarne Stroustrup James Gosling created


created the C created C++ in Java while working for
programming language 1979 at Bell Labs. Sun Microsystems.
in 1972. It was created as a Oracle is now the owner
C language of it.
extension.

Programming C is a procedural Both procedural Java is an object-oriented


model programming language and object- programming language.
oriented
programming are
supported by it.

Type of As it connects the gaps C++ is a high-level Due to the fact that Java
language between machine-level language. code is converted into
and high-level machine language via a
languages, C is a compiler or interpreter,
middle-level language. Java is a high-level
language.

Compilation and C is not understood; it C++ cannot be Java can be interpreted


Interpretation is just compiled. interpreted; it can as well as compiled.
only be compiled.

Memory Functions like Using the 'new' Java supports memory


Allocation malloc(), calloc(), etc. keyword, memory allocation through the
can be used to allocate allocation is usage of the "new"
memory in C programs. accomplished in keywor
C++.
Java Architecture
1. Compilation and interpretation in Java
Java combines both the approaches of compilation and interpretation. First, java compiler
compiles the source code into bytecode. At the run time, Java Virtual Machine (JVM)
interprets this bytecode and generates machine code which will be directly executed by the
machine in which java program runs. So, java is both compiled and interpreted language.

Figure 1: Java Architecture

2. Java Virtual Machine (JVM)


JVM is a component which provides an environment for running Java programs. JVM
interprets the bytecode into machine code which will be executed the machine in which the
Java program runs.

3. Why Java is Platform Independent?


Platform independence is one of the main advantages of Java. In another words, java is
portable because the same java program can be executed in multiple platforms without
making any changes in the source code. You just need to write the java code for one platform
and the same program will run in any platforms. But how does Java make this possible?

As discussed earlier, first the Java code is compiled by the Java compiler and generates the
bytecode. This bytecode will be stored in class files. Java Virtual Machine (JVM) is unique
for each platform. Though JVM is unique for each platform, all interpret the same bytecode
and convert it into machine code required for its own platform and this machine code will be
directly executed by the machine in which java program runs. This makes Java platform
independent and portable.

Let’s make it more clear with the help of the following diagram. Here the same compiled
Java bytecode is interpreted by two different JVMS to make it run in Windows and Linux
platforms.
4. Java Runtime Environment (JRE) and Java Architecture in Detail
Java Runtime Environment contains JVM, class libraries and other supporting components.

The Java source code is compiled into bytecode by Java compiler. This bytecode will be
stored in class files. During runtime, this bytecode will be loaded, verified and JVM
interprets the bytecode into machine code which will be executed in the machine in which the
Java program runs.

A Java Runtime Environment performs the following main tasks respectively.

1. Loads the class: This is done by the class loader


2. Verifies the bytecode: This is done by bytecode verifier.
3. Interprets the bytecode: This is done by the JVM

A detailed Java architecture can be drawn as given below.

Figure 3: Java Architecture in Detail

4.1. Class loader


Class loader loads all the class files required to execute the program. Class loader makes the
program secure by separating the namespace for the classes obtained through the network
from the classes available locally. Once the bytecode is loaded successfully, then next step is
bytecode verification by bytecode verifier.
4.2. Byte code verifier
The bytecode verifier verifies the byte code to see if any security problems are there in the
code. It checks the byte code and ensures the followings.

1. The code follows JVM specifications.


2. There is no unauthorized access to memory.
3. The code does not cause any stack overflows.
4. There are no illegal data conversions in the code such as float to object references.
Once this code is verified and proven that there is no security issues with the code, JVM will
convert the byte code into machine code which will be directly executed by the machine in
which the Java program runs.

4.3. Just in Time Compiler


You might have noticed the component “Just in Time” (JIT) compiler in Figure 3. This is a
component which helps the program execution to happen faster.

As we discussed earlier when the Java program is executed, the byte code is interpreted by
JVM. But this interpretation is a slower process. To overcome this difficulty, JRE include the
component JIT compiler. JIT makes the execution faster.

If the JIT Compiler library exists, when a particular bytecode is executed first time, JIT
complier compiles it into native machine code which can be directly executed by the machine
in which the Java program runs. Once the byte code is recompiled by JIT compiler, the
execution time needed will be much lesser. This compilation happens when the byte code is
about to be executed and hence the name “Just in Time”.

Once the bytecode is compiled into that particular machine code, it is cached by the JIT
compiler and will be reused for the future needs. Hence the main performance improvement
by using JIT compiler can be seen when the same code is executed again and again because
JIT make use of the machine code which is cached and stored.

5. Why Java is Secure?


The byte code is inspected carefully before execution by Java Runtime Environment (JRE).
This is mainly done by the “Class loader” and “Byte code verifier”. Hence a high level of
security is achieved.

6. Garbage Collection
Garbage collection is a process by which Java achieves better memory management. As you
know, in object oriented programming, objects communicate to each other by passing
messages.

Whenever an object is created, there will be some memory allocated for this object. This
memory will remain as allocated until there are some references to this object. When there is
no reference to this object, Java will assume that this object is not used anymore. When
garbage collection process happens, these objects will be destroyed and memory will be
reclaimed.
Garbage collection happens automatically. There is no way that you can force garbage
collection to happen. There are two methods “System.gc()” and “Runtime.gc()” through
which you can make request for garbage collation. But calling these methods also will not
force garbage collection to happen and you cannot make sure when this garbage collection
will happen.

Writing Simple Java Programs

Java is an Object oriented language. Every java program imports packages which are provides necessary
classes and interfaces.

For example:

import java.util.*;

import java.io.*;

After import statement, every java program starts with the declaration of the class. A program may have one
or more classes. A class declaration starts with the keyword class, followed by the identifier or name of the
class. Giving the name of a package at the top is optional. Class declaration contains name of the class and
body of the class. The body of the class may consist of several statements and is enclosed between the
braces {}.

A sample of class declarations is as follows.


public class Start
{
//class body
}

Here:
public is access specifier. This class is accessible to any outside code. Otherwise, the class is accessible to
only same package classes. class is a keyword of java language which is used to declare the class.

The class body starts with the left brace { and ends with the right closing brace }.
// are comments which are neglected by the compiler.
A class body may comprise statements for declaration of variables. constants, expressions, and methods.

Simple program in Java. Save this code in Text Document as “Start.java”


public class Start()
{
public static void main()
{
System.out.println(“Hello World”);
}
}
Here:
class is a keyword
Start is a name the class. Here class is declared as public, so it is available to all the classes.
main() is the method which initiate and terminate the program ( in java functions are called as Methods)
println() is method of object “out”. “out” is the object of class “System”. println() prints the string “Hello
World” on the screen/monitor.

Compiling and Running Java program


Java compiler first converts the source code into an intermediate code, known as bytecode or virtual
machine code. To run the bytecode, we need the Java Virtual Machie (JVM). JVM exists only inside the
computer memory and runs on top of the Operating System. The bytecode is not machine specific. The
Java interpreter converts the bytecode into Machine code. The following diagram illustrates the process of
compiling and running Java programs.
For compiling the program, the Java compiler javac is run, specifying the name of the source file on the
command line as depicted here:
javac Start.java
The Java compiler creates a file called Start.class containing the bytecode version of the program. The java
interpreter in JVM executes the instructions contained in this intermediate Java bytecode version of the
program. The Java interpreter is called with “java” at the command prompt.
C:\> java Start
Output:
Hello World

Here java command calls the Java interpreter which executes the Start.class (bytecode of Start.java).

Structure of 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 Behaviours

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, and multi-line 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*/

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:
1. import java.util.Scanner; //it imports the Scanner class only
2. 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
}
}
You can read more about the Java main() method here.

Methods and behaviour


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.");
}
}
Elements or Tokens in Java Programs
Java program contains different types of elements like white spaces, comments and tokens. A token is the
smallest program element which is recognized by the compiler and which treats them as defined for the
compiler. A program is a set of tokens which comprise the following elements:

Identifiers or names: Identifier is the name of variables, methods, classes etc.


Rules for framing Names or Identifiers.
• It should be a single word which contains alphabets a to z or A to Z, digits 0 to 9, underscore (_).
• It should not contain white spaces and special symbols.
• It should not be a keyword of Java.
• It should not be Boolean literal, that is, true or false.
• It should not be null literal.
• It should not start with a digit but it can start with an underscore.
• It can comprise one or more unicode characters which are characters as well as digits.

Conventions for Writing Names


• Names of packages are completely in lower-case letters such as mypackage, java.lang.
• Names of classes and interfaces start with an upper-case letter.
• Names of methods start with a lower-case character.
• Names of variables should start with a lower-case character.

Keywords: These are special words defined in Java and represent a set of instructions.
• The keywords represent groups of instructions for the compiler.
• These are special tokens that have a predefined meaning and their use is restricted.
• keywords cannot be used as names of variables, methods, classes, or packages.
• These are written in the lower case.
• E.g. class, int, float, for, while, if, else etc.

Literals: These are values represented by a set of character, digits, etc.


• A literal represents a value which may be of primitive type, String type, or null type.
• The value may be a number (either whole or decimal point number) or a sequence of characters which is
called String literal, Boolean type, etc.
• A literal is a constant value.
Types of Literals:
i. Integer literals
• Sequences of digits.
• The whole numbers are described by different number systems such as decimal numbers, hexadecimal
numbers, octal numbers, and binary numbers.
• Each number has a different set of digits.
Decimal Integer Literals
• These are sequences of decimal digits which are 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9.
• Examples of such literals are 6, 453, 34789, etc.
Hex Integral Literals
• These are sequences of hexadecimal digits which are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, and F.
• The values 10 to 15 are represented by A, B, C, D, E, and F or a, b, c, d, e, and f.
• The numbers are preceded by 0x or 0X. Examples are 0x56ab o0X6AF2, etc.
Octal Integer Literals
• These are sequences of octal digits which are 0, 1, 2, 3, 4, 5, 6, and 7.
• These numbers are preceded by 0. Examples of literals are 07122, 04, 043526.
Binary Literal
• These are sequences of binary digits.
• Binary numbers have only two digits—0 and 1 and a base 2.
• Examples of such literals are 0b0111001, 0b101, 0b1000, etc.
ii. Floating point literal
• These are floating decimal point numbers or fractional decimal numbers
with base 10. Examples are 3.14159, 567.78, etc.
iii. Boolean literal
• These are Boolean values. There are only two values—true or false.
iv. Character literal
• These are the values in characters.
• Characters are represented in single quotes such as ‘A’, ‘H’, ‘k’, and so on.
v. String literal
• These are strings of characters in double quotes. Examples are “Delhi”,
“John”, “AA”, etc.
vi. Null literal
• There is only one value of Null Literal, that is, null.
Separators: These include comma, semicolon, period(.), Parenthesis (), Square brackets [], etc
Java Statements
A Statement is a instruction to the computer. A program is a set of statements or instructions. The statements
specify the sequence of actions to be performed when some method or constructor is invoked. The
statements are executed in the sequence in the specified order. The important Java statements are as
follows.
Statement Description
Empty statement These are used during program development.
Variable declaration statement It defines a variable that can be used to store the values
Labeled statement A block of statements is given a label. The labels should not be
keywords, previously used labels, or already declared local
variables.
Expression statement Most of the statements come under this category. There are
seven types of expression statements that include assignment,
method call and allocation, pre-increment, post increment, pre-
decrement, and post decrement statements
Control statement This comprises selection, iteration, and jump statements.
Selection statement In these statements, one of the various control flows is selected
when a certain condition expression is true. There are three
types of selection statements including if, if-else, and switch.
Iteration statement These involve the use of loops until some condition for the
termination of loop is satisfied. There are three types of
iteration statements that make use of while, do, and for
Jump statement In these statements, the control is transferred to the
beginning or end of the current block or to a labeled statement.
There are four types of Jump statements including break,
continue, return, and throw.
Synchronization statement These are used with multi-threading
Guarding statement These are used to carry out the code safely that may cause
exceptions (such as division by zero, and so on). These
statements make use of try and catch block, and finally
Command Line Arguments
• A Java application can accept any number of arguments from the command line.
• These arguments can be passed at the time of running the program. This enables a programmer to check
the behaviour of a program for different values of inputs.
• When a Java application is invoked, the runtime system passes the command line arguments to the
application's main method through an array of strings.
Example showing command line argument
class vehicle
public static void main(String args[])
{
int x = args.length;
for(int i=0; i<x; i++)
{
System.out.println(args[i]);
}}
Output
C:\> Java vehicle “Car Cycle Motorbike"
Car
Cycle
Motorbike

You might also like