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

Java_UNIT 1

The document provides an overview of Object Oriented Programming with Java, detailing its platform, programming elements, and structure. It discusses the history of Java's creation, its features, advantages of Java bytecode, and the roles of JVM and JRE in executing Java applications. Additionally, it highlights Java's object-oriented nature, security, portability, and multi-threading capabilities.

Uploaded by

Vishva Desai
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Java_UNIT 1

The document provides an overview of Object Oriented Programming with Java, detailing its platform, programming elements, and structure. It discusses the history of Java's creation, its features, advantages of Java bytecode, and the roles of JVM and JRE in executing Java applications. Additionally, it highlights Java's object-oriented nature, security, portability, and multi-threading capabilities.

Uploaded by

Vishva Desai
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 99

Object Oriented Programming with

Java

UNIT -1
Java Platform and
Programming Elements
Name of Description
Language
Basic Beginner’s All purpose Symbolic instruction Code. It was
designed to be learned and used easily by beginners.
C Developed at Bell Laboratories. C Combines the power of an
assembly language with the ease of use and portability of a
high level language. Popular
C++ C++ is an object oriented language, based on C.
C# It is a hybrid of Java and C++ & was developed by Microsoft.
High-Level
COBOL Common business oriented language , it’s use for business Languages
application.
Fortran Formula Translation. It’s popular for
Mathematical
Scientificand application.
Java Full Form “Just Another Virtual Accelerator”, Developed by
Sun Microsystems, now it is part of Oracle. It is widely used
for developing platform independent Internet Application.
❖ The Creation of Java
• James Gosling, Mike Sheridan,
and Patrick Naughton initiated the Java language
project in June 1991. The small team of sun engineers
called Green Team.
• Firstly, it was called "Greentalk" by James
Gosling, and the file extension was .gt.
• After that, it was called Oak and was developed
as a part of the Green project
• Oak is a symbol of strength and chosen as a national
tree of many countries like the U.S.A., France,
Germany, Romania, etc.
The Creation of Java
• Java was developed by James
Gosling, who is known as the father
of Java, in 1995. James
Gosling and his team members
started the project in the early
'90s.
Why Use Java?
• Java works on different platforms (Windows, Mac, Linux,
Raspberry Pi, etc.)
• It is one of the most popular programming language in the world
• It has a large demand in the current job market
• It is easy to learn and simple to use
• It is open-source and free
• It is secure, fast and powerful
• It has a huge community support
• Java is an object-oriented language which gives a clear structure
to programs and allows code to be reused, lowering development
costs
Java Program
Structure
with simple
I/O
Operation
Java Program Structure with
simple I/O Operation

Package Declaration

• For all these classes package belongs to


a single parent directory. We use the
keyword package to declare the package
name.

For example:
• package java //where java is the
package name.
Java Program Structure
with simple I/O
Operation
Import Statements

• 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
Java Program Structure
with simple I/O
Operation

Interface Statements

• An interface is a completely
"abstract class" that is used to group
related methods with empty bodies:
Java Program Structure
with simple I/O
Operation

Class Definition

• 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
{
}
Java Program Structure
with simple I/O
Operation
Class Variables and Constants
• 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;
}
Java Program Structure with simple I/O
Operation

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[])
{
}
Java Program Structure with simple I/O
Operation

• Main Method Class

For example:
• public class Student //class definition
•{
• public static void main(String args[])
•{
• //statements
•}
•}
Java main() method:
Java Program Structure • The main() is the starting point for JVM to start
with simple I/O execution of a Java program. Without the main()
Operation method, JVM will not execute the program. The syntax
of the main() method is:
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
Java Program instructions execute at runtime and perform the
Structure specified task.
with simple • A method is a block of code which only runs when
I/O it is called.
Operation • You can pass data, known as parameters, into a
method.
• Methods are used to perform certain actions, and
they are also known as functions.
Java Program Structure with simple I/O Operation

Create a Method

• A method must be declared within a


