0% found this document useful (0 votes)
2 views56 pages

2 22CA026_Advance Java Programming_Data Types and Operators

Java is a powerful, object-oriented programming language used for developing standalone and web applications. It features platform independence, security, robustness, and supports high-performance, multithreading, and dynamic loading of classes. Java's development is facilitated through the Java Development Kit (JDK) and various Integrated Development Environments (IDEs), with a focus on its syntax, data types, and execution process.

Uploaded by

dolphiverma80
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
2 views56 pages

2 22CA026_Advance Java Programming_Data Types and Operators

Java is a powerful, object-oriented programming language used for developing standalone and web applications. It features platform independence, security, robustness, and supports high-performance, multithreading, and dynamic loading of classes. Java's development is facilitated through the Java Development Kit (JDK) and various Integrated Development Environments (IDEs), with a focus on its syntax, data types, and execution process.

Uploaded by

dolphiverma80
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 56

Java : As a Language

• Java is a simple yet powerful object oriented language that is


used for developing robust mission critical applications

• Java is used for developing two types of applications:


• Standalone applications for servers , desktops
and mobile devices

• Web applications called applets


Features of Java
• Simple
• Object-Oriented
• Platform independent & Architecture neutral
• Secured
• Robust
• Portable
• Dynamic
• Interpreted
• High Performance
• Multithreaded
• Distributed
Features of Java

• Simple-syntax is based on C++ (so easier for programmers to learn it after C++). Removed many
confusing and/or rarely-used features e.g., explicit pointers, operator overloading etc.

• Object-Oriented- It is truly object oriented. Everything in java is a class. It supports all the
features of object oriented languages which include: Encapsulation, Data hiding, Data abstraction,
Polymorphism Inheritance. Being an object oriented language, Java is data centric language as
compared to procedural languages which are function/procedure centric.

• Platform independent & Architecture neutral - Java is platform independent and architecture
neutral language. The size of primitives is not dependent on platform or architecture on which
code is written for example size of int in C is dependent on compiler and architecture used by the
machine on which code is written but in java size of int will remain 32 bit whatever be the platform
or architecture of the machine.
• Secured- Java is best known for its security. With Java, we can develop virus-free systems. Java is
secured because:
• No explicit pointer
• Java Programs run inside a Java Runtime Environment.
How does JRE work?

The JDK and JRE interact with one another to create a sustainable runtime environment that enables
the seamless execution of Java-based applications in virtually any operating system. The following
make up the JRE architecture:

• ClassLoader: The Java ClassLoader dynamically loads all classes necessary to run a Java program.
Since Java classes are only loaded into memory when they're required, the JRE uses ClassLoaders to
automate this process on demand.

• Bytecode verifier: The bytecode verifier ensures the format and accuracy of Java code before it
passes to the interpreter. In the event that code violates system integrity or access rights, the class
will be considered corrupted and won't be loaded.

• Security Manager: It determines what resources a class can access such as reading and writing to
the local disk

• Interpreter: After the bytecode successfully loads, the Java interpreter creates an instance of the
JVM that allows the Java program to be executed natively on the underlying machine.
• Robust-Robust simply means strong. Java is robust because:
• It uses strong memory management.
• There is a lack of pointers that avoids security problems.
• There is automatic garbage collection in java 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.

• Portable-The code after compilation of java source code can run on any architecture and any
platform with the condition that JVM exits there.

• Dynamic- Java is a dynamic language. It supports dynamic loading of classes. It means classes
are loaded on demand. It also supports functions from its native languages, i.e., C and C++.

• 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 internet.
• 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 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.

• Multithreaded- A thread is like a separate program, executing concurrently. We can write Java
programs that deal with many tasks at once by defining multiple threads. The main advantage of
multi-threading is that it doesn't occupy memory for each thread. It shares a common memory
area. Threads are important for multi-media, Web applications, etc.
Java Language Specifications: API ,JDK
and IDEs
 API
