[go: up one dir, main page]

0% found this document useful (0 votes)
5 views51 pages

JAVA-PPT M1 (1)

Java was developed by Sun Microsystems in the early 1990s, initially aimed at consumer electronics before being re-targeted for the Internet and renamed from Oak to Java in 1995. The language is characterized by key features such as simplicity, security, portability, and robustness, making it suitable for various applications. Java supports various data types, operators, control statements, and object-oriented programming principles, allowing for efficient software development.

Uploaded by

maitreyee658
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views51 pages

JAVA-PPT M1 (1)

Java was developed by Sun Microsystems in the early 1990s, initially aimed at consumer electronics before being re-targeted for the Internet and renamed from Oak to Java in 1995. The language is characterized by key features such as simplicity, security, portability, and robustness, making it suitable for various applications. Java supports various data types, operators, control statements, and object-oriented programming principles, allowing for efficient software development.

Uploaded by

maitreyee658
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

Java: History

⚫ In 1990, Sun Microsystems started a project called Green.


⚫ Objective: to develop software for consumer electronics.
⚫ Project was assigned to James Gosling, a veteran of classic
network software design. Others included Patrick
Naughton, ChrisWarth, Ed Frank, and Mike Sheridan.
⚫ The team started writing programs in C++ for embedding
into
– toasters
– washing machines
– VCR’s
⚫ Aim was to make these appliances more “intelligent”.
Java: History (contd)
⚫ Java was “re-targeted” for the Internet

⚫ The team was expanded to include Bill Joy (developer of


Unix), Arthur van
Hoff, Jonathan Payne, Frank Yellin, Tim Lindholm etc.
⚫ In 1994, an early web browser called WebRunner was written
in Oak.
WebRunner was later renamed HotJava.
⚫ In 1995, Oak was renamed Java.
⚫ A common story is that the name Java relates to the place
from where the development team got its coffee. The
name Java survived the trade mark search.
The Java Buzzwords
⚫ The key considerations were summed up by the Java
team in the following list of buzzwords:
❖ Simple
❖ Secure
❖ Portable
❖ Object-oriented
❖ Robust
❖ Multithreaded
❖ Architecture-neutral
❖ Interpreted
❖ High performance
❖ Distributed
❖ Dynamic
⚫ simple – Java is designed to be easy for the professional
programmer to learn and use.
⚫ object-oriented: a clean, usable, pragmatic approach to
objects, not restricted by the need for compatibility with
other languages.
⚫ Robust: restricts the programmer to find the mistakes early,
performs compile-time (strong typing) and run-time
(exception-handling) checks, manages memory
automatically.
⚫ Multithreaded: supports multi-threaded programming for
writing program that perform concurrent computations
⚫ Architecture-neutral: Java Virtual Machine provides
a platform independent environment for the execution
of Java byte code
⚫ Interpreted and high-performance: Java programs
are compiled into an intermediate representation –
byte code:
a) can be later interpreted by any JVM
b)can be also translated into the native machine code
for efficiency.
⚫Distributed: Java handles TCP/IP protocols,
accessing a resource through its URL much like
accessing a local file.
⚫Dynamic: substantial amounts of run-time type
information to verify and resolve access to objects
at run-time.
⚫Secure: programs are confined to the Java
execution environment and cannot access other
parts of the computer.
⚫Portability: Many types of computers and
operating systems are in use throughout the
world—and many are connected to the Internet.
⚫For programs to be dynamically downloaded to all
the various types of platforms connected to the
Internet, some means of generating portable
executable code is needed. The same mechanism
that helps ensure security also helps create
portability.
⚫Indeed, Java's solution to these two problems is
both elegant and efficient.

L 1.13
Data Types

⚫Java defines eight simple types:


