Beruflich Dokumente
Kultur Dokumente
Java
Session Objectives
Introduction to Java
Java Features
Java Architecture
History of Java
Java began as Programming Language Oak.
Oak - Developed by members of Green Project, which included James
Gosling and 2 more people in 1991 to create products for electronics
market.
Existing programming languages were not suited for the same.
Chief Programmer of Sun Microsystems, James Gosling, was given the
task of creating software for controlling consumer electronic devices.
The requirement of Software was to run on different kinds of computers,
should have power of networks and be based on web.
Members of the Oak team realized that Java would provide the required
cross platform independence that is independent from hardware,network
and OS.
Features of Java
Java is simple:
The syntax of Java is similar to C++. Java does not support
pointers, multiple inheritance, goto statement, and operator
overloading
The byte data type of Java occupies one byte of memory space and
can store integral numbers
The other data type boolean can store any one of the two
boolean values, true and false
Java omits pointers and structs that are available in C++
JVM Tasks
All class files imported across the network pass through the
bytecode verifier, which ensures that:
The code adheres to the JVM specification.
The code does not violate system integrity.
The code causes no operand stack overflows or underflows.
The parameter types for all operational code are correct.
No illegal data conversions (the conversion of integers to
pointers) have occurred.
System.out.println(Hello);
}
}
JDK Versions
JDK Editions
Java Standard Edition (J2SE)
A Simple Application
Example 1.1
//This application program prints Welcome
//to Java!
package chapter1;
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}
Source
Run
NOTE: To run the program,
install slide files on hard
disk.
- javac file.java
Source Code
Bytecode
Run Byteode
i.e. java Welcome
Result
How it works!
Compile-time Environment
Compile-time Environment
Class
Loader
Bytecode
Verifier
Java
Source
(.java)
Java
Compiler
Java
Bytecodes
move locally
or through
network
Java
Interpreter
Just in
Time
Compiler
Runtime System
Java
Bytecode
(.class )
Operating System
Hardware
Java
Class
Libraries
Java
Virtual
machine
How it works!
Executing Applications
On command line
- java classname
Bytecode
Java
Interpreter
on Windows
Java
Interpreter
on Linux
...
Java
Interpreter
on Sun Solaris
Example
javac Welcome.java
java Welcome
output:...
Java uses all the system resources such as the display device
and the keyboard with the help of the System class. This class
contains all the methods that are required to work with the
system resources
The out object encapsulated inside the System class
represents the standard output device. This object contains the
println() method
The println() method displays data on the screen
Data Types
Data Types
int
It is a 32-bit signed two's complement integer data type. It ranges from 2,147,483,648 to 2,147,483,647. This data type is used for integer values.
However for wider range of values use long.
byte
The byte data type is an 8-bit signed two's complement integer. It ranges from 128 to127 (inclusive). We can save memory in large arrays using byte. We can
also use byte instead of int to increase the limit of the code.
short
The short data type is a 16-bit signed two's complement integer. It ranges from 32,768 to 32,767. short is used to save memory in large arrays.
long
The long data type is a 64-bit signed two's complement integer. It ranges from 9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. Use this data type
with larger range of values.
Data Types
float
The float data type is a single-precision 32-bit IEEE 754 floating point. It ranges
from 1.40129846432481707e-45 to 3.40282346638528860e+38 (positive or
negative). Use a float (instead of double) to save memory in large arrays. We do
not use this data type for the exact values such as currency. For that we have to
use java.math.BigDecimal class.
double
This data type is a double-precision 64-bit IEEE 754 floating point. It ranges from
4.94065645841246544e-324d to 1.79769313486231570e+308d (positive or
negative). This data type is generally the default choice for decimal values.
boolean
The boolean data type is 1-bit and has only two values: true and false. We use
this data type for conditional statements. true and false are not the same as True
and False. They are defined constants of the language.
char
The char data type is a single 16-bit, unsigned Unicode character. It ranges from 0
to 65,535. They are not same as ints, shorts etc.
Type
int
Explanation
A 32-bit (4-byte) integer value
short
long
byte
float
double
char
Identifiers
Identifiers are used for class names,method names and variable names.
Identifier may be any descriptive sequence of upper case and lower case
characters, numbers, or the underscore and dollar sign characters.
They must not begin with number.
Java is case-sensitive, so VALUE is different identifier than Value.
abstract
continue
goto
package
synchronized
assert
default
if
private
this
boolean
do
implements
protected
throw
break
double
import
public
throws
byte
else
instanceof
return
transient
case
extends
int
short
try
catch
final
interface
static
void
char
finally
long
strictfp
volatile
class
float
native
super
while
const
for
new
switch
Variables
The variable is an identifier that denotes a storage location used to store a data
value.
A variable name can be choosen by the programmer in a meaningful way so as to
reflect what it represents in the program. Variable names may consist of alphabets,
digits, the underscore(_) and dollar character, subject to the following conditions:
Declaration of Variables
The general form of variable declaration is:
float initVal;
int retVal, index = 2;
double gamma = 1.2, brightness
boolean valueOk = false;
Initialisation
If no value is assigned prior to use, then the compiler will give an error
Java sets primitive variables to zero or false in the case of a boolean variable
All object references are initially set to null
An array of anything is an object
Declarations
Assignment
int a = 1, b = 2, c = 5
a=b=c
System.out.print(
a= + a + b= + b + c= + c)
What is the value of a, b & c
Done right to left: a = (b = c);
Flow of Control
Java executes one statement after the other in the order they are written
Many Java statements are flow control statements:
Alternation: if, if else, switch
Looping:
for, while, do while
Escapes:
break, continue, return
The if statement evaluates an expression and if that evaluation is true then the specified
action is taken
if ( x < 10 ) x = 10;
If the value of x is less than 10, make x equal to 10
It could have been written:
if ( x < 10 )
x = 10;
Or, alternatively:
if ( x < 10 ) { x = 10; }
Relational Operators
==
!=
>=
<=
>
<
Equal (careful)
Not equal
Greater than or equal
Less than or equal
Greater than
Less than
If else
The if else statement evaluates an expression and performs one action if that evaluation
is true or a different action if it is false.
if (x != oldx) {
Nested if else
else if
if ( n == 1 ) {
// execute code block #1
}
else if ( j == 2 ) {
// execute code block #2
}
else {
// if all previous tests have failed, execute
code block #3
}
A Warning
WRONG!
if( i == j )
if ( j == k )
System.out.print(
i equals k);
else
System.out.print(
i is not equal
to j);
CORRECT!
if( i == j ) {
if ( j == k )
System.out.print(
i equals k);
}
else
System.out.print(i is
not equal to j); //
Correct!
Loop n times
while loops
while(response == 1) {
System.out.print( ID = + userID[n]);
n++;
response = readInt( Enter );
}
What is the minimum number of times the loop
is executed?
What is the maximum number of times?
TYPE CASTING
In some situations we need to store a value of one type into a variable
of another type. In such situations, we must cast the value to be
stored by proceeding ot with the type name in paranthesis.
syntax:
type variable2 = (type) variable2;
do { } while loops
do {
System.out.print( ID = + userID[n] );
n++;
response = readInt( Enter );
}while (response == 1);
Break
A break statement causes an exit from the innermost containing while, do, for
or switch statement.
Continue
userID);
Arrays
- name
- type
- length
These must be declared when the array is created.
Arrays sizes cannot be changed during the execution of the code
TYPE CASTING
The process of converting one data type to another is called casting. Casting is often
necessary when a method return a type different than the one we require.
Four integer types can be cast to any other type except boolean. Casting into a smaller
type except boolean. Similarly, the float and double can be cast to any other type
except boolean. But casting to smaller type can result in a loss of data. Casting a
floating point value to an integer will result in a loss of the fractional part.
Example:
int m = 50;
byte n = (byte)m;
long count = (long)m;
TYPE CASTING
The following table , guarantees to result in no loss of information or data.
FROM
TO
byte
short
char
int
long
float, double
float
double
Casting
Example:
Creation and Casting of variables
class TypeWrap{
public static void main(String args[]) {
System.out.println("Variable Created");
char c= 'x';
byte b=50;
short s=1996;
int i=12345; int j= 123;
long l=12345654321L;
float f1=3.142F; float f2=1.2e-5F;
double d2=0.000000987;
short s1 = (short)b; short s2 = (short)i; // produces incorrect result
float f = (float)i;
int n = (int)f1; // Fractional part is lost
byte b1 = (byte)i; // produces incorrect result
byte b2=(byte)j;
System.out.println(" s1 = " + s1);
System.out.println(" s2 = " + s2);
System.out.println(" f = " + f);
System.out.println(" n = " + n);
System.out.println(" b1 = " + b1);
System.out.println(" b2 = " + b2);
}
Operators
Operators
Arithmetic Operators
+,-,*,/,%
++,--
Relational Operators
= =,!=,>,<,>=,<=
And,Or,Not
Ternary Operator
Operators Precedence
()
[]
Highest
++
--
>
>=
==
!=
<
<=
&
&&
||
?:
=
Lowest
Introduction
Classes And Objects
Encapsulation
car
Super class
Polymorphism
manual
draw()
automatic
Subclasses
draw()
Class Fruit{
int grams;
int cals_per_gram;
int total_calories() {
return(grams*cals_per_gram);
}
}
Methods
A method is a named sequence of code that can be invoked by other Java code.
A method takes some parameters, performs some computations and then optionally returns
a value (or object).
Methods can be used as part of an expression statement.
public float convertCelsius(float tempC) {
return( ((tempC * 9.0f) / 5.0f) + 32.0f );
}
Method Signatures
Public/private
Using objects
Here, code in one class creates an instance of another class and does something
with it
Constructors
The line
Overloading
Fruit() {grams=50;}
Fruit(a,b) { grams=a; cals_per_gram=b;}
By looking at arguments Java decides which version to use
What is a class?
A class consists of
Name conventions
An example of a class
class Person {
String name;
int age;
void birthday ( ) {
age++;
System.out.println (name + ' is
now ' + age);
}
}
Person john;
john = new Person ( );
john.name = "John Smith";
john.age = 37;
Person mary = new Person ( );
mary.name = "Mary Brown";
mary.age = 33;
mary.birthday ( );
1. Data Abstraction
2. Encapsulation
3. Inheritance
4. Polymorphism
Classes
A Class is blueprint that defines the variables and methods common to all
objects of a certain kind. Class is a user-defined data type with a template that
serves to define its properties. Once the class type has been defined, we can
create "variables" of primitive data types similar to the basic type declarations
and also methods, which are also called as functions. In Java, these variables
and methods are termed as instances of classes.
Defining of Class
Syntax:
[variable declaration;]
[method declaration;]
Objects
An Object is a representation (instance )of a class, which
inherits all the properties from his class.
Declaration of Objects: ClassName objectName;
Example:
Circle myCircle;
A Circle object
Data Field
radius = 5
Method
findArea
Creating Objects
Syntax:ClassName objectName = new ClassName();
Example:
Circle myCircle = new Circle(); // Dynamic Memory Allocation using
new operator
Constructors
We know that all objects that are created must be given initial values.
It would be simpler and more concise to initialize an object when it is first
created.
Java supports a special type of method, called a constructor that initializes it
when it is created.
In the Java(TM) programming language, constructors are instance methods with
the same name as their class.
Constructors are invoked using the new keyword. A constructor method is a
special type of method that determines how an object is initialized when created.
They have as same name as the class and do not have any return type.
When a keyword new is used to create an instance of a class. Java allocates
memory for the object, initializes the instance variables and calls the constructor
methods.
Every class has a default constructor that does not take any argument and the
body of it does of it not have any statements.
Constructors Example
class Circle
{
int radius ;
Circle(int a)
//Constructor
{
radius=a;
}
void findArea()
{
System.out.println("Area of c1 = " + (3.14f*radius*radius));
}
public static void main(String args[])
{
Circle c1;
//object declaration
c1=new Circle(10);
//object creation
c1. findArea() ;
c1=new Circle(50);
c1. findArea() ;
}
}
public Access:
Any variable or method is visible to the entire class in which it is defined.
What if we to make it visible to all the classes outside this class? This is possible
by simply declaring the variable as public. A variable or method declares as
public has the widest possible visibility and accessible everywhere, and any
class can use it.
private Access:
It is narrowly visible and the highest level of protection that can possibly be
obtained. private methods and variables cannot be seen by any class other than
the one which they are defined. They are extremely restrictive but are most
commonly used. They are accessible only within their own class. They cannot
be inherited by subclasses and therefore not accessible in subclasses.
protected Access:
This protected specifier is the relationship between a class and its present
and future subclasses. The subclasses are closer to the parent class than any
other class. This level gives more protection and narrow visibility.
package Access:
package is indicated by the lack of any access modifier in a declaration. It
has an increased protection and narrowed visibility and is the default protection
when none has been specified.
Scope of Variables
this keyword
The keyword this is useful when you need to refer to instance of the class from
its method.
The keyword helps us to avoid name conflicts.
As we can see in the program that we have declare the name of instance
variable and local variables same.
Now to avoid the confliction between them we use this keyword.
Here, this section provides you an example with the complete code of the
program for the illustration of how to what is this keyword and how to use it.
Constructor Overloading
& this Keyword
class Student {
int rollno;
String name;
Student(int rollno) {
this.rollno=rollno;
}
Student(int rollno,String name){
this.rollno=rollno;
this.name=name;
}
public static void main(String args[])
{
Student scott=new Student(101,);
Student peter=new Student(102,Peter);
}
}
Method Overloading
class Student {
int rollno;
String name;
void setDetails(int rollno) {
this.rollno=rollno;
}
void setDetails(int rollno,String name){
this.rollno=rollno;
this.name=name;
}
public static void main(String args[]) {
Student scott=new Student();
scott.setDetails(101);
Student peter=new Student();
peter.setDetails(102,peter);
}
}
Summary
In this Session