stands for Application Program Interface. It contains
predefined classes and interfaces for developing Java Programs

 JavaSE,EE and ME- Java is full fledged and powerful language that
can be used in many ways. It comes in three editions:

 JavaSE (Standard Edition)- Used to design standalone client-side


applications and applets

 JavaEE(Enterprise Edition)- Used for developing server side


applications such as Java Servlets and Java Server pages

 Java
ME( Micro Edition)- Used for developing applications for
mobile devices such as cell phones
 JDK- There are many versions of Java Standard
Edition (SE). Sun releases each version with a
Java development Toolkit (JDK).
 JDK consists of a set of programs for developing
and testing Java programs each of which is
invoked from a command line.
 JDK tools
◦ javac---java Compiler
◦ java---java interpreter
◦ javadoc---java documentation
◦ jdb----java debugger
 Besides JDK, Java development tools can also be
used ( like NetBeans, Eclipse, Jbuilder,
intelliJIDEA and TextPad) that provide an
integrated development Environment (IDEs) for
rapidly developing Java programs.
Creating , Compiling and Executing a Java
Program
A java program can be written using any
of the editors like notepad. The extension
of a java program is .java
Once the source code is created, it is
compiled using java compiler (javac)
The compiled java code is called the
Bytecode and is platform independent
and architecture neutral code. The
extension of Bytecode file is .class
Bytecode is interpreted by JVM to create
java executable file (no extension)
Create/Modify Source
Code

Source Code
e.g abc.java

Compile Source Code


e.g javac abc.java
If error

Byte Code

JVM interpreting the Bytecode


Run ByteCode
e.g java abc

If runtime errors
JIT (Just In Time Compiler)
Bytecode is one of the most important features of
java that aids in cross-platform execution. Way of
converting bytecode to native machine language
for execution has a huge impact on the speed of
it. These Bytecode have to be interpreted or
compiled to proper machine instructions
depending on the instruction set architecture.
Moreover these can be directly executed if the
instruction architecture is bytecode based.
Interpreting the bytecode affects the speed of
execution.
In order to improve performance, JIT compilers
interact with the Java Virtual Machine (JVM) at run
time and compile suitable bytecode sequences
into native machine code.
While using a JIT compiler, the hardware is able to
JIT compiler
The JIT compiler is able to perform certain simple
optimizations while compiling a series of bytecode
to native machine language. Some of these
optimizations performed by JIT compilers are
data-analysis, reduction of memory
accesses by register allocation, translation
from stack operations to register
operations, elimination of common sub-
expressions etc.
A simple Java Program
package package_name //optional
import java.io.* //optional
class Example
{
/* the variables or methods declared outside main and inside the
class are called member variables and member methods */
public static void main(String ar[])
{
System.out.println(“hello”);
}
}
The program will be saved as Example.java
(the name of the saved file should be exactly similar to the
class name containing main())
 The source code compiled using the command:
 javac Example.java (given at coomand
prompt)
 Once the file is successfully compiled, a .class
file with the same name(Example.class) will be
created on the system
 To run this file, interpreter is called that
interprets the Bytecode (.class file) created after
compilation. The command for this is:
 java Example
public static void main(String ar[]){}

public: this is an access specifier that indicates that main()


function is accessible outside the class. Anything that is
declared public is accessible outside the class

static: this modifier specifies that main() function can be


called without instantiating the class. This is essential as
the main() is called by interpreter before any objects are
made

void: this specifies that main() does not return a value

main() function takes as argument an array of String class


objects . This array takes values from the command line
called command line
arguments
System.out.println(“hello”);

Classname Method of PrintStream class


used for displaying on console

PrintStream class
object
 Program to swap the values of two variables
class Swap{
public static void main(String ar[])
{
int a, b,temp;
a=12; b=13;
temp=a; a=b; b=temp;
System.out.println(“a= “+a+”b=“+b);
}
}
Concatenation operator
Save this file as Swap.java that combines a string
with a simple variable
Atomic elements of Java
 Java programs are a collection of whitespace,