1)byte – 8-bit integer type
2)short – 16-bit integer type 3)int
– 32-bit integer type 4)long – 64-
bit integer type
5)float – 32-bit floating-point type
6)double – 64-bit floating-point type
7)char – symbols in a character set
8)boolean – logical values true and false
⚫byte: 8-bit integer type.
Range: -128 to 127.
Example: byte b = -15;
Usage: particularly when working with data
streams.
⚫short: 16-bit integer type.
Range: -32768 to 32767.
Example: short c = 1000;
Usage: probably the least used simple type.
⚫ int: 32-bit integer type.
Range: -2147483648 to 2147483647.
Example: int b = -50000;
Usage:
1) Most common integer type.
2) Typically used to control loops and to index arrays.
3)Expressions involving the byte, short and int values are
promoted to int before calculation.

L 1.16
⚫ long: 64-bit integer type.
Range: -9223372036854775808 to
9223372036854775807.
Example: long l = 10000000000000000;
Usage: 1) useful when int type is not large enough to hold
the desired value
⚫ float: 32-bit floating-point number.
Range: 1.4e-045 to 3.4e+038.
Example: float f = 1.5;
Usage:
1) fractional part is needed
2) large degree of precision is not required
⚫ double: 64-bit floating-point number.
Range: 4.9e-324 to 1.8e+308.
Example: double pi = 3.1416;
Usage:
1) accuracy over many iterative calculations
2) manipulation of large-valued numbers

L 1.18
char: 16-bit data type used to store characters.
Range: 0 to 65536.
Example: char c = ‘a’;
Usage:
1) Represents both ASCII and Unicode character sets;
Unicode defines a
character set with characters found in (almost) all
human languages.
2)Not the same as in C/C++ where char is 8-bit and
represents ASCII only.
⚫boolean: Two-valued type of logical values.
Range: values true and false.
Example: boolean b = (1<2);
Usage:
1) returned by relational operators, such as 1<2
2)required by branching expressions such as if
or for

L 1.20
Variables
⚫ declaration – how to assign a type to a variable
⚫ initialization – how to give an initial value to a variable
⚫ scope – how the variable is visible to other parts of the
program
⚫ lifetime – how the variable is created, used and destroyed
⚫ type conversion – how Java handles automatic type
conversion
⚫ type casting – how the type of a variable can be narrowed
down
Variables

⚫Java uses variables to store data.


⚫To allocate memory space for a variable JVM
requires:
1) to specify the data type of the variable
2) to associate an identifier with the variable
3)optionally, the variable may be assigned an initial
value
⚫All done as part of variable declaration.

L 2.2
Basic Variable Declaration

⚫ datatype identifier [=value];


⚫ datatype must be
⚫ A simple datatype
⚫ User defined datatype (class type)
⚫ Identifier is a recognizable name confirm to identifier
rules
⚫ Value is an optional initial value.
Variable Declaration
⚫ We can declare several variables at the same time:
type identifier [=value][, identifier [=value] …];
Examples:
int a, b, c;
int d = 3, e, f = 5;
byte g = 22;
double pi = 3.14159;
char ch = 'x';

L 2.4
Variable Scope
⚫ Scope determines the visibility of program elements with respect
to other program elements.
⚫ In Java, scope is defined separately for classes and methods:
1) variables defined by a class have a global scope
2) variables defined by a method have a local scope
A scope is defined by a block:
{

}
A variable declared inside the scope is not visible outside:
{
int n;
}
n = 1;// this is illegal
Variable Lifetime

⚫Variables are created when their scope is entered


by control flow and destroyed when their scope is
left:
⚫A variable declared in a method will not hold its
value between different invocations of this
method.
⚫A variable declared in a block looses its value when
the block is left.
⚫Initialized in a block, a variable will be re-
initialized with every re-entry. Variables lifetime is
confined to its scope!
Arrays
⚫ An array is a group of liked-typed variables referred to by
a common
⚫ name, with individual variables accessed by their index.
⚫ Arrays are:
1) declared
2) created
3) initialized
4) used
⚫ Also, arrays can have one or several dimensions.
Operators Types

⚫Java operators are used to build value expressions.


⚫Java provides a rich set of operators:
1) assignment
2) arithmetic
3) relational
4) logical
5) bitwise

L 2.13
Arithmetic assignments
+= v += expr; v = v + expr ;

-= v -=expr; v = v - expr ;

*= v *= expr; v = v * expr ;

/= v /= expr; v = v / expr ;

%= v %= expr; v = v % expr ;
Basic Arithmetic Operators
+ op1 + op2 ADD

- op1 - op2 SUBSTRACT

* op1 * op2 MULTIPLY

/ op1 / op2 DIVISION

% op1 % op2 REMAINDER

L 2.15
Relational operator
== Equals to Apply to any type

!= Not equals to Apply to any type

> Greater than Apply to numerical type

< Less than Apply to numerical type

>= Greater than or equal Apply to numerical type

<= Less than or equal Apply to numerical type


Logical operators
& op1 & op2 Logical AND

| op1 | op2 Logical OR

&& op1 && op2 Short-circuit


AND
|| op1 || op2 Short-circuit OR

! ! op Logical NOT

^ op1 ^ op2 Logical XOR


L 2.17
Bit wise operators
~ ~op Inverts all bits

& op1 & op2 Produces 1 bit if both operands are 1

| op1 |op2 Produces 1 bit if either operand is 1

^ op1 ^ op2 Produces 1 bit if exactly one operand is 1

>> op1 >> op2 Shifts all bits in op1 right by the value of
op2
<< op1 << op2 Shifts all bits in op1 left by the value of
op2
Expressions
⚫An expression is a construct made up of variables,
operators, and method invocations, which are
constructed according to the syntax of the language, that
evaluates to a single value.
⚫Examples of expressions are in bold below:
int number = 0;
anArray[0] = 100;
System.out.println ("Element 1 at index 0: " +
anArray[0]);
int result = 1 + 2; // result is now 3 if(value1 ==
value2)
System.out.println("value1 == value2");
L 2.19
Expressions
⚫ The data type of the value returned by an expression depends on
the elements used in the expression.
⚫ The expression number = 0 returns an int because the
assignment operator returns a value of the same data type as its
left-hand operand; in this case, number is an int.
⚫ As you can see from the other expressions, an expression can
return other types of values as well, such as boolean or String.
The Java programming language allows you to construct
compound expressions from various smaller expressions as long
as the data type required by one part of the expression matches
the data type of the other.
⚫ Here's an example of a compound expression: 1*2*3
Control Statements

⚫ Java control statements cause the f low of execution to


advance and branch based on the changes to the state
of the program.
⚫ Control statements are divided into three groups:
⚫ 1) selection statements allow the program to choose
different parts of the execution based on the outcome
of an expression
⚫ 2) iteration statements enable program execution to
repeat one or more statements
⚫ 3) jump statements enable your program to execute in
a non-linear fashion
L 3.1
Selection Statements

⚫Java selection statements allow to control the flow


of program’s execution based upon conditions
known only during run-time.
⚫Java provides four selection statements:
1) if
2) if-else
3) if-else-if
4) switch
Iteration Statements
⚫ Java iteration statements enable repeated execution of
part of a program until a certain termination condition
becomes true.
⚫ Java provides three iteration statements:
1) while
2) do-while
3) for

L 3.3
Jump Statements

⚫ Java jump statements enable transfer of control to


other parts of program.
⚫ Java provides three jump statements:
1) break
2) continue
3) return
⚫ In addition, Java supports exception handling that can
also alter the control f low of a program.
Type Conversion
• Size Direction of Data Type
– Widening Type Conversion (Casting down)
• Smaller Data Type → Larger Data Type
– Narrowing Type Conversion (Casting up)
• Larger Data Type → Smaller Data Type
• Conversion done in two ways
– Implicit type conversion
• Carried out by compiler automatically
– Explicit type conversion
• Carried out by programmer using casting
L 3.5
Type Conversion

• Widening Type Converstion


– Implicit conversion by compiler automatically

byte -> short, int, long, float, double


short -> int, long, float, double
char -> int, long, float, double
int -> long, float, double
long -> float, double
float -> double
Type Conversion

• Narrowing Type Conversion


– Programmer should describe the conversion
explicitly
byte -> char
short -> byte, char
char -> byte, short
int -> byte, short, char
long -> byte, short, char, int
float -> byte, short, char, int, long
double -> byte, short, char, int, long, float
Type Conversion

⚫ byte and short are always promoted to int


⚫ if one operand is long, the whole expression is
promoted to long
⚫ if one operand is float, the entire expression is
promoted to float
⚫ if any operand is double, the result is double
Type Casting

⚫General form: (targetType) value


⚫Examples:
⚫1) integer value will be reduced module bytes
range:
int i;
byte b = (byte) i;
⚫2) floating-point value will be truncated to
integer value:
float f;
int i = (int) f;
L 3.9
Simple Java Program

⚫ A class to display a simple message:


class MyProgram
{
public static void main(String[] args)
{
System.out.println(“First Java program.");
}
}
What is an Object?

⚫Real world objects are things that have:


1) state
2)behavior
Example: your dog:
⚫state – name, color, breed, sits?, barks?, wages
tail?, runs?
⚫behavior – sitting, barking, waging tail, running
⚫A software object is a bundle of variables (state)
and methods (operations).
What is a Class?

⚫ A class is a blueprint that defines the variables and


methods common to all objects of a certain kind.
⚫ Example: ‘your dog’ is a object of the class Dog.
⚫ An object holds values for the variables defines in the
class.
⚫ An object is called an instance of the Class

L 4.3
Class

⚫ A basis for the Java language.


⚫ Each concept we wish to describe in Java must be
included inside a class.
⚫ A class defines a new data type, whose values are
objects:
⚫ A class is a template for objects
⚫ An object is an instance of a class
Class Definition

⚫ A class contains a name, several variable declarations


(instance variables) and several method declarations. All
are called members of the class.
⚫ General form of a class:
class classname {
type instance-variable-1;

type instance-variable-n;
type method-name-1(parameter-list) { … }
type method-name-2(parameter-list) { … }

type method-name-m(parameter-list) { … }
}

L 4.7
Example: Class Usage
class Box {
double width;
double height;
double depth;
}
class BoxDemo {
public static void main(String args[]) {
Box mybox = new Box();
double vol;
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
vol = mybox.width * mybox.height * mybox.depth;
System.out.println ("Volume is " + vol);
} }
Example: Method

⚫Classes declare methods to hide their internal data


structures, as well as for their own internal use: Within a
class, we can refer directly to its member variables:
class Box {
double width, height, depth;
void volume() {
System.out.print("Volume is ");
System.out.println(width * height * depth);
}
}
Parameterized Method

⚫Parameters increase generality and applicability of


a method:
⚫1) method without parameters
int square() { return 10*10; }
⚫2) method with parameters
int square(int i) { return i*i; }
⚫Parameter: a variable receiving value at the time
the method is invoked.
⚫Argument: a value passed to the method when it is
invoked.

L 5.6
Access Control: Data Hiding and
Encapsulation
• Java provides control over the visibility of variables
and methods.
• Encapsulation, safely sealing data within the capsule
of the class Prevents programmers from relying on
details of class implementation, so you can update
without worry
• Helps in protecting against accidental or wrong
usage.
• Keeps code elegant and clean (easier to maintain)
Access Modifiers: Public, Private,
Protected
• Public: keyword applied to a class, makes it
available/visible everywhere. Applied to a
method or variable, completely visible.
• Default(No visibility modifier is specified): it
behaves like public in its package and private
in other packages.
• Default Public keyword applied to a class,
makes it available/visible everywhere.
Applied to a method or variable, completely
visible.

L 6.2
⚫ Private fields or methods for a class only visible within
that class. Private members are not visible within
subclasses, and are not inherited.
⚫ Protected members of a class are visible within the
class, subclasses and also within all classes that are in
the same package as that class.
Visibility
public class Circle {
private double x,y,r;

// Constructor
public Circle (double x, double y, double r) {
this.x = x;
this.y = y;
this.r = r;
}
//Methods to return circumference and area
public double circumference() { return 2*3.14*r;}
public double area() { return 3.14 * r * r; }
}
L 6.4

You might also like