class. It is defined with the name of the
method, followed by parentheses (). Java
provides some pre-defined methods, such
as System.out.println(), but you can also
create your own methods to perform
certain actions:

• Example:
❖ Java Program Structure with simple I/O Operation
Print() Method

There is also a print() method, which is similar to println().

The only difference is that it does not insert a new line at the end of the
output: public class Main {
public static void main(String[] args)
{
System.out.print("Hello World!
"); System.out.print("I will
print");
}
}
Output: Hello World! I will print
Java Program Structure with simple
I/O Operation

• Java I/O (Input and Output) is used to process the


input and produce the output.

• Java uses the concept of a stream to make I/O operation


fast. The java.io package contains all the classes required
for input and output operations.

• We can perform file handling in Java by Java I/O API.


Java Program Structure with simple I/O Operation

Stream:
• A stream is a sequence of data. In Java, a stream is composed of bytes.
It's called a stream because it is like a stream of water that continues
to flow.
• In Java, 3 streams are created for us automatically. All these streams
are attached with the console.

• 1) System.out: standard output stream


• 2) System.in: standard input stream
• 3) System.err: standard error stream
Java Program Structure with simple I/O Operation

Output Stream
• Java application uses an output stream to write data to a
destination; it may be a file, an array, peripheral device
or socket.

Input Stream
• Java application uses an input stream to read data from a
source; it may be a file, an array, peripheral device or
socket.
• The working of Java Output Stream and Input Stream by the figure given
below.

Java Program Structure with simple I/O Operation


Hello World Example

class Simple
{
public static void main(String args[])
Java Program
{
Structure with System.out.println("Hello Java");
simple I/O }
Operation }

To javac Simple.java
compile:

To java Simple
execute:
❖ Java’s Magic: The Byte Code
❖ Java’s Magic: The Byte Code
Advantage of Java Bytecode:
1. It helps in achieving platform-independence.
2. The set of instructions for a JVM may differ from system to system but
can all interpret Bytecode.
3. Bytecodes are non-runnable codes that rely on the availability of
an interpreter, this is where JVM comes into play.
4. It is a machine-level language code that runs on the JVM.
5. It adds portability to Java which resonates with the saying, “write once,
read anywhere”.
❖ Java’s Magic: The Byte Code

Disadvantages of Java Bytecode:


1. The bytecode cannot run without an interpreter or JVM. If any
device doesn't have JVM, bytecode won't run on that device.

2. It is difficult to analyze the bytecode as it is in the form of


binary and not understandable by humans.
Features of Java
1. Object-oriented:
• An object is an instance of a class. A class is a template or blueprint
from which objects are created. So, an object is the
instance(result) of a class.
Object Definitions:
• An object is a real-world entity.
• An object is a runtime entity.
• The object is an entity which has state and behavior.
• The object is an instance of a class.
Features of
Java
Features of
Java
2. Simple:
• Java is designed as a simple programming
language. When Java was developed, the Java
team wanted it to be simple for the
professional programmer to learn and
use effectively.
• This is because it has to work on various
electronic devices or on small machines where
less memory is available. At that time,
the size of basic interpreter and class
support is only 40 KB.
Features of Java

3. Secure:
Java supports the distributed
environment of the internet; it also
provides multiple security features.
Security problems like tampering,
impersonation, and virus threats can be
eliminated or reduced by using Java on
Internet.
Features
of Java
4. Platform
Independent:
Features of
Java
5. Robust:
• The English meaning of Robust is strong. Java is robust
because:
• It uses strong memory management.
• There is a lack of pointers that avoids security problems.
• Java provides automatic garbage collection which runs on
the Java Virtual Machine to get rid of objects which
are not being used by a Java application anymore.
• There are exception handling and the type checking
mechanism in Java. All these points make Java robust.
Features of Java

6. Portable:

• If a program gives the same result on


every system machine, that program is
called portable. Java programs are
portable.

• Java is portable because it facilitates you to


