Java
Introduction
History of Java
• Java was originally developed by Sun Microsystems
starting in 1991
– James Gosling
– Patrick Naughton
– Chris Warth
– Ed Frank
– Mike Sheridan
• This language was initially called Oak
• Renamed Java in 1995
What is Java
• A simple, object‐oriented, distributed, interpreted,
robust, secure, architecture neutral, portable,
high‐performance, multithreaded, and dynamic
language ‐‐ Sun Microsystems
• Object‐Oriented
– No free functions
– All code belong to some class
– Classes are in turn arranged in a hierarchy or package
structure
What is Java
• Distributed
– Fully supports IPv4, with structures to support IPv6
– Includes support for Applets: small programs embedded in
HTML documents
• Interpreted
– The program are compiled into Java Virtual Machine (JVM)
code called bytecode
– Each bytecode instruction is translated into machine code
at the time of execution
Java Introduction:
Java Editions:
• Java 2 Platform, Standard Edition (J2SE)
– Used for developing Desktop based application and
networking applications
• Java 2 Platform, Enterprise Edition (J2EE)
– Used for developing large‐scale, distributed networking
applications and Web‐based applications
• Java 2 Platform, Micro Edition (J2ME)
– Used for developing applications for small
memory‐constrained devices, such as cell phones, pagers
and PDAs
Basic Concepts
Features of Java
Object Oriented Language
True OOPL
Reusability (built-in classes in packages)
Compiled and Interpreted
Compiler generates bytecode instructions
Interpreter generates machine instructions executable on the particular
machine
Platform-independent (Architecture-Neutral) and Portable
Change in program not required
Robust and Secure
Compile-time and run-time check for data types
Exception handling mechanism
Multi-threaded
Do many things concurrently with synchronization
Basic Concepts
OOP Principles
Encapsulation
Mechanism that binds together code and data it manipulates,
and keeps it safe from outside interference and misuse
Inheritance
Process by which one object acquires the properties of another
object
Polymorphism
A feature that allows one interface to be used for a general class
of actions
OOP Paradigm
• Class
• Object
• Methods
• Data
OOP Pillars
• Data Encapsulation
• Data Abstraction
• Inheritance
• Polymorphism
OOP Pillars Access
Modifiers
• Data Encapsulation
• Data Abstraction Public
• Inheritance
• Polymorphism Protected
Private
Process of Hiding details
OOP Pillars
• Data Encapsulation
• Data Abstraction
• Inheritance
• Polymorphism
OOP Pillars
• Data Encapsulation
• Data Abstraction
• Inheritance
• Polymorphism
Message
Communication
• An object-oriented
program consists of a
set of objects that
communicate with
each other.
• It involves the following
basic steps:
1. Creating classes
that define
objects and their
behavior.
2. Creating objects
from class
definitions.
3. Establishing
communication
among objects.
Data Science & Engineering, DCA, MIT
Some Topics for the Lab
• Java Program Structure
• Data Types and Variables
• Operators
• Control statements & Loops
• Type Conversion and Casting
• Arrays : 1-D & 2-D.
Java Program Structure
Documentation Section
Package Statements
Import Statements
Interface Statements
Class Definitions
Main Method Class
{
Main Method Definition
}
Case
[Link] Sensitive
Class name Comments /*
same as Source (enter)
/* file name
*This is a simple Java program.
One main()
*Call this file "[Link]". method among
*/ all class files
class HelloWorld
{
// Your program begins with a call to main().
public static void main(String args[])
{
[Link]("Hello.");
}
}
Examining [Link]
• public static void main(String[] args)
– main is the starting point of every Java application
– public is used to make the method accessible by all
– static is used to make main a static method of class
HelloWorld. Static methods can be called without using
any object; just using the class name. JVM call main using
the [Link] (Ex. [Link])
notation
– void means main does not return anything
– String args[ ] represents an array of String objects that
holds the command line arguments passed to the
application.
Examining [Link]
• [Link]()
– Used to print a line of text followed by a new line(ln)
– System is a class in [Link] package
– out is a public static member of class System
– out represents the standard output stream
– println is a public method of the class of which out is an
object
Examining [Link]
• [Link]() is similar to [Link](),
but does not print a new line automatically
• [Link]() is used to print formatted output
like printf() in C
• In Java, characters enclosed by double quotes ("")
represents a String object, where String is a class of
the Java API
• We can use the plus operator (+) to concatenate
multiple String objects and create a new String
object
Scanner class for reading input from keyboard
int a;
Scanner sc = new Scanner([Link]);
a = [Link]();
1) int nextInt()
It is used to read an integer value from the
keyboard.
2) float nextFloat()
It is used to read a float value from the
keyboard.
3) long nextLong()
It is used to read a long value from the
keyboard.
import [Link]; 4) String next()
It is used to read string value from the
keyboard.
Scanner example
import [Link];
class test
{ public static void main(String args[])
{ int a,b,c;
Scanner sc = new Scanner([Link]);
[Link]("Enter a first number");
a = [Link]();
[Link]("Enter a second number");
b = [Link]();
c = a+ b;
[Link]("sum is :"+c);
}
}
Scanner example-2
Data Types and Variables
Java Keywords
abstract continue for new switch
assert default goto package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
case enum instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp volatile
const float native super while
Comments
// for single line, /* and */ for multiline
Data Types and Variables
Primitive Data Types
Integers:
Java does not support unsigned integers
Name Width in bits Range
long 64 -9,223,372,036,854,775,808 9,223,372,036,854,775,807
int 32 -2,147,483,648 2,147,483,647
short 16 -32,768 32,767
byte 8 -128 127
Floating-Point:
Name Width in bits Approximate Range
double 64 4.9e-324 1.8e+308
float 32 1.4e-045 3.4e+038
Character: char 16 (Unicode)
Boolean: boolean 8 (true, false)
Data Types and Variables
Identifiers
Used for naming variables, methods, classes, interfaces and
packages
Sequence of uppercase and lowercase letters, numbers,
underscore and dollar-sign characters
Keywords cannot be used
Must not begin with a number
Case sensitive
Conventions:
Variables and Methods: Mixed Case
– first letter of each word except the first word in uppercase, others in
lowercase
Interfaces and Classes: Camel Case
– first letter of each word in uppercase, others in lowercase
Packages: Lower Case
Question:
Data Types and Variables
Scope and Lifetime of Variables
Example: void test()
{
int x = 10;
if (x == 10)
{
int y = 20; // y = 20
x = y * 2; // x = 40
[Link](“x = ” + x);
[Link](“y = ” + y);
}
y = 100; // cannot find symbol
x = x + 15;
[Link](“x = ” + x);
}
Operators
Arithmetic and Relational Operators
Operator Result
Operator Result
+ Addition
- Subtraction (also unary == Equal to
minus)
!= Not equal to
* Multiplication
/ Division > Greater than
% Modulus
< Less than
++ Increment
-- Decrement >= Greater than or equal to
+= Addition assignment <= Less than or equal to
-= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment
Operators
Bitwise and Boolean Logical Operators
Operator Result Operator Result
~ Bitwise unary NOT & Logical AND
& Bitwise AND | Logical OR
| Bitwise OR ^ Logical exclusive OR
|| Short-circuit OR
^ Bitwise exclusive OR
&& Short-circuit AND
>> Shift right
! Logical unary NOT
<< Shift left
&= AND assignment
&= Bitwise AND assignment
|= OR assignment
|= Bitwise OR assignment ^= XOR assignment
^= Bitwise exclusive OR == Equal to
assignment
!= Not equal to
>>= Shift right assignment
?: Ternary if-then-else
<<= Shift left assignment
Operator precedence Groups
highest
Operator Category Operators Associativity
Unary operators + - ++ -- ! R→L
Arithmetic operators */% L→R
Arithmetic Operators +- L→R
Shift Operators << >> L→R
Relational operators < <= > >= L→R
Equality operators == != L→R
Bitwise AND & L→R
Bitwise XOR ^ L→R
Bitwise OR | L→R
Logical AND && L→R
Logical OR || L→R
Conditional expression ?: R→L
Assignment operator = += -= *= /= %= R→L
lowest
30
Example:
Suppose that i, j and k are integer variables whose values are
i =1, j = 2 and k = 3 respectively
Expression Interpretation
i<j true
(i + j) >= k true
(j + k) >(i + 5) false
k != 3 false
j == 2 true
31
Control Statements
Jump (transfer of control) statements
(Continued …)
The return statement
Syntax: Same as in C and C++
– Used to return from a method
Other jump statements (used with exception handling)
try
catch
throw
throws
finally
Control Statements
Selection statements
The if statement
Syntax: Same as in C and C++
– if statements can be nested
– if-else-if ladder can be used
The switch statement
Syntax: Same as in C and C++
– switch statements can be nested
Note:
From JDK 7 onwards, strings can be used as case labels in ‘switch’
statement
Control Statements
Iteration statements
The while statement
Syntax: Same as in C and C++
The do-while statement
Syntax: Same as in C and C++
The for statement
Syntax: Same as in C and C++
Control Statements
Jump (transfer of control) statements
Basic form of the break statement
Syntax: Same as in C and C++
– Used with switch statement and loops
Labeled break statement
Syntax: break label;
Control Statements
OUTPU
T
Data Types and Variables
Type Conversion and Casting
Automatic Conversion: Conditions
Two types are compatible
– Numeric types (integer and floating-point) are compatible with each
other
Destination type is larger than source type
Examples:
byte to int – possible
Any numeric type to char/boolean – not possible
char and boolean – not compatible with each other
Automatic type conversion is done when a literal integer constant
is stored into variables of type byte, short, long and char
Type conversion example:
1. int a = 2;
2. float b = 2.5f;
3. double c = 11.11;
4. a = c; // Error
5. b = c; // Error
6. c = a; // OK
7. c = b; // OK
Data Types and Variables
Type Conversion and Casting (Continued …)
Syntax: (target-type) value
Example: int a; byte b; b = (byte) a;
Truncation in case of floating-point values
Example: 1.23 assigned to integer → 1 (0.23 truncated)
Examples:
byte b;
int i = 257;
double d = 323.142;
b = (byte) i; // 1 (remainder of special type of division)
i = (int) d; // 323 (0.142 lost)
b = (byte) d; // 67 (0.142 lost and reduced to modulo)
Data Types and Variables
Automatic Type Promotion in Expressions
Depends on precision required
Precision required by an intermediate value exceeds the range of
either operand
Example 1:
byte a = 40, b = 50, c = 100; int d = a * b / c;
– Result of a * b exceeds range of byte
– Promotes byte, short operand to int during evaluation
– a * b is performed using integers and …
Example 2:
byte b = 50; b = b * 2;
– Error, cannot assign an int to a byte (operands promoted to int)
– Use explicit type-casting
byte b = 50;
b = (byte) (b * 2);
Arrays
Basic Concepts of an Array
Arrays are dynamically created objects.
An array object contains a number of variables.
Number of variables may be zero (i.e., array is empty).
Variables contained in an array have no names
– They are referenced by array access expressions that use non-
negative integer index values (from 0 to n-1).
Array objects have a public instance variable called length,
which gives the number of elements in the array.
Arrays
One-Dimensional Arrays
Syntax: type var-name[];
Only declaration, memory not allocated
Allocate memory using new operator
array-var = new type[size]
Example 1:
int one[];
one = new int [5];
Example 2:
int one[] = new int [12];
Example 3:
int one[] = {1, 2, 3, 4, 5};
Arrays
Two-Dimensional Arrays
Syntax: type var-name[][];
Only declaration, memory not allocated
Allocate memory using new operator
array-var = new type[size][size]
Example 1:
int two[][];
two = new int [3][2];
Example 2:
int two [][] = new int [3][2];
Example 3:
int two[][] = {{1, 2}, {3, 4}, {5, 6}};
Arrays
Two-Dimensional Arrays (Continued …)
Example 4:
int two[][] = new int [3][];
two [0] = new int [2];
two [1] = new int [2];
two [2] = new int [2];
Example 5:
int two [][] = new int [3][];
two [0] = new int [1];
two [1] = new int [3];
two [2] = new int [2];
(Differing-size second dimension)
Arrays
Alternate methods of declaration
Alternate syntax:
1-D: type [] var-name;
2-D: type [][] var-name;
Example 1:
int a[] = new int [3];
int[] a = new int [3];
Example 2:
int b[][] = new int [3][4];
int[][] b = new int [3][4];
Example 3:
int num1[], num2[], num3[];
int[] num1, num2, num3;
Array Example:
OUTPUT
2-D Array example:
2-D Array example-2: