Java - Unit I
Java - Unit I
Java Platform:
The Java platform has two components – API and Java Virtual Machine
Java was developed by James Ghosling, Patrick Naughton, Mike Sheridan at Sun
Microsystems Inc. in 1991. It took 18 months to develop the first working version.
The initial name was Oak but it was renamed to Java in 1995.
4. The java launcher tool then runs your application with an instance of the Java Virtual
Machine.
5. Through the JVM, the same application is capable of running on multiple platforms.
Bytecode:
1) 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.
2) Although the details of the JVM will differ from platform to platform, all understand
the same Java bytecode.
3) A Java program is executed by the JVM also helps to make it secure. Because the
JVM is in control, it can contain the program and prevent it from generating side
effects outside of the system.
Java vs C vs C++
Aspects C C++ Java
Developed Year 1972 1979 1991
Developed By Dennis Ritchie Bjarne Stroustrup James Gosling
Paradigms Procedural Object Oriented Object Oriented
Platform Dependent Dependent Independent
Dependency
Header files Supported Supported Use Packages
(import)
Pointers Supported Supported No Pointers
Storage Allocation Uses malloc, calloc Uses new , delete uses garbage
collector
Linker
application
This C++ compiler
appliction (executabl does not care
e)
runs about
directly on filenames.
top of OS.
Java compiler
6
b) Applets
i. Portability is a major aspect of the Internet because there are many different
types of computers and operating systems connected to it.
ii. The Bytecode made Java code to be portable.
iii. Security : Java achieved the security by confining internet based programs
(applet) to the Java execution environment and not allowing it access to other
parts of the computer
1. Simple:
a) Java is easy to learn and its syntax is quite simple, clean and easy to understand.
b) It is simple because, Syntax is based on C and C++.
c) Java removed pointers and operator overloading concepts.
2. Object oriented:
iv. Inheritance
v. Polymorphism
vi. Abstraction
3. Distributed: Java is designed for the distributed environment of the Internet because it
handles TCP/IP protocols. Java has features that enables a program to invoke methods
across a network.
5. Dynamic: Java programs carry with them substantial amounts of run-time type
information that is used to verify and resolve accesses to objects at run time. This makes it
possible to dynamically link code in a safe and expedient manner. This is crucial to the
robustness of the Java environment, in which small fragments of bytecode may be
dynamically updated on a running system.
i. C and C++ are platform dependency languages, But Java is platform independent
language.
ii. Java designers goal was “Write once; run anywhere, any time, forever”(WORA).
Java programs written in one operating system can able to run on any operating
system.
iii. Java compiler generates an architecture-neutral bytecode which makes the compiled
code to be executable on many processors with the presence of Java run time
system (JVM).
7. Portable: Java is a portable language means, we can carry the same Java bytecode to
any platform.
9. High Performance: Java is faster than traditional interpretation since byte code 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 (JIT).
9
10. Robust: The ability to create robust programs was given a high priority in the design
of Java.
i. No explicit pointers.
ii. Java Programs run inside virtual machine environment.
Evolution of Java
Java continued to evolve at an explosive pace.
It has dynamic history. Since the beginning, Java has been at the center of a culture of
innovation.
10
JDK
JRE
JVM
JIT
11
1) the libraries,
3) and other components to run applets and applications written in the Java
programming language.
5) The JRE does not contain compilers or debuggers for developing applets and
applications.
JRE = The Libraries + JVM + Java Plug-in + Java Web Start + Other components
2) The Java virtual machine is an abstract computing machine that has an instruction
set and manipulates memory at run time.
3) The Java Virtual Machine is responsible for the hardware- and operating system-
independence of the Java SE platform, the small size of compiled code (bytecodes),
and platform security.
4) JVM includes dynamic compilers – Just In Time Compilers (JIT) that adaptively
compile Java bytecodes into optimized machine instructions.
1. class loader subsystem: a mechanism for loading types (classes and interfaces)
3. Run Time Data areas: The Virtual machine organizes the memory it needs to
execute a program into several runtime data areas.
i. Method area: All the class data has been placed on to the method area.
ii. Heap: All objects the program instantiates is placed onto the heap.
iii. Java Stacks: A Java stack stores the state of Java (not native) method
invocations for the thread.
iv. PC registers: The value of the pc register indicates the next instruction to
execute.
v. Native Method stacks: Native methods are the methods written in a
language other than the Java programming language. These are the stacks
created for other languages functions or operating system functions.
Organizes a program around its code. Organizes a program around its data (that is, objects).
proce metho
dure d
metho Object
d data
proce
dure metho
Global
proce d
metho Object
data
dure d data
proce metho
dure d
metho Object
d data
Components:
1. Classes
2. Objects
3. Abstraction
15
Class: A class defines the structure and behavior (data and code) that will be shared by a
set of objects. A class is a structure that defines the data and the methods (functions in
other languages) to work on that data.
import java.lang.System;
class ExampleProgram
{
public static void main(String[] args)
{
System.out.println(“Hello World");
}
}
1) There can be any number of objects of a given class in memory at any one time.
2) Software objects are conceptually similar to real-world objects.
3) Objects consist of state and behavior.
4) An object stores its state in fields (variables in some programming languages) and
exposes its behavior through methods (functions in some programming languages).
16
Abstraction:
Hierarchical classifications
CAR
MP3 player
Radio
CD Player
17
1. Encapsulation:
Encapsulation is the mechanism that binds together code and the data it manipulates,
and keeps both safe from outside interference and misuse.
Example:
18
class Bicycle
{
int cadence = 0; Member
int speed = 0; variables (OR)
int gear = 1; Instance
Member
variables memb
methods (OR)
void changeGear(int newValue) ers
methods
{
gear = newValue;
}
}
class BicycleDemo
{
public static void main(String[] args)
{
// Create two different Bicycle objects
Bicycle bike1 = new Bicycle();
Bicycle bike2 = new Bicycle();
bike1.changeGear(2);
bike2.changeGear(5);
}
}
2. Inheritance:
Inheritance is the process by which one object acquires the properties of another object.
ii. Inheritance allows classes to inherit commonly used state and behavior from other
classes.
iii. It supports the concept of hierarchical classification.
iv. Benefits are : Code reuse and Decrease of Program size
v. In the Java programming language, all classes descend from java.lang.Object, that
is, Object is the superclass for all classes.
Example:
a) Different kinds of objects often have a certain amount in common with each other.
Mountain bikes, road bikes, and tandem bikes, for example, all share the
characteristics of bicycles (current speed, current pedal cadence, current gear).
b) Yet each also defines additional features that make them different: tandem bicycles
have two seats and two sets of handlebars; road bikes have drop handlebars; some
mountain bikes have an additional chain ring, giving them a lower gear ratio.
Superclass
subclasses
The syntax for creating a subclass is simple. At the beginning of your class declaration, use
the extends keyword, followed by the name of the class to inherit from:
In the Java programming language, each class is allowed to have one direct
superclass, and each superclass has the potential for an unlimited number
of subclasses.
Definition:
Polymorphism in java is a concept by which we can perform a single action by
different ways.
Types of Polymorphism:
Example
Example:
class BlockTest {
public static void main(String args[]) {
if(x < y) If X is less than Y then both
{ // begin a block statements inside the block
x = y; will be executed.
y = 0;
} // end of block
}
}
whitespace
a) Java is a free-form language – do not need to follow any indentation rules.
b) In Java, whitespace is a space, tab, or newline.
Identifiers
a) Identifiers are used to name classes, variables, and methods.
b) An identifier may be any descriptive sequence of uppercase and lowercase letters,
numbers, or the underscore and dollar-sign characters.
c) Java is case-sensitive language.
AvgTemp 2count
Count high-temp
A4 Not/ok
$test
This_is_ok
Literals
Example:
Integer Literals
Ex: ox7f
Floating-point Literals
1) Represented in –
a) Standard notation -> 2.0, 3.14
b) Scientific notation -> 6.022E23, 314159E-05
2) Floating point literals in Java default to double precision.
3) To specify a float literal, we must append an F or f to the constant.
4) Hexadecimal floating point literals are also supported.
Ex: 0x12.2P2
Boolean Literals
It contains only two logical values - true or false. These values do not convert into any
numerical representation.
Character Literal
1) A literal character is represented inside a pair of single quotes.
2) All of the visible characters can be directly entered inside the quotes, such as 'a', 'z',
and '@'.
3) For characters that are impossible to enter directly, there are several escape
sequences.
Ex: ‘\’’ for single-quote character
‘\n’ for the new line character
4) Characters can be represented in Octal and Hexadecimal notation
Octal
backslash followed by the three-digit number. For example, ' \141' is the letter 'a'.
Hexadecimal
a backslash-u ( \u), then exactly four hexadecimal digits. For example, ' \u0061'
String Literal
String literals in Java are specified by enclosing a sequence of characters between a pair of
double quotes.
25
Example:
"Hello World"
"two\nlines"
" \"This is in quotes\""
Comments
Example : /**
First Java Program
*/
Separators
Keywords are the reserved words which can not be used as identifiers in program.
26
Example:
println() and print() methods are built-in methods and available through System.out.
System is a predefined class and out is an output stream associated with system.
a) Every variable has a type, every expression has a type, and every type is strictly
defined.
b) All assignments, whether explicit or via parameter passing in method calls, are
checked for type compatibility.
c) There are no automatic conversions of conflicting types as in some languages.
d) The Java compiler checks all expressions and parameters to ensure that the types
are compatible.
byte b;
boolean myBooleanPrimitive;
3) The number types (both integer and floating point types) are all signed, meaning they can
be negative or positive.
4) The leftmost bit (the most significant digit) is used to represent the sign, where a 1 means
negative and 0 means positive. The rest of the bits represent the value, using two's
complement notation.
char 16 2 0 65535
boolean: The boolean data type has only two possible values: true and false.
Characters (char)
Example
29
class CharDemo
{ Output:
public static void main(String args[]) {
char ch1, ch2; ch1 and ch2 : X Y
ch1 = 88; // code for X
ch2 = 'Y';
System.out.print("ch1 and ch2: ");
System.out.println(ch1 + " " + ch2);
}
}
This is executed.
// a boolean value can control the if statement
if(b) 10 > 9 is true
System.out.println("This is executed.");
b = false;
Reference Types
reference
Object o;
Pen p1;
String s1, s2, s3; // declare three String vars.
Example
class A
{
int i;
void m1() {
System.out.println(“Hello”);
}
class Test
{
31
Variables :
Variables are the identifiers of the memory location, which used to store the data temporary
for later use.
Declaring a Variable:
c) To declare more than one variable of the specified type, use a comma-separated list.
Example:
Dynamic Initialization:
Java allows variables to be initialized dynamically, using any expression valid at the time
the variable is declared.
class DynInit {
public static void main(String args []) {
double a = 3.0, b = 4.0;
// c is dynamically initialized
double c = a + b;
Scope:
a) A scope determines what objects are visible to other parts of your program.
b) It also determines the lifetime of those objects.
a) The scope defined by a method begins with its opening curly brace and ends with
closing curly brace.
b) Variables declared inside a scope are not visible (that is, accessible) to code that is
defined outside that scope.
c) Every block defines a new scope.
d) Scopes can be nested:
i. objects declared in the outer scope will be visible to the code within
the inner scope.
ii. Objects declared within the inner scope will not be visible outside it.
iii. We cannot declare a variable to have the same name as one in an
outer scope.
class Scope {
public static void main(String args[]) {
int x; // known to all code within main
x = 10;
{ // start new scope
int y = 20; // known only to this block
// Nested scope – Outer scope and inner scope with same variable
class ScopeErr {
public static void main(String args[]) {
int bar = 1;
{ // creates a new scope
int bar = 2; // Compile-time error – bar already defined!
}
}
}
Lifetime of a variable
class LifeTime {
public static void main(String args[]) {
int x;
y = 100;
System.out.println("y is now: " + y);
}
}
}
1) 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:
i. The two types are compatible.
ii. The destination type is larger than the source type.
2) For widening conversions, the numeric types, including integer and floating-point
types, are compatible with each other.
3) There are no automatic conversions from the numeric types to char or boolean.
4) Java also performs an automatic type conversion when storing a literal integer
constant into variables of type byte, short, long, or char.
(target-type) value
Note:
When a floating-point value is assigned to an integer type then truncation will occur.
If the size of the value is too large to fit into the target integer type, then that value
will be reduced modulo (the remainder of an integer division by the) target
type’s range.
// Demonstrate casting
class Casting {
public static void main(String args[]) {
byte b; Output:
int I = 257;
double d = 323.142; Conversion of int to byte.
Example:
Output:
byte b = 50;
Compilation Error (because, in expression,
byte is promoted to int so, the result also int)
36
b = b * 2;
Example
class Test {
public static void main(String args[]) {
byte b = 42;
char c = 'a'; Output:
short s = 1024;
int i = 50000; 235.2 + 515 - 126.3616
float f = 5.67f;
double d = .1234; result = 623.8384122070313
Arrays
1. In Java, arrays are objects.
2. An array is a container object that holds a fixed number of values of a single type.
3. Arrays can hold either primitives or object references, but the array itself will
always be an object on the heap memory.
4. Arrays offer a convenient means of grouping related information.
5. In Java all arrays are dynamically allocated.
6. We can access a specific element in the array by specifying its index within square
brackets. All array indexes start at zero.
Types of Arrays
a) One-Dimensional arrays
37
b) Multidimensional arrays
One-Dimensional arrays
Syntax:
type var-name [ ];
var-name = new type [size];
Note:
int[ ] months;
months = new int[12];
Initializing an array:
Accessing an array:
month_days[0] = 31;
month_days[1] = 28;
month_days[2] = 31;
month_days[3] = 30;
month_days[4] = 31;
month_days[5] = 30;
month_days[6] = 31;
month_days[7] = 31;
month_days[8] = 30;
month_days[9] = 31;
month_days[10] = 30;
month_days[11] = 31;
System.out.println("April has " + month_days[3] + " days.");
}
}
array initializer
class Array
{
39
Multidimensional arrays
[0] [0] [0] [1] [0] [2] [0] [3] [0] [4]
Left index
determines row [1] [0] [1] [1] [1] [2] [1] [3] [1] [4]
[2] [0] [2] [1] [2] [2] [2] [3] [2] [4]
[3] [0] [3] [1] [3] [2] [3] [3] [3] [4]
class TwoDArray { p
public static void main(String args[]) {
int twoD[ ][ ]= new int[4][5]; Output:
01234
56789
10 11 12 13 14
15 16 17 18 19
40
int i, j, k = 0;
Example:
0
1 2
3 4 5
6 7 8 9
class TwoDAgain
{
public static void main(String args[])
{
int twoD[ ][ ] = new int[4][ ];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];
int i, j, k = 0;
}
}
Strings
Pointers
1) C and C++ supports pointers.
2) But, Java does not support or allow pointers
3) Java is designed in such a way that as long as we stay within the confines of the
execution environment, we never need to use a pointer.
4) There would not be any benefit using pointers.
5) In Java, memory management is handled by Garbage Collector.
UNIT – I END