carry the Java bytecode to any
platform. It doesn't require any
implementation.
Features
of Java
7. Architecture
neutral (System
independence):
Features of
Java
8. Dynamic:
• Java is a dynamic language. It supports the dynamic
loading of classes. It means classes are
loaded on demand. It also supports functions
from its native languages, i.e., C and C++.
• Java supports dynamic compilation and automatic
memory management (garbage collection).
• Before the development of Java, only static text was
displayed in the browser. But using applet
program, we can also create animation dynamically on
the Internet.
Features of Java

9. Interpreted:
• During compilation, Java compiler converts the
source code of the program into bytecode. This
byte code can be executed on any system
machine with the help of Java interpreter in
JVM.
• If we take any other programming language,
only a compiler or an interpreter is used to run
programs. But in Java, we use both compiler
and interpreter for the execution of the
program.
10. High-performance:
• Java is faster than other traditional interpreted
programming languages because Java bytecode is
"close" to native code. It is still a little bit slower than Features of Java
a compiled language (e.g., C++). Java is an
interpreted language that is why it is slower than
compiled languages, e.g., C, C++, etc.
• The speed of interpreter inside JVM to execute a
program is slow. To overcome this problem, JavaSoft
team has introduced JIT (Just In Time) compiler
which improves the performance of interpreting byte
code by caching interpretations.
• Due to which the speed of execution of java
program is enhanced. So, both interpreter and JIT
compiler in JVM work together to run the program.
11. Multi-
threaded:
Java supports JVM utilizes
A thread is like a
separate program,
Features of Java
multi-threading multiple executing
programming threads to concurrently.
that allows to execute We can write Java
programs that deal
write programs different with many tasks at
to do several blocks of once by defining
works code. multiple threads. The
simultaneously. Creating main advantage of
multiple multi-threading is that
A thread is an it doesn't occupy
threads is
individual memory for each
called thread. It shares a
process to
Features of Java

12. Distributed:
• Java is distributed because it facilitates
users to create distributed
applications in Java. RMI and EJB
are used for creating distributed
applications.
• This feature of Java makes us able to
access files by calling the
methods from any machine on the
JVM
and
JRE
❖ JVM and JRE

✔ JVM:

• JVM (Java Virtual Machine) is an abstract machine.


It is called a virtual machine because it doesn't
physically exist. It is a specification that provides a
runtime environment in which Java bytecode can be
executed. It can also run those programs which are
written in other languages and compiled to Java
bytecode.
❖ JVM and JRE

• JVMs are available for many hardware and software platforms. JVM, JRE, and
JDK are platform dependent because the configuration of each OS is different
from each other. However, Java is platform independent.
• There are three notions of the JVM: specification, implementation, and instance.

The JVM performs the following operation:


• Loads code
• Verifies code
• Executes code
• Provides runtime environment
❖ JVM and JRE

JVM provides definitions for the:


• Memory area
• Class file format
• Register set
• Garbage-collected heap
• Fatal error reporting etc.
Features of JVM :
• The JVM enables a user to run applications
on their device or in a cloud
environment.
• It helps in converting the bytecode into
machine-specific code.
JVM and
• JVM also provides some basic Java
JRE functions, such as garbage collection,
security, memory management, and many
more.
• It uses a library along with the files given by
JRE (Java Runtime Environment) for
running the program.
JVM and JRE

Features of JVM :

• Both JRE and JDK contain JVM.

• It is easily customizable. For instance, a user can feasibly allocate a maximum


and minimum memory to it.

• JVM can also execute a Java program line by line. It is thus also known as an
interpreter.

• JVM is also independent of the OS and hardware. It means that once a user
writes a Java program, they can easily run it anywhere.
JRE:
• JRE is an acronym for Java Runtime
Environment. It is also written as Java RTE.
The Java Runtime Environment is a
set of software tools which are used for
JVM and used to
developing Java applications. It is
provide the runtime
environment. It is the implementation of
JRE JVM. It physically exists. It contains a set of
libraries + other files that JVM uses at
runtime.
• The implementation of JVM is also actively
released by other companies
besides Sun Micro Systems.
JVM
and
JRE
JVM and JRE
Features of JRE :

• It is a set of tools that actually helps the JVM


to run.

• The JRE also consists of deployment technology.


It includes Java Plug-in and Java Web
Start as well.

• A developer can easily run a source code in JRE.


But it does not allow them to write and
compile the concerned Java program.
JVM and JRE
Features of JRE :

• JRE also contains various integration libraries like the JDBC


(Java Database Connectivity), JNDI (Java Naming
and Directory Interface), RMI (Remote Method
Invocation), and many more.

• It consists of the JVM and virtual machine client for Java


HotSpot.
JDK:

JVM JDK is an acronym for Java


Development Kit. The Java

and
Development Kit (JDK) is a
software development
environment which is used to
JRE develop Java applications and
applets. It physically exists. It
contains JRE + development tools.
JVM and JRE

JDK is an implementation of any one of the below


given Java Platforms released by Oracle Corporation:

• Standard Edition Java Platform


• Enterprise Edition Java Platform
• Micro Edition Java Platform
JVM and JRE

JDK:

• The JDK contains a private Java Virtual Machine (JVM) and


a few other resources such as an interpreter/loader
(java), a compiler (javac), an archiver (jar), a
documentation generator (Javadoc), etc. to complete the
development of a Java Application.
JVM and JRE
JVM and JRE
Features of JDK :

• It has all the features that JRE does.


• JDK enables a user to handle multiple extensions in only one catch
block.
• It basically provides an environment for developing and executing the
Java source code.
• It has various development tools like the debugger, compiler, etc.
• One can use the Diamond operator to specify a generic interface in place
of writing the exact one.
• Any user can easily install JDK on Unix, Mac, and Windows OS
(Operating Systems).
Difference Between JDK, JRE, and JVM
Parameter JDK JRE JVM
Full-Form The JDK is an The JRE is an The JVM is an
abbreviation for Java abbreviation for Java abbreviation for Java
Development Kit. Runtime Environment. Virtual Machine.

Definition The JDK (Java The Java Runtime The Java Virtual
Development Kit) is a Environment (JRE) is an Machine (JVM) is a
software development kit implementation of JVM. It is platform-independent
that develops applications a type of software package abstract machine that has
in Java. Along with JRE, that provides class libraries three notions in the form of
the JDK also consists of of Java, JVM, and various specifications. This
various development other components for document describes the
tools (Java Debugger, running the applications requirement of JVM
JavaDoc, compilers, etc.) written in Java implementation.
programming.
Difference Between JDK, JRE, and JVM
Parameter JDK JRE JVM

Functionality The JDK primarily JRE has a major JVM specifies all of the
assists in executing responsibility for creating implementations. It is
codes. It primarily an environment for the responsible for
functions in execution of code. providing all of these
development. implementations to the
JRE.

Platform The JDK is JRE, just like JDK, is also The JVM is
Dependency platform-dependent. It platform-dependent. It platform-independent. It
means that for every means that for every means that you won’t
different platform, you different platform, you require a different JVM
require a different require a different JRE. for every different
JDK. platform.
Difference Between JDK, JRE, and JVM

Parameter JDK JRE JVM

Implementation JDK = JRE = JVM = Only


Development Libraries for the runtime
Tools + JRE running the environment
(Java Runtime application + that helps in
Environment) JVM (Java executing the
Virtual Java
Machine) bytecode.
Character Set
• Characters are the smallest units (elements) of Java language that are used
to write Java tokens. These characters are defined by the Unicode character
set.

• A character set in Java is a set of alphabets, letters and some special


characters that are valid in java programming language.

• The first character set used in the computer system was US-ASCII
(American Standard Code for Information
Interchange (ASCII pronounced as ass-kee)). It is limited to
represent only American English.
Escape Sequence
Escape Description
Characters
Escape
\t It is used to insert a tab in
Sequence the text at this point.

