B.SC Sem - 5 Java I Unit
B.SC Sem - 5 Java I Unit
UNIT -1
Introduction to Java
JAVA was developed by James Gosling at Sun Microsystems in the year 1991, later
acquired by Oracle Corporation.
It is a simple programming language. Java makes writing, compiling, and debugging
programming easy. It helps to create reusable code and modular programs.
Java is a class-based, object-oriented programming language and is designed to have as few
implementation dependencies as possible.
A general-purpose programming language made for developers to write once run anywhere
that is compiled Java code can run on all platforms that support Java. Java applications are
compiled to byte code that can run on any Java Virtual Machine. The syntax of Java is
similar to c/c++.
History
It is a programming language created in 1991. James Gosling, Mike Sheridan, and Patrick Naughton, a
team of Sun engineers known as the Green team initiated the Java language in 1991. Sun Microsystems
released its first public implementation in 1996 as Java 1.0.
James Gosling in 1995 developed Java, who is known as the Father of Java. Currently, Java is used in
mobile devices, internet programming, games, e-business, etc. Initially it is name as OAK which is a
tree name.later on it is named as java
Java Terminology
Before learning Java, one must be familiar with these common terms of Java.
1. Java Virtual Machine(JVM): This is generally referred to as JVM. There are three execution phases
of a program. They are written, compile and run the program.
2. Bytecode in the Development process: The Javac compiler of JDK compiles the java source code
into bytecode so that it can be executed by JVM. It is saved as .class file by the compiler. To view the
bytecode, a disassembler like javap can be used.
1
B.sc (SEM V) PROGRAMMING IN JAVA
3. Java Development Kit(JDK): While we were using the term JDK, when we learn about bytecode
and JVM . So, as the name suggests, it is a complete Java development kit that includes everything
including compiler, Java Runtime Environment (JRE), java debuggers, java docs, etc. For the program
to execute in java, we need to install JDK on our computer in order to create, compile and run the
java program.
Sun MicroSystems officially describes Java with the following list of features:
● Simple and Familiar
● Compiled and Interpreted
● Platform Independent
● Portable
● Architectural Neutral
● Object-Oriented
● Robust
● Secure
● Distributed
● Multi-threaded and Interactive
● High Performance
● Dynamic and Extensible
1. Simple and Familiar
Java is simple because:
Its coding style is very clean and easy to understand. It removes complexity because it doesn’t use
complex and difficult features of other languages like C and C++, which are as follows:
3.Platform Independent
● The most significant feature of Java is that it provides platform independence which leads
to a facility of portability, which ultimately becomes its biggest strength.
● Being platform-independent means a program compiled on one machine can be
executed on any machine in the world without any change.
● Java achieves platform independence by using the concept of the BYTE code.
● In Java the compiler converts the source code into an intermediate code called the byte code
and this byte code is further translated to machine-dependent form by another layer of
software called JVM (Java Virtual Machine).
Therefore, JVM can execute bytecode on any platform or OS on which it is present, regardless of the
fact that on which machine the bytecode was generated.
This is where the “Write Once, run anywhere” (WORA) slogan for Java comes in, which means that
we can develop applications on one environment (OS) and run on any other environment without
doing any modification in the code.
3
B.sc (SEM V) PROGRAMMING IN JAVA
4.Portable
● Java is “portable” refers to the SE (Standard Edition) version. The portability actually
comes from architecture-neutrality.
● Java programs portable among different platforms such as Windows, Unix, Solaris, and
Mac.Any changes and updates made in Operating Systems, Processors and System resources
will not enforce any changes in Java programs.
5.Architectural Neutral
This buzzword means that the program written on one platform or OS is independent of other
platforms or environments and can run on any other Operating System without recompiling them.
6.Object-Oriented
Java strongly supports the concepts of Object-Oriented Programming due to which it is called a pure
object oriented language.
Java supports major Object-Oriented programming features like Encapsulation, Abstraction, and
Inheritance.
7.Robust
● Java is robust as it is capable of handling run-time errors, supports automatic garbage
collection and exception handling, and avoids explicit pointer concept.
● Java has a strong memory management system.
● It helps in eliminating errors as it checks the code during both compile and runtime.
8. Secure
● Security is an important issue for any programming language as there is a threat of
malicious activities and viruses.
● Java supports access modifiers to check memory access and also ensures that no
viruses enter an applet.
● Java is a more secure language as compared to C/C++, as it does not allow a programmer to
explicitly create pointers. Thus in Java, we can not gain access to a particular variable if we do not
initialize it properly.
9.Distributed
● Java is distributed because it encourages users to create distributed applications.
● In Java, we can split a program into many parts and store these parts on different
4
B.sc (SEM V) PROGRAMMING IN JAVA
computers. A Java programmer sitting on a machine can access another program
running on the other machine.
● This feature in Java gives the advantage of distributed programming, which is very helpful
when we develop large projects. Java helps us to achieve this by providing the concept of
RMI (Remote Method Invocation) and EJB (Enterprise JavaBeans).
● Java comes with an extensive library of classes for interacting, using TCP/IP protocols such as
HTTP and FTP, which makes creating network connections much easier than in C/C++.
● It also enables multiple programmers at many locations to work together on a single
project.
10. Multi-threaded and Interactive
● A thread is an independent path of execution within a program, executing concurrently.
Multithreaded means handling multiple tasks simultaneously or executing multiple portions
(functions) of the same program in parallel.
● The code of java is divided into smaller parts and Java executes them in a sequential and timely
manner.
Advantages:
● The main advantage of multithreading is that the maximum utilization of resources is
possible.
● It doesn’t occupy memory for each thread. It shares a common memory area.
● There is no need to wait for the application to finish one task before beginning another one.
● There is a decreased cost of maintenance. Also, It is time-saving.
● It improves the performance of complex applications.
● Java is interactive because its code supports effective CUI (Character User Interface) and GUI
(Graphical User Interface) programs. It greatly improves the interactive performance of
graphical applications.
11. High Performance
● The performance of Java is impressive for an interpreted language because of its
intermediate bytecode.
● Java provides high performance with the use of “JIT – Just In Time compiler”, in which the
compiler compiles the code on-demand basis, that is, it compiles only that method which is
5
B.sc (SEM V) PROGRAMMING IN JAVA
being called. This saves time and makes it more efficient.
● Bytecodes generated by the Java compiler are highly optimized, so Java Virtual Machine can
execute them much faster.
12. Dynamic and Extensible
● Java is dynamic and extensible means with the help of OOPs, we can add classes and add
new methods to classes, creating new classes through subclasses. This makes it easier for
us to expand our own classes and even modify them.
● Java gives the facility of dynamically linking new class libraries, methods, and objects. It is
highly dynamic as it can adapt to its evolving environment.
● Java even supports functions written in other languages such as C and C++ to be written in Java
programs. These functions are called “native methods”. These methods are dynamically linked
at runtime.
Types of Java Applications
There are mainly 4 types of applications that can be created using Java programming:
1) Standalone Application
Standalone applications are also known as desktop applications or window-based applications. These
are traditional software that we need to install on every machine. Examples of standalone application
are Media player, antivirus, etc. AWT and Swing are used in Java for creating standalone applications.
2) Web Application
An application that runs on the server side and creates a dynamic page is called a web application.
Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF, etc. technologies are used for creating web
applications in Java.
3) Enterprise Application
An application that is distributed in nature, such as banking applications, etc. is called an enterprise
application. It has advantages like high-level security, load balancing, and clustering. In Java, EJB is
used for creating enterprise applications.
4) Mobile Application
An application which is created for mobile devices is called a mobile application. Currently, Android and
Java ME are used for creating mobile applications.
7
B.sc (SEM V) PROGRAMMING IN JAVA
Q.Explain about Naming Convention?
Hungarian Notation:
Hungarian Notation is the naming convention followed by SUN (Stanford University Network) micro
system to develop their predefined classes, interfaces, methods and data members.
For example:
System, NumberFormatException, Array IndexOutOfBoundException
Hungarian rule for Method:
If a method name contains more than one word then first word letter is small and rest of the words
first letters must be capital.
For example:
println (), actionPerformed (), adjustmentValueChanged ()
Hungarian rule for Data Members:
All the data members are the predefined classes and interfaces must be represented used as capital
letters.
For example:
PI, MAX_VALUE, and MIN_VALUE
All the data members in the predefined classes and interfaces are belongs to public static
final XXX data members. XXX represents data type, variable name and variable value. Every final
data member must belong to static data member but reverse may or may not be applicable.
Q.Explain Structure of Java Program
Java is an object-oriented programming, platform-independent, and secure programming language
that makes it popular. Using the Java programming language, we can develop a wide variety of
applications.
8
B.sc (SEM V) PROGRAMMING IN JAVA
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:
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.
package p1;
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
9
B.sc (SEM V) PROGRAMMING IN JAVA
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;
}
10
B.sc (SEM V) PROGRAMMING IN JAVA
d.display();
}
}
Output
Welcome to java
Creating Hello World Example
class Simple
{
public static void main(String args[])
{
System.out.println("Hello Java"); } }
11
B.sc (SEM V) PROGRAMMING IN JAVA
Simple.java To
execute:
java Simple
Output:
Hello Java
void is the return type of the method. It means it doesn't return any value. main
Letters: Both lowercase (a, b, c, d, e, etc. ) and uppercase (A, B, C, D, E, etc.) letters.
Digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9.
Special symbols: _, (, ), {, }, [, ], +, -, *, /, %, !, &, |, ~, ^, <, =, >, $, #, ?, Comma (,), Dot (.), Colon (:),
Semi-colon (;), Single quote (‘), Double quote (“), Back slash (\).
12
B.sc (SEM V) PROGRAMMING IN JAVA
Java supports 5 types of tokens which are:
● Keywords
● Identifiers
● Literals
● Operators
● Special Symbols
Keywords
Keywords in Java are predefined or reserved words that have special meaning to the Java compiler.
Each keyword is assigned a special task or function and cannot be changed by the user. You cannot use
keywords as variables or identifiers as they are a part of Java syntax itself. A keyword should always be
written in lowercase as Java is a case sensitive language. Java supports various keywords, some of them
are listed below:
● byte
● short
● int
● long
● float
● double
● char
● boolean
b) Access Modifiers: There are three reserved words as keywords for access modifiers by Java
language. They are as follows:
13
B.sc (SEM V) PROGRAMMING IN JAVA
● private
● protected
● public
These keywords are called access modifier keywords.
c) Control Statement: There are ten reserved words as keywords for the control statement by Java
language. They are as:
● else
● switch
● case
● default
● for
● while
● do
● continue
● break
● goto [reserved but not in used]
● if
d) 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
e) Modifiers: There are eight modifier keywords reserved in the Java language. These
keywords are also called non-access modifier keywords. They are as follows:
● static
● abstract
● synchronized
● volatile
● native
● transient
● strictfp
● final
f) Exceptions: There are five exception keywords that are reserved by Java language. They are as:
14
B.sc (SEM V) PROGRAMMING IN JAVA
● try
● catch
● finally
● throw
● throws
g) Package: Java language has included two reserved keywords for a package that is as follows:
● package
● import
h) Miscellaneous keywords:
● return
● const (*)
● instanceof
● void
● assert
● default
● enum
The keywords const and goto are reserved but not used. In addition to these keywords, Java reserves
the following: null, true, and false.
Identifier
Java Identifiers are the user-defined names of variables, methods, classes, arrays, packages, and
interfaces. Once you assign an identifier in the Java program, you can use it to refer the value
associated with that identifier in later statements.
There are some rules which you must follow while naming the identifiers such as:
● Identifiers must begin with a letter, dollar sign or underscore.
● Apart from the first character, an identifier can have any combination of characters.
● Identifiers in Java are case sensitive.
● Java Identifiers can be of any length.
● Identifier name cannot contain white spaces.
● Any identifier name must not begin with a digit but can contain digits within.
● Most importantly, keywords can’t be used as identifiers in Java.
●
Example:
//Valid Identifiers
$myvariable //correct
_name //correct
Name //correct
//Invalid Identifiers
&Name //error
23name //error
switch //error
Studnet's //error
Literals
Literals in Java are similar to normal variables but their values cannot be changed once assigned. In
other words, literals are constant variables with fixed values. These are defined by users and can
belong to any data type. Java supports five types of literals which are as follows:
● Integer
● Floating Point
● Character
● String
● Boolean
Example:
public class sample
{
public static void main(String[] args)
{
int a1 = 112; // Int literal
float a2 = 31.10; // Float literal char
System.out.println(a1); //112
System.out.println(a2); //31.40
System.out.println(a3); //edu
System.out.println(s); //Edureka
System.out.println(value); //true } }
16
B.sc (SEM V) PROGRAMMING IN JAVA
Operators
An operator in Java is a special symbol that signifies the compiler to perform some specific
mathematical or non-mathematical operations on one or more operands. Java supports 8 types of
operators. Below I have listed down all the operators, along with their examples:
Operator Examples
Arithmetic+ , – , / , * , %
Unary ++ , – – , !
Assignment = , += , -= , *= , /= , %= , ^=
Logical && , ||
Bitwise &,|,^,~
Symbol Description
● Brackets [] These are used as an array element reference and also indicates single and
multidimensional subscripts
● Parentheses() These indicate a function call along with function parameters
● Braces{} The opening and ending curly braces indicate the beginning and end of a block
of code having more than one statement
● Comma ( , ) This helps in separating more than one statement in an expression
● Semi-Colon (;) This is used to invoke an initialization list
● Asterisk (*) This is used to create a pointer variable in Java
18
B.sc (SEM V) PROGRAMMING IN JAVA
Datatype: Type of data that can be stored in this variable.
Variable name: Name given to the variable.
In this way, a name can only be given to a memory location. It can be assigned values in two ways:
variable name=value;
● Local Variables
● Instance Variables
● Static Variables
Local variables
● A variable defined within a block or method or constructor is called a local variable.
● These variables are created when the block is entered or the function is called and
destroyed after exiting from the block or when the call returns from the function.
● The scope of these variables exists only within the block in which the variable is
declared. i.e. we can access these variables only within that block.
● Initialization of the local variable is mandatory before using it in the defined scope.
2. Instance Variables
Instance variables are non-static variables and are declared in a class outside any method,
constructor,…...................................................................or block.
● As instance variables are declared in a class, these variables are created when an object of the
class is created and destroyed when the object is destroyed.
● Unlike local variables, we may use access specifiers for instance variables. If we do not
specify any access specifier then the default access specifier will be used.
● Initialization of Instance Variable is not Mandatory. Its default value is 0
19
B.sc (SEM V) PROGRAMMING IN JAVA
● Instance Variable can be accessed only by creating objects.
3. Static Variables
Static variables are also known as Class variables.
● These variables are declared similarly as instance variables, the difference is that static
variables are declared using the static keyword within a class outside any method constructor
or block.
● Unlike instance variables, we can only have one copy of a static variable per class
irrespective of how many objects we create.
● Static variables are created at the start of program execution and destroyed
automatically when execution ends.
● Initialization of Static Variable is not Mandatory. Its default value is 0
● If we access the static variable like the Instance variable (through an object), the
compiler will show the warning message and it won’t halt the program. The compiler will
replace the object name with the class name automatically.
● If we access the static variable without the class name, the compiler will automatically
append the class name.
Example
class sample
{
// Static variable
static int a;
// Instance variable
int b;
class IfExample
{
public static void main(String []args)
{
int a=10;
If(a>0)
{
System.out.println(“Value of a is positive");
} } }
Output
Value of a is positive
2. If-Else Statement
If the condition is true then, it will execute the If block. Otherwise, it will execute the Else block.
Syntax
21
B.sc (SEM V) PROGRAMMING IN JAVA
if(condition)
{
// statements
}
else
{
// statements
}
//other statements
Flowchart
Example
class IfElseExample
{
public static void main(String []args)
{
int a=-10;
If(a>0)
{
System.out.println(“Value of a is positive");
}
else
{
System.out.println(“Value of a isnegative");
}}}
Output
Value of a is negative
3. If Else-If statement
If the condition is true, then it will execute the If block. Otherwise, it will execute the Else-If block.
Again, if the condition is not met, then it will move to the else block.
if(condition1)
{
// statements
22
B.sc (SEM V) PROGRAMMING IN JAVA
}
else if(condition 2)
{
// statements
}
………..
…………
………...
else if(condition n)
{
//statements
}
else
{
//statements
}
Example
class IfElseIfExample
{
public static void main(String []args)
{
int a=0;
If(a>0)
{
System.out.println(“Value of a is positive");
}
else if(a<0)
{
System.out.println(“Value of a isnegative");
}
else
{
System.out.println(“Value of a is zero");
} } }
Output
Value of a is zero
4. Switch Statement
Switch statement allows program to select one action among multiple actions during the program
execution.
Syntax:
switch (expression)
{
case value1:
23
B.sc (SEM V) PROGRAMMING IN JAVA
// code
break;
case value2:
// code
break;
...
...
default:
// default statements
}
Based on the argument in the switch statement suitable case value will be selected and executed.
Example
import java.util.Scanner;
public class SwitchExample
{
public static void main(String[] args)
{
int num1, num2;
Scanner s= new Scanner(System.in);
System.out.print("Enter first number:");
num1 = s.nextInt();
System.out.print("Enter second number:");
num2 = s.nextInt();
System.out.print("Enter an operator (+, -, *, /): ");
char operator = s.next().charAt(0);
s.close();
int result ;
switch(operator)
{
case '+':
result= num1 + num2;
24
B.sc (SEM V) PROGRAMMING IN JAVA
break;
case '-':
result = num1 - num2;
break;
case '*':
result= num1 * num2;
break;
case '/':
result = num1 / num2;
break;
/* If user enters any other operator or char apart from
* +, -, * and /, then display an error message to user
*
*/
default:
System.out.printf("You have entered wrong operator");
return;
}
System.out.println(num1+" "+operator+" "+num2+": "+result);
} }
Output:
Enter first number:40
Enter second number:4
Enter an operator (+, -, *, /): /
40.0 / 4.0: 10.0
Looping Control Statements
These are used to execute a block of statements multiple times. It means it executes the same code
multiple times so it saves code. These are also called Iteration statements.
25
B.sc (SEM V) PROGRAMMING IN JAVA
the statements inside for loop body gets executed. Once the condition returns false, the
statements in for loop does not execute and the control gets transferred to the next
statement in the program after for loop.
● Third step: After every execution of for loop’s body, the increment/decrement part of for
loop executes that updates the loop counter.
● Fourth step: After third step, the control jumps to second step and condition is re-
evaluated.
Flow chart
Example
class ForExample
{
public static void main(String []args)
{
int a=1;
for(int i=0; i<5; i++)
{
System.out.println(“Value of a is:”+ a); a+
+; // increases value by 1
} } }
Output:
Value of a is:1
Value of a is:2
Value of a is:3
Value of a is:4
Value of a is:5
2. While loop
While loop executes till the condition becomes false.
Syntax:
while(condition)
{
// statements
}
26
B.sc (SEM V) PROGRAMMING IN JAVA
Flowchart
In while loop, condition is evaluated first and if it returns true then the statements inside while loop
execute. When condition returns false, the control comes out of loop and jumps to the next statement
after while loop.
Example
class WhileLoopExample
{
public static void main(String args[])
{
int i=10;
while(i>1)
{
System.out.println(i);
i--;
} } }
Output:
10 9 8 7 6 5 4 3 2
3. Do-while loop
When you are using for or while, then it will execute the loop body only if the condition if true.
In do-while loop, it will execute the loop first, then it checks the condition. So, it will execute the loop
atleast once.
It is called exit controlled loop and for ,while loop are called entry controlled loop.
Syntax:
do
{
// statements
}while(condition);
Flowchart
27
B.sc (SEM V) PROGRAMMING IN JAVA
Example Program
class Sample
{
public static void main(String args[])
{
int a = 1;
do
{
System.out.println(“hello”); i+
+;
}while( a<=1 );
}}
Output
Hello
Unconditional Control Statements/Jump Statements
1. break Statement
break is a keyword. It is used within any control statements. It is used to terminate the execution of the
current loop or switch statements.
28
B.sc (SEM V) PROGRAMMING IN JAVA
Value of variable is: 0
Value of variable is: 1
Value of variable is: 2
Outof while-loop
2.continue Statement
continue is a keyword. It is used to continue the execution of the current loop with the next iteration.
Java is a high level programming language. A program written in high level language cannot be run on
any machine directly. First, it needs to be translated into that particular machine language. The javac
compiler does this thing, it takes java program (.java file containing source code) and translates it into
machine code (referred as byte code or .class file).
Java Virtual Machine (JVM) is a virtual machine that resides in the real machine (your computer) and
the machine language for JVM is byte code. This makes it easier for compiler as it has to generate byte
code for JVM rather than different machine code for each type of machine. JVM executes the byte
code generated by compiler and produce output. JVM is the one that makes java platform
29
B.sc (SEM V) PROGRAMMING IN JAVA
independent.
So that the primary function of JVM is to execute the byte code produced by compiler. Each operating
system has different JVM, however the output they produce after execution of byte code is same
across all operating systems. Which means that the byte code generated on Windows can be run on
Mac OS and vice versa. That is why we call java as platform independent language. The same thing can
be seen in the diagram below:
JVM Architecture
Heap: Heap is a part of JVM memory where objects are allocated. JVM creates a Class object for
each .class file.
Stack: Stack is a also a part of JVM memory but unlike Heap, it is used for storing temporary variables.
PC Registers: This keeps the track of which instruction has been executed and which one is going to
be executed. Since instructions are executed by threads, each thread has a separate PC register.
Native Method stack: A native method can access the runtime data areas of the virtual machine.
Native Method interface: It enables java code to call or be called by native applications. Native
applications are programs that are specific to the hardware and OS of a system.
Garbage collection: A class instance is explicitly created by the java code and after use it is
automatically destroyed by garbage collection for memory management.
30
B.sc (SEM V) PROGRAMMING IN JAVA
JVM Vs JRE Vs JDK
JRE: JRE is the environment within which the java virtual machine runs. JRE contains Java virtual
Machine(JVM), class libraries, and other files excluding development tools such as compiler and
debugger.
Which means you can run the code in JRE but you can’t develop and compile the code in JRE.
JVM: As we discussed above, JVM runs the program by using class, libraries and files provided by JRE.
JDK: JDK is a superset of JRE, it contains everything that JRE has along with development tools such as
compiler, debugger etc.
In Java, we can cast both reference and primitive data types. By using casting, data can not be changed
but only the data type is changed.
Note: type casting is not possible for a Boolean data type. Type
casting can be
● Implicit casting.
● Explicit casting.
Implicit casting
This type of conversion is also known as widening casting. It happens automatically when converting
from a narrower range data type to a wider range data type. It also means converting a lower data type
like an int to a higher data type like a double.
If the targeted value to be converted has a smaller length e.g. 4 bytes, to a larger data type e.g. 8 bytes.
31
B.sc (SEM V) PROGRAMMING IN JAVA
Implicit casting follows the order of conversion as shown below:
Byte -> Short -> Char -> Int -> Long -> Float -> Double
Example
Here, we will convert an int value to a long value and finally to a double value by using a simple
assignment operator:
System.out.println(d);
System.out.println(i); //fractional part lost
} }
Output:
57.17
57
57
In the example above, we converted the double data type into an int data type. The decimal part of
the value is lost after type casting.
32