identifiers, comments, literals, operators,
separators, and keywords.

 Identifiers-
Identifiers are used for class names,
method names, and variable names. An identifier
may be any sequence of uppercase and
lowercase letters, numbers, underscore and/or
dollar-sign characters.

 They must not begin with a number, lest they be


confused with a numeric literal.
◦ Again, Java is case-sensitive
Atomic elements of Java
 Literals-A constant value in Java is created by
using a literal representation of it.
 Comments
 There are three types of comments defined by
Java.
 single-line (//)
 multiline. (/* */)
 documentation comment. (/** */)
Java keywords
 Thereare 49 reserved keywords currently
defined in the Java language .

 Thesekeywords, combined with the syntax of the


operators and separators, form the definition of
the Java language. These keywords cannot be
used as names for a variable, class, or method.

 Inaddition to the keywords, Java reserves the


following: true, false, and null. These are
values defined by Java. You may not use these
words for the names of variables, classes, and so
on
Data Types in Java
Java defines eight simple (or elemental) types of
data: byte, short, int, long, char, float,
double, and boolean. These can be put in
four groups:
 Integers This group includes byte, short, int,
and long, which are for wholevalued signed
numbers.
 Floating-point numbers This group includes float
and double, which represent
numbers with fractional precision.
 Characters This group includes char, which
represents symbols in a character
set, like letters and numbers.
 Boolean This group includes boolean, which is
a special type for representing true/false
 Strings in Java

 Unlike other languages, Strings in Java are objects of class


String

 String literals in Java are specified like they are in most


other languages—by enclosing a sequence of characters
between a pair of double quotes. Examples of string
literals are

 “Hello World”
 “two\nlines”
 “\”This is in quotes\””
Integers
Java defines four integer types:
byte, short, int, and long. All of
these are signed, positive and
negative values. Java does not
support unsigned, positive-only
integers. Many other computer
languages, including C/C++, support
both signed and unsigned integers.
The width and ranges of these
integer types vary widely, as shown
in this table:
Floating-Point Types
Floating-point numbers, also known
as real numbers, are used when
evaluating expressions that require
fractional precision. For example,
calculations such as square root, or
transcendentals such as sine and
cosine, result in a value whose
precision requires a floating-point
type
There are two kinds of floating-point
types, float and double, which
represent single- and double-
Characters
In Java, the data type used to store
characters is char. Java uses
Unicode to represent characters. 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.
Booleans
Java has a simple 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, such as a < b.
boolean is also the type
required by the conditional
expressions that govern the
control statements such as if and
for.
Integer Literals
Any whole number value is an
integer literal. Examples are 1, 2, 3,
and 42. These are all decimal values,
meaning they are describing a base
10 number.
There are two other bases which can
be used in integer literals, octal
(base eight) and hexadecimal (base
16).
Octal values are denoted in Java by
a leading zero. Normal decimal
numbers cannot have a leading zero.
A more common base for numbers
used by
programmers is hexadecimal. You
signify a
hexadecimal constant with a leading
zero-x,
( 0x or 0X). The range of a
hexadecimal
digit is 0 to 15, so A through F
(or a
through f ) are substituted for 10
through 15.
A long literal is specified by
Floating-Point Literals
Floating-point numbers represent
decimal values with a fractional
component. They
can be expressed in either standard
or scientific notation.
Standard notation consists of a
whole number component followed
by a decimal point followed by a
fractional component. For example,
2.0, 3.14159, and 0.6667 represent
valid standard-notation floating-point
numbers.
Scientific notation uses a standard-
notation, floating-point number plus
a suffix that specifies a power of 10
by which the number is to be
multiplied. The exponent is indicated
by an E or e followed by a decimal
number, which can be positive or
negative. Examples include
6.022E23, 314159E–05, and
2e+100.
Floating-point literals in Java default
to double precision. To specify a
float literal, you must append an F
The default double type consumes
64 bits of storage, while the less-
accurate float type requires only
32 bits
Boolean Literals Boolean literals are
simple. There are only two logical
values that a boolean value can
have, true and false. The values
of true and false do not convert
into any numerical representation.
The true literal in Java does not
equal 1, nor does the false
literal equal 0. In Java, they can
Character Literals
Characters in Java are indices into
the Unicode character set. They are
16-bit values that can be converted
into integers and manipulated with
the integer operators, such as the
addition and subtraction operators.
A literal character is represented
inside a pair of single quotes. All of
the visible ASCII characters can be
directly entered inside the quotes,
such as ‘a’, ‘z’, and ‘@’.
String Literals
String literals in Java are specified
like they are in most other
languages—by enclosing
a sequence of characters between a
pair of double quotes. Examples of
string literals are
“Hello World”
“two\nlines”
“\”This is in quotes\””
 The Scope and Lifetime of Variables

 Most other computer languages define two general


categories of scopes for variables: global and local.
However, these traditional scopes do not fit well with
Java’s strict, object oriented model.

 In Java, the two major scopes are those defined by a class


and those defined by a method

 The scope defined by a method begins with its opening


curly brace.
Operators and Assignments
Java operators include the following:

• Unary arithmetic operator


• Binary arithmetic operator
• Bitwise operators
• Shift operators
• Logical operators
• Assignment operator
• The cast operator
• Ternary operator
Unary arithmetic operator-
Unary operator perform operations on a
single
operand. These are:

 increment operator - ++
 decrement operator- --
 Change the sign of the value- +,-

Applies to byte,char or short values

Unary numeric promotion- If the single operand of the unary


operator has a type
narrower than int, it is converted to int by implicit widening
The ++ and -- operators are used to
increment and decrement a value.
 ++x -----prefix
 x++ ----postfix
 --x ----prefix
 x-- -----postfix
Unary numeric promotion- If the single
operand of the unary operator has a type
narrower than int, it is converted to int by
implicit widening primitive conversion,
otherwise it is not converted. In other
words, unary numeric promotion converts
operands of byte, short, char to int by
applying an implicit widening conversion,
but the operands of other numeric types
are not affected.
 byte b=3
 b=(byte) –b // numeric promotion of byte
 Binary Arithmetic Operators-

* Multiplication / Division % Modulus


+ addition - Subtraction

 Numeric promotions- When binary operations


are applied to
numeric arguments (integer and floating-point),
numeric
promotion is performed before the operation
takes place.
The binary addition operator ‘+’ performs two
tasks:

 One is to add two numbers

 Second is to concatenate two String


objects in Java
 Binary Arithmetic Operators-
* Multiplication / Division % Modulus
+ addition - Subtraction

 Numeric promotions- When binary operations are


applied to numeric arguments (integer and
floating-point), numeric promotion is performed
before the operation takes place. The numeric
promotion consists of converting the values of
the operands to a common type. The rules are:

 One operand double , other is converted to


double.
 Otherwise, if one is float, then other is
converted to float.
 Otherwise if one is long, other is converted
to long
 Otherwise both the operands are converted
to int
Comparison operators- to compare primitive values
or object references.
These operators are organized into three groups:
 Relational operators----defined only for numeric values
 Equality operators
 instanceof operator------defined only for object references

 Relational operators- Four relational operators are:


<
>
 <=
 >=
 Results in a boolean value true or false if the operands on both
sides show the same relation as the operator or otherwise.
 Equality operators

 ==
 !=

 When object references are compared, they are compared


for same object instance and not whether the objects
have the same value.

 equals method- This method is defined in Object class as a


means to compare the values of two objects. All the
subclasses of Object class like String class inherit this
method and use it to compare the object values rather than
their instance equality.
 instanceof operator- This is a binary operator that is used to
determine whether an object reference (the left operand) is an instance of
the class, interface or array type specified by the right operand. It cannot
be used with primitive values( compilation error).

 Logical Operators- Java supports two groups of logical


operators, the boolean operator !(not), & (and), | (or) and ^
(Exclusive-or) and the logical short circuit operators
&&( short-circuit and) and || (short-circuit or). All of these
operators are restricted to boolean operands.
 Assignment Operators-
 =
 +=
 -=
 /=
 *=
 %=
 &=
 |=
 ^=
 <<=
 >>=
Bitwise Operators- The bitwise
operators are:
 ~(inversion)---------------unary operator.
Inverses the bits that make up the integer
value Binary operators
 & (and)
 | (or)
 ^ (exclusive-or)

Shift Operators- The shift operator <<(left


shift),
>> (right shift) and >>> (unsigned right
shift) also
work on the bit level.
Bitwise Operators- The bitwise
operators are:
~(inversion)---------------unary operator.
Inverses the bits that make up the integer
value
Binary operators
& (and)
| (or)
^ (exclusive-or)
&----returns a 1 bit if the corresponding
bits of its operands are both 1. It returns a
0 otherwise
|---returns a 1 bit if one of the
corresponding bits of its operands is 1 or
if both of the corresponding bits of its
operands is 1. it returns a 0 otherwise
 ShiftOperators- The shift operator <<(left shift),
>> (right shift) and >>> (unsigned right shift)
also work on the bit level.
 The << operator causes the bits of the left
operand to be shifted to the left based on the
value of the right operand. The new bits that are
used to fill in the shifted right bits have the value
0.
 Each left shift corresponds to multiplication of
the value by 2. thus if shift is to be done by n,
the value will be multiplied by 2n
class ByteShift {
public static void main(String args[]) {
byte a = 64, b;
int i;
i = a<< 2; //due to numeric promotion, we are
assigning to int
variable
b = (byte) (a << 2);
System.out.println("Original value of a: " + a);
System.out.println("i and b: " + i + " " + b);
Right Shift Operator- The >> operator
causes the bits of the left operand to be
shifted to the right based on the value of
the right operand. The new bits that are
used to fill in the shifted left bits have the
value of the leftmost bit (before the shift
operation). The syntax for giving this shift
is:
value>>num

 This is called the sign shift as it


preserves the sign (positive or
negative) of the operand.

When a negative value is shifted right,


ones are filled in from the left.
• Shifting the operand one bit to right is same as dividing it
by 2 and ignoring the remainder.
64 >> 1 gives 32 which is equal to 64 / 21
64 >> 2 gives 16 which is equal to 64 / 22
The >>> operator is identical to the
>> operator except that the bits
that fill in the shifted left bits have
the value 0.This is said to be
unsigned shift as it does not
preserve the sign of the operand.
• One’s Complement Operator
– it can be effectively used is in development of a file encryption utility.

• Bitwise AND Operator


– Probably, the best use of the AND operator is to check whether a particular bit of an operand is
ON or OFF. This facility of checking the bit value as on or off is most useful in finding the type of a
file
– The second, and equally important use of the AND operator is in changing the status of the bit, or
more precisely to switch OFF a particular bit.

• Bitwise OR Operator
– Bitwise OR operator is usually used to put ON a particular bit in a number.

• Bitwise XOR Operator


– XOR operator is used to toggle a bit ON or OFF. A number XORed with another number twice
gives the original number.
• Logical Operators- Java supports two groups of
logical operators, the boolean operator !(not), &
(and), | (or) and ^ (Exclusive-or) and the logical
short circuit operators &&( short-circuit and) and ||
(short-circuit or). All of these operators are
restricted to boolean operands.
• The ! Operator performs the logical negation. It
changes true value to false and false value to true.
• &,| and ^ operate in the same manner as the
bitwise operators do when applied to each bit.
 The ternary operator- The ternary operator ?:, also referred
to as the conditional operator has three operands and takes
the following forms:

operand1 ? operand2 : operand3

You might also like