• List of Java Escape \' It is used to insert a single quote character in


Characters the text at this point.

\" It is used to insert a double quote character in


the text at this point.

\r It is used to insert a
carriage return in the text at this
point.
Escape Description
Characters
Escape \\ It is used to insert a backslash character in
Sequence the text at this point.

\n It is used to insert a new


• List of Java Escape
line in the text at this point.
Characters
\f It is used to insert a form feed in the text at
this point.

\b It is used to insert a backspace in the text at


this point.

\DDD Octal Character


❖ Escape Sequence
While we compile the program with the above two statements, the
compiler gives errors, as shown below.

In such a case, the compiler needs to be told that quotation marks do not signal
the start or end of a string, but instead are to be printed. The following
statement prints statements with quotation marks.

System.out.println("\"Java\" is an object-oriented programming language.")


Char Unicode Escape Description
Sequence
Escape Special U+0009 \u0009 Horizontal
Codes Tab
Sequence U+000A \u000A Line Feed

List of Unicode
U+000D \u000D Carriage
Character or Return /
Escape Enter
Sequence
U+00A0 \u00A0 Non-Breakin
g Space
Escape • List of Unicode Character or Escape Sequence

Sequence
CHAR UNICODE ESCAPE SEQUENCE DESCRIPTION
Symbols Codes
s U+0026 \u0026 Ampersand
• U+2022 \u2022 Bullet
? U+25E6 \u25E6 White Bullet
∙ U+2219 \u2219 Bullet Operator
‣ U+2023 \u2023 Triangular Bullet
- U+2043 \u2043 Hyphen Bullet
° U+00B0 \u00B0 Degree
∞ U+221E \u221E Infinity
Escape Sequence
Unicode Character Sequence Example

public class UnicodeCharacterExample


{
public static void main(String args[])
{

System.out.println("\"Example of Unicode Character Sequence\", \u0026 2023


Java");
}
}

Output: "Example of Unicode Character Sequence", & 2023 Java


❖ Escape Sequence
Escape Sequence Character Example
class Test
{
public static void main(String[] args)
{
System.out.println("Good Morning
"); System.out.print("*\n**\n***\n");
}
}

Output: Good Morning


*
**
***
Identifiers
• Rules for Identifiers

1. Java identifier is a sequence of characters that


Identifiers consists of letters, digits, underscores (_), and dollar
signs ($).
2. It must start with a letter, an underscore (_), or a
dollar sign ($). It cannot begin with a digit.

3. It cannot be a reserved word.

4. It cannot be true, false, or null.

5. A valid identifier must have characters [A-Z] or [a-z]


or numbers [0-9], and underscore(_) or a dollar sign
($).
• Rules for Identifiers

Identifiers 6. There should not be any space in an identifier.

7. An identifier should not contain a number at the


starting. For example, 123java is an invalid
identifier.

8. We can't use the Java reserved keywords as


an identifier such as int, float, double, char,
etc.
Keywords
• Keywords in Java are predefined words that have specific meanings to
the compiler and that meanings cannot be changed.

• Since keywords have specific meaning in Java language, we cannot use


them as names of classes, variables, methods, and so on.

• Since Java is a case-sensitive language, all keywords must be written


in lowercase letters (small letters).

• Java keywords are also known as reserved words. Keywords are particular
words that act as a key to a code. These are predefined words by Java
so they cannot be used as a variable or object name or class name.
List of Reserved Keywords

1) Data Type: Java language has reserved eight


words as keywords for data types that are as follows:
❖ Keywords •byte
•short
•int
•long
•float
•double
•char
•boolean
List of Reserved Keywords

2) Access Modifiers: There are three


❖ Keywords reserved words as keywords for access
modifiers by Java language.
They are as follows:
• private
• protected
• public
These keywords are called access modifier
keywords.
❖ Keywords List of Reserved Keywords

3) Control Statement: There are ten reserved words as keywords


for the control statement by Java language. They are as:
- else - while
- Switch - do
- Case - continue
- Default - break
- For - goto
- if
❖ Keywords List of Reserved Keywords

4) Object and Classes: There are seven reserved keywords for


classes and objects by Java language. They are as follows:
• class
• interface
• extends
• implements
• this
• super
• new
List of Reserved Keywords

5) Modifiers: There are eight modifier


keywords reserved in the Java language. These
❖ Keywords keywords are also called non-access modifier
keywords. They are as follows:
• static
• abstract
• synchronized
• volatile
• native
• transient
• strictfp
• final
List of Reserved Keywords
6) Exceptions: There are five exception keywords
that are reserved by Java language. They are as:
❖ Keywords • try
• catch
• finally
• throw
• throws

7) Package: Java language has included two


reserved keywords for a package that is as follows:
• package
• import
List of Reserved Keywords

8) Miscellaneous keywords:
❖ Keywords • return
• const (*)
• instanceof
• void
• assert
• default
• enum
Data
Types
1. Primitive data types (also called intrinsic or built-in types)

❖ Data • A primitive data type specifies the size and type


of variable values, and it has no additional

Types methods.
There are eight primitive data types in Java:

Data Type Size Description


byte 1 byte Stores whole numbers from -128
to 127
short 2 bytes Stores whole numbers from
-32,768 to 32,767
int 4 bytes Stores whole numbers from
-2,147,483,648 to 2,147,483,647
Data Type Size Description
long 8 bytes Stores whole numbers from
-9,223,372,036,854,775,808
to
9,223,372,036,854,775,80
7 Data
float 4 bytes Stores fractional numbers.
Sufficient for storing 6 to Types
7 decimal digits
double 8 bytes Stores fractional
numbers. Sufficient for
storing 15 decimal digits
Data Data Type Size Description
Types boolean 1 bit Stores true or
• Primitive data types in false values
Java are those data types
can
whose variables
store only one
char 2 bytes Stores a single
value at a time. character/letter
• We cannot store
multiple values of the
or ASCII values
same type. These data
types are pre-defined in
Java. They are
named by a Keyword.
❖ Data Types
Example:

int x; // valid
x = 10; // valid because "x" store only one value at a time because it is
the primitive type variable.

x = 10, 20 ,30 40; // invalid.

• Primitive data types are not user-defined data-types. i.e.


Programmers cannot develop primitive data types.
❖ Data Types
Byte Data type

For example, we can declare a variable of type byte by using byte keyword
as:

byte b, c; // Variables b and c of type byte.

• The byte data type is used to save memory in large arrays where the
memory savings is most required. It saves space because a byte is
4 times smaller than an integer. It can also be used in place of "int"
data type.
❖ Data Types
Example:

public class ByteExample


{
public static void main(String[] args)
{
byte num = 110; // byte is 8 bit
value. System.out.println(num);
}
}

Output: 110
❖ Data Types
Short Data type Example:

package
datatypePrograms; class
ShortExample
{
public static void main(String[] args)
{
short num = 350; // Here, we have stored a value 350 into a variable
num of short data type.
System.out.println(num);
}
}

Output: 350
❖ Data Types
int Data type

1. We mostly use int data type for integer values in


Java programming.

2. Int data type is a 32-bit signed two’s complement integer.

3. It has a wider range from -2,147,483,648 to 2,147,483,647.

4. The memory size is 32 bits, i.e. 4 bytes.

5. The default value of int data type is 0.


❖ Data Types
int Data type Example:

class IntegerExample
{
public static void main(String[] args)
{
int a = 100; // Here, we have stored 100 into a which is declared as int
type. int b = 200; // 200 is stored into b which is declared as int type.
System.out.println(a+b);
}
}

Output: 300
Long Data Type
1. We mostly use this data type for a huge number where int
type is not large enough to store the desired value.
2. A long data type is a 64-bit signed two’s complement integer.
3. Default memory size allocated to this data type is 64 bits, i.e.
8 bytes.

❖ Data 4. The default value of long data type is 0.


