Module-1ppt Java
Module-1ppt Java
23ECE505A
• Java is an object-oriented programming language developed by
James Gosling and colleagues at Sun Microsystems in the early
1990s.
C++ JAVA
C++ is platform-dependent. Java is platform-independent.
C++ is mainly used for system Java is mainly used for application
programming. programming.
C++ supports the goto statement. Java doesn't support the goto
statement.
C++ JAVA
C++ uses compiler only Java uses compiler and interpreter
both.
C++ supports structures and unions. Java doesn't support structures and
unions.
C++ doesn't have built-in support for Java has built-in thread support.
threads. It relies on third-party libraries
for thread support.
C++ doesn't support documentation Java supports documentation
comment. comment (/** ... */) to create
documentation for java source code.
Allows both procedural programming Support object-oriented programming
and object-oriented programming. model.
JAVA ENVIRONMENT:
• Java environment includes a number of
development tools, classes and methods.
• The development tools are part of the system
known as Java Development Kit (JDK) and the
classes and methods are part of the Java
Standard Library (JSL), also known as the
Application Programming Interface (API).
• Java Development kit (JDK) – The JDK comes with a
set of tools that are used for developing and
running Java program. It includes:
• 1. Appletviewer - (It is used for viewing the applet)
• 2. Javac - (It is a Java Compiler)
• 3. Java - (It is a java interpreter)
• 4. Javap - (Java diassembler,which convert byte
code into program description)
• 5. Javah - (It is for java C header files)
• 6. Javadoc - (It is for creating HTML document) 7.
Jdb - (It is Java debugger)
• a) javac (Java compiler) In java, we can use any text
editor for writing program and then save that
program with “.java” extension.
• Java compiler convert the source code or program
in bytecode and interpreter convert “.java” file in
“.class” file.
• b) java(Java Interpreter) As we learn that, we can
use any text editor for writing program and then
save that program with “.java” extension.
• Java compiler convert the source code or program
in bytecode and interpreter convert “.java” file in
“.class” file.
Process of building and running java program
Java Virtual Machine(jvm)
All programming language compilers convert
the source code to machine code.
Same job done by Java Compiler to run a Java
program, but the difference is that Java compiler
convert the source code into Intermediate code
is called as bytecode for a machine that does not
exist.
This machine is called the Java Virtual machine
and it exits only inside the computer memory.
Compilation process
The Virtual machine code is not machine specific. The machine specific
code is generated by Java interpreter by acting as an intermediary between
the virtual machine and real machines shown below
• The key that allows Java to solve both the security and the
portability problems is that the output of a Java compiler is not
executable code. Rather, it is bytecode.
• Bytecode is a highly optimized set of instructions designed to
be executed by the Java run-time system, which is called the
Java Virtual Machine (JVM).
• In essence, the original JVM was designed as an interpreter for
bytecode.
• Translating a Java program into bytecode makes it much easier
to run a program in a wide variety of environments because
only the JVM needs to be implemented for each
platform.
• Although the details of the JVM will differ from platform to
platform, all understand the same Java bytecode.
• If a Java program were compiled to native code, then different
versions of the same program would have to exist for each
type of CPU connected to the Internet. This is, of course, not a
feasible solution.
• In general, when a program is compiled to an intermediate
form and then interpreted by a virtual machine, it runs slower
than it would run if compiled to executable code.
• Because bytecode has been highly optimized, the use of
bytecode enables the JVM to execute programs much faster
than you might expect.
The Java Buzzwords
Simple
• Java was designed to be easy for the
professional programmer to learn and use
effectively.
• Because Java inherits the C/C++ syntax and
many of the object-oriented features of C++,
most programmers have little trouble learning
Java.
Object-Oriented
• Although influenced by its predecessors, Java was not
designed to be source-code compatible with any other
language. This allowed the Java team the freedom to design
with a blank slate.
• Although influenced by its predecessors, Java was not
designed to be source-code compatible with any other
language. This allowed the Java team the freedom to design
with a blank slate.
• The object model in Java is simple and easy to extend, while
primitive types, such as integers, are kept as high-
performance nonobjects.
Robust
• The multi platformed environment of the Web places
extraordinary demands on a program, because the program
must execute reliably in a variety of systems. Thus, the ability
to create robust programs was given a high priority in the
design of Java.
• Because Java is a strictly typed language, it checks your code
at compile time. However, it also checks your code at run
time.
• Java virtually eliminates memory allocation and deallocation
problems by managing memory allocation and deallocation
for you.
Multithreaded
• Java was designed to meet the real-world requirement of
creating interactive, networked programs.
• To accomplish this, Java supports multithreaded
programming, which allows you to write programs that do
many things simultaneously.
• Java’s easy-to-use approach to multithreading allows you to
think about the specific behavior of your program, not the
multitasking subsystem.
Architecture-Neutral
• A central issue for the Java designers was that of code
longevity and portability. One of the main problems facing
programmers is that no guarantee exists that if you write a
program today, it will run tomorrow—even on the same
machine.
• Operating system upgrades, processor upgrades, and changes
in core system resources can all combine to make a program
malfunction.
• The Java designers made several hard decisions in the Java
language and the Java Virtual Machine in an attempt to alter
this situation. Their goal was “write once; run anywhere, any
time, forever.” To a great extent, this goal was accomplished.
Interpreted and High Performance
• Java enables the creation of cross-platform programs by
compiling into an intermediate representation called Java
bytecode. This code can be executed on any system that
implements the Java Virtual Machine.
• Java bytecode was carefully designed so that it would be easy
to translate directly into native machine code for very high
performance by using a just-in-time compiler. Java run-time
systems that provide this feature lose none of the benefits of
the platform-independent code.
Distributed
• Objects
• Classes
• Data Abstraction and
Encapsulation
• Inheritance
• Polymorphism
• Dynamic binding
• Message Passing
FEATURES OF OOP
OBJECTS
Objects are the basic run-time entities in an
object-oriented system. They may represent a
person, a place, a bank account, a table of data or
any item that the program has to handle.
FEATURES OF OOP
CLASSES
A Class is a collection objects of similar type.
For example, mango, apple and orange are
members of the class fruit;
fruit mango;
Will create an object mango belonging to the class
fruit
FEATURES OF OOP
DATA ABSTRACTION
Data abstraction refers to, providing only
essential information to the outside world
and hiding their background details.
ABSTRACTION
ABSTRACTION
FEATURES OF OOP
ENCAPSULATION
• Encapsulation is the mechanism
that binds together code (function)
and the data.
POLYMORPHISM
• "One Interface, Multiple Methods.“ (One name, many
forms)
• Greek term which means ability to take more than one form.
FEATURES OF OOP
POLYMORPHISM
FEATURES OF OOP
INHERITANCE
• Process by which one object can acquire the
• Helps in reusability.
FEATURES OF OOP
DYNAMIC BINDING
Binding refers to the linking of a procedure call to
the code to be executed in response to the call.
Dynamic binding (also known as late binding)
means that the code associated with a given
procedure call is not known until the time of the
call at run time.
FEATURES OF OOP
MESSAGE PASSING
A message for an object is a request for execution of a
procedure, and therefore will invoke a
function(procedure) in the receiving object that generates
the desired result.
Message passing involves specifying the name of the
object, the name of the function (message) and the
information to be sent.
APPLICATIONS OF
JAVA
• Java is the most popular language, in today’s world billion of devices running on
a Java platform
• Java touched every field of development of software, java’s features make it the
• It is most secured language in current world due to that all the banking
application development happen in java only, it is very easy to learn like C, C++
language.
APPLICATIONS OF
JAVA
class Prg1
{
public static void main(String args[ ])
{
System.out.println(“Hello World!!!”);
}
}
String args[ ] The main() method takes an array of String objects as a command-line
argument.
out is a static final field in System class which is of the type PrintStream .
Static fields and methods must be accessed by using the class name,
so we need to use System.out.
println is a public method in PrintStream class to print the data values
How to Read and Print an Integer value in Java
Steps for Input
1. The user enters an integer value when asked.
2. This value is taken from the user with the help of nextInt() method of Scanner Class.
3. The nextInt() method, in Java, reads the next integer value from the console into the specified variable
variableOfIntType = ScannerObject.nextInt();
n=25;
System.out.println(“The value of n is:”+ n);
n= n*3;
System.out.print(“The current value of n is:” );
System.out.println(n);
}
}
class Main {
Output
10 + 20 = 30
Lexical Issues
Java programs are a collection of whitespace, identifiers, literals,
comments, operators, separators, and keywords.
Whitespace:
• Java is a free-form language. This means that there is no need
to follow any special indentation rules.
• In Java, whitespace is a space, tab, or newline.
Identifiers:
• Identifiers are used for class names, method names, and
variable names. An identifier may be any descriptive
sequence of uppercase and lowercase letters, numbers, or the
underscore and dollar-sign characters.
• They must not begin with a number, lest they be confused
with a numeric literal.
• Java is case-sensitive, so VALUE is a different
identifier than Value.
Literals:
• A constant value in Java is created by using a
literal representation of it.
Ex: 100 98.6 'X' "This is a test“
Comments:
i) single-line
ii) multiline
iii)documentation comment: This type of comment is used to
produce an HTML file that documents your program. The
documentation comment begins with a /** and ends with a */.
Separators:
In Java, there are a few characters that are used as separators .
The Java Keywords
• There are 50 keywords currently defined in the Java language.
These keywords, combined with the syntax of the operators and
separators, form the foundation of the Java language. These
keywords cannot be used as names for a variable, class, or
method.
Data Types, Variables, and Arrays
The Primitive Types
• Java defines eight primitive types of data: byte, short, int,
long, char, float, double, and boolean. The primitive types
are also commonly referred to as simple types.
Integers
Floating-Point Types
Characters
• In Java, the data type used to store characters is char.
• Java uses Unicode to represent characters. Unicode defines a fully
international character set that can represent all of the characters found
in all human languages.
• For this purpose, it requires 16 bits. Thus, in Java char is a 16-bit type.
The range of a char is 0 to 65,536. There are no negative chars.
• Although char is designed to hold Unicode characters, it can also be
thought of as an integer type on which you can perform arithmetic
operations. For example, you can add two characters together, or
increment the value of a character variable.
Booleans
• Java has a primitive type, called boolean, for logical values. It
can have only one of two possible values, true or false. This is
the type returned by all relational operators, as in the case of
a < b. boolean is also the type required by the conditional
expressions that govern the control statements such as if and
for.
Variables:
• In Java, all variables must be declared before they can be
used. The basic form of a variable declaration is shown here:
type identifier [ = value][, identifier [= value] ...] ;
• Java allows variables to be initialized dynamically, using any
expression valid at the time the variable is declared.
Type Conversion and Casting
1) Java’s Automatic Conversions:
• When one type of data is assigned to another type of variable,
an automatic type conversion will take place if the following
two conditions are met:
• The two types are compatible.
• The destination type is larger than the source type.
• When these two conditions are met, a widening conversion
takes place.
2) Casting Incompatible Types :
• To create a conversion between two incompatible types, you
must use a cast. A cast is simply an explicit type conversion. It
has this general form:
(target-type) value
Automatic Type Promotion in Expressions
• In an expression, the precision required of an intermediate
value will sometimes exceed the range of either operand.
• Consider:
byte a = 40; byte b = 50; byte c = 100;
int d = a * b / c;
• The result of the intermediate term a * b easily exceeds the
range of either of its byte operands. To handle this kind of
problem, Java automatically promotes each byte, short, or
char operand to int when evaluating an expression. This
means that the subexpression a * b is performed using
integers—not bytes.
Arrays
• An array is a group of like-typed variables that are referred to by
a common name. Arrays of any type can be created and may
have one or more dimensions. A specific element in an array is
accessed by its index. Arrays offer a convenient means of
grouping related information.
One-Dimensional Arrays:
A one-dimensional array is, essentially, a list of like-typed
variables.
• The general form of a one-dimensional array declaration is:
• type var-name[ ];
• Here, type declares the base type of the array. The base
type determines the data type of each element that
comprises the array.
• The general form of new as it applies to one-dimensional arrays appears
as follows:
• array-var = new type[size];
Ex: month_days = new int[12];
• All elements in the array will be initialized to zero.
class AutoArray {
public static void main(String args[]) {
int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31,
30, 31 };
System.out.println("April has " + month_days[3] + "
days.");
}
}
Multidimensional Arrays
• In Java, multidimensional arrays are actually arrays of arrays.
• To declare a multidimensional array variable, specify each
additional index using another set of square brackets. For
example, the following declares a two dimensional array
variable called twoD.
• int twoD[][] = new int[4][5];
• When you allocate memory for a multidimensional array, you
need only specify the memory for the first (leftmost)
dimension. You can allocate the remaining dimensions
separately.
.
class TwoDArray {
public static void main(String args[]) {
int twoD[][]= new int[4][5];
//This line declares and initializes a 2D array with 4 rows and 5
columns.
int i, j, k = 0;
// i and j are loop variables, and k is initialized to 0. k will be used
to fill the array sequentially
for(i=0; i<4; i++) //This outer loop iterates over each row.
for(j=0; j<5; j++) //This inner loop iterates over each column in the
current row.
{
twoD[i][j] = k; // inside the loop, assigns the value of k to the
element at twoD[i][j] and then k++ increments k by 1
k++;
}
for(i=0; i<4; i++)
// After the array is filled, this loop iterates over each row to print
the elements.
{
for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
} output
} 01234
} 56789
10 11 12 13 14
15 16 17
Operators
• Java provides a rich operator environment. Most of
its operators can be divided into the
• following four groups: arithmetic, bitwise, relational,
and logical.
Arithmetic Operators
• Arithmetic operators are used in mathematical expressions in
the same way that they are used in algebra. The operands of
the arithmetic operators must be of a numeric type. You
cannot use them on boolean types, but you can use them on
char types, since the char type in Java is, essentially, a subset
of int.
• The following table lists the arithmetic operators:
The Modulus Operator
• The modulus operator, %, returns the remainder of a division
operation. It can be applied to floating-point types as well as integer
types. The following example program demonstrates the %:
class Modulus {
public static void main(String args[]) {
int x = 42;
double y = 42.25;
System.out.println("x mod 10 = " + x % 10);
System.out.println("y mod 10 = " + y % 10);
}
}
When you run this program, you will get the following output:
x mod 10 = 2
y mod 10 = 2.25
Arithmetic Compound Assignment Operators:
• Java provides special operators that can be used to combine
an arithmetic operation with an assignment.
• There are compound assignment operators for all of the
arithmetic, binary operators. Thus, any statement of the form
• var = var op expression; eg: x = x+ can be rewritten as
• var op= expression; eg: x += 1
System.out.println(ans);
System.out.println(ans1);
}
}
}
Relational Operators
• The relational operators determine the relationship that one
operand has to the other.
• Specifically, they determine equality and ordering. The
outcome of these operations is a boolean value. The
relational operators are shown here:
class GFG {
public static void main(String[] args)
{
int var1 = 5, var2 = 10, var3 = 5;
// variable declaration
int n1 = 5, n2 = 10, max;
System.out.println("First num: " + n1);
System.out.println("Second num: " + n2);
• The switch statement is Java’s multiway branch statement. It provides an easy way to
dispatch execution to different parts of your code based on the value of an
expression.
• Here is the general form of a switch statement:
switch (expression) {
case value 1:
// statement sequence
break;
case value 2:
// statement sequence
break;
...
case value N:
// statement sequence
break;
default:
// default statement sequence
}
// A simple example of the switch.
class SampleSwitch {
public static void main(String args[]) {
for(int i=0; i<6; i++)
switch(i) {
case 0:
System.out.println("i is zero.");
break;
case 1:
System.out.println("i is one.");
break;
case 2:
System.out.println("i is two.");
break;
case 3:
System.out.println("i is three.");
break;
default:
System.out.println("i is greater than 3.");
} } }
Iteration Statements
• Java’s iteration statements are for, while, and do-while. These statements
create loops. A loop repeatedly executes the same set of instructions until
a termination condition is met.
while:
• The while loop is Java’s most fundamental loop statement. It repeats a
statement or block while its controlling expression is true. Its general
form:
while(condition) {
// body of loop
}
• The condition can be any Boolean expression. The body of the loop will be
executed as long as the conditional expression is true.
• When condition becomes false, control passes to the next line of code
immediately following the loop.
• The curly braces are unnecessary if only a single statement is being
repeated.
// Demonstrate the while loop.
class While {
public static void main(String args[]) {
int n = 10;
while(n > 0) {
System.out.println("tick " + n);
n--;
}
}
}
• Since the while loop evaluates its conditional expression at the top of
the loop, the body of the loop will not execute even once if the
condition is false to begin with.
• The body of the while (or any other of Java’s loops) can be empty. This
is because a null statement (one that consists only of a semicolon) is
syntactically valid in Java.
// The target of a loop can be empty.
class NoBody {
public static void main(String args[]) {
int i, j;
i = 100;
j = 200;
// find midpoint between i and j
while(++i < --j) ; // no body in this loop
System.out.println("Midpoint is " + i);
}
}
This program finds the midpoint between i and j. It generates the
following output:
Midpoint is 150
do-while
• The do-while loop always executes its body at least
once, because its conditional expression is at the
bottom of the loop. Its general form is :
do {
// body of loop
} while (condition);
• Each iteration of the do-while loop first executes the
body of the loop and then evaluates the conditional
expression.
• If this expression is true, the loop will repeat.
Otherwise, the loop terminates. The condition must
be a Boolean expression.
for
Using break :
• In Java, the break statement has three uses. First it terminates
a statement sequence in a switch statement.
• Second, it can be used to exit a loop.
• Third, it can be used as a “civilized” form of goto.
// Using break to exit a while loop.
class BreakLoop2
{
public static void main(String args[])
{
int i = 0;
while(i < 100)
{
if(i == 10) break; // terminate loop if i is 10
System.out.println("i: " + i);
i++;
}
System.out.println("Loop complete.");
}
}
Using break as a Form of Goto
// Using break as a civilized form of goto.
class Break {
public static void main(String args[]) {
boolean t = true;
first: {
second: {
third: {
System.out.println("Before the break.");
if(t) break second; // break out of second block
System.out.println("This won't execute");
}
System.out.println("This won't execute");
}
System.out.println("This is after second block.");
}}}
Running this program generates the following output:
Before the break.
This is after second block.
Using continue