5. It has a wide range from -9,223,372,036,854,775,808 (-2^63)
to 9,223,372,036,854,775,807 (-2^63-1). Long data type is
Types useful when big whole numbers are needed.

Example:
long num = -2334456L;
Here, we have stored -2334456 into a variable num of type
long. L represents JVM will consider it as a long value and will
allot 8 bytes to it.
❖ Data Types
long Data type

Let’s create a program where we will calculate the distance traveled by


light in 1000 days using long data type. Look at the following source
code.
package
datatypePrograms; public
class LongExample
{
public static void main(String[] args)
{
int lightSpeed;
long days;
long seconds;
❖ Data Types
long Data type
long distance;
// Speed of light in miles per
sec. lightSpeed = 186282;
days = 1000;
// Number of days.
seconds = days*24*60*60; // Convert into
seconds. distance = lightSpeed * seconds;
System.out.println("In 1000 days, distance traveled by light: " +distance + "
miles");
}
}

Output:
In 1000 days,distance traveled by light: 16094764800000 miles
❖ Data Float Data Type

There are two kinds of floating-point data


Types types:
• float
• double.
❖ Data Types
Double Data Type

1. A double data type is also used to represent decimal numbers up to 15 decimal


digits accurately.

2. The double data type is a double-precision 64-bit IEEE 754 floating-point.

3. Memory size is 64 bits, i.e. 8 bytes, and the default value is


0.0d. Example:
double num = 1345.6;
double distance = 1.50e9; // Here, e represents x 10 to the power.

Hence, 1.50e9 means 1.50*10^9. It is called scientific notation of representing


number.
❖ Data Types
Double Data Type Example:
package
datatypePrograms; public
class Area
{
public static void main(String[] args)
{
double pi, r; r = 5.5; // Radius of circle.
pi = 3.1416; // Calculate the area of circle.
double area = pi * r * r;
System.out.println("Area of circle: "
+area);
}
}
Boolean Data Type

• The Boolean data type is used to store only two


possible values: true and false. This data type is used
for simple flags that track true/false
conditions.
❖ Data
• The Boolean data type specifies one bit of
Types information, but its "size" can't be defined precisely.
Example:

Boolean one = false


Boolean Data Type
1. boolean data type represents one bit of information as either
true or false. i.e. there is only two possibles value true or false.
Internally, JVM uses one bit of storage to represent a boolean
value.

❖ Data 2. It is generally used to test a particular conditional statement


during the execution of the program.

Types 3. Boolean data type takes zero bytes of


memory.
4. Default value is false.

Example:
boolean b = false;
Character Data type

1. A char data type is mainly used to store a single character like P,


a, b, z, x, etc.

2. It is a single 16-bit Unicode character.

❖ Data 3. Memory size taken by a single char is 2


bytes.

Types 4. It can represent a range of 0 to 65536


characters.
5. A default value for char is ‘u0000’ which represents blank space
or single space. Here, ‘u’ represents that character is a Unicode.

Example:
char ch = ‘D’;
❖ Data Types
Character Data type

• The char data type single 16-bit Unicode


is a value-range character. Its '\u0000' (or
inclusive).The lies
char data type is used0)
to store to '\uffff' (or
characters.
packagebetween 65,535
datatypePrograms; public
class CharExample
{
public static void main(String[] args)
{
char ch1, ch2;
ch1 = 88;
ch2 = 'R';
char ch3;
❖ Data Types
Character Data type

ch3 = 'A';
ch3++;
System.out.println(ch1)
;
System.out.println(ch2)
;
System.out.println(ch3)
;
}
}
In the above program, we have assigned a value 88 (which is an ASCII value) in
Output:
aXvariable
R B ch1, and specifies a letter X. ch3 is assigned value A and then it is
incremented. So, ch3 will now store B, the next character in the ASCII sequence.
Data Types

Exercise:

• Num = 10;

• FloatNum = 9.88;

• Letter = ‘B’;

• Bool = false;

• Text = “Hello”;

You might also like