Unit 1 Java Basics
Unit 1 Java Basics
3
Before Java: C
4
Before Java: C++
• Designed by Bjarne Stroustrup in 1979.
• Response to the increased complexity of programs and respective improvements in
the programming paradigms and methods:
1) assembler languages
2) high-level languages
3) structured programming
4) object-oriented programming (OOP)
• OOP – methodology that helps organize complex programs through the use of
inheritance, encapsulation and polymorphism.
• C++ extends C by adding object-oriented features.
5
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”.
6
Java: History (contd.)
C++ is powerful, but also dangerous. The power and popularity of C derived from the
extensive use of pointers. However, any incorrect use of pointers can cause memory leaks,
leading the program to crash.
In a complex program, such memory leaks are often hard to detect.
Robustness is essential. Users have come to expect that Windows may crash or that a
program running under Windows may crash. (“This program has performed an illegal
operation and will be shut down”)
However, users do not expect toasters to crash, or washing machines to crash.
A design for consumer electronics has to be robust.
Replacing pointers by references, and automating memory management was the proposed
solution.
7
Java: History (contd.)
• Hence, the team built a new programming language called Oak, which avoided
potentially dangerous constructs in C++, such as pointers, pointer arithmetic,
operator overloading etc.
• Introduced automatic memory management, freeing the programmer to
concentrate on other things.
• Architecture neutrality (Platform independence)
• Many different CPU’s are used as controllers. Hardware chips are evolving rapidly.
As better chips become available, older chips become obsolete and their
production is stopped.
• Manufacturers of toasters and washing machines would like to use the chips
available off the shelf, and would not like to reinvest in compiler development
every two-three years. So, the software and programming language had to be
architecture neutral.
8
Java: History (contd)
• It was soon realized that these design goals of consumer electronics perfectly suited an
ideal programming language for the Internet and WWW, which should be:
object-oriented (& support GUI)
robust
architecture neutral
• Internet programming presented a BIG business opportunity. Much bigger than
programming for consumer electronics.
• Java was “re-targeted” for the Internet
• 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.
9
Java History
Designed by James Gosling, Patrick Naughton, Chris Warth, Ed Frank and Mike Sheridan
at Sun Microsystems in 1991.
With Internet, the urgent need appeared to break the fortified positions of Intel,
Macintosh and Unix programmer communities.
Java was not designed to replace C++, but to solve a different set of problems.
10
11
The Java Buzzwords
The key considerations were summed up by the Java team in the following list of buzzwords:
Simple Distributed
Secure Dynamic
Portable
Object-oriented
Robust
Multithreaded
Architecture-neutral
Interpreted
High performance
12
• 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
13
• 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.
14
• 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.
15
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
16
• 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 17
calculation.
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
18
• 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
19
• 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
20
Variables
• declaration – how to assign a type to a variable
21
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.
Examples:
int a, b, c;
int d = 3, e, f = 5;
byte g = 22;
double pi = 3.14159;
char ch = 'x';
23
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 24
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.
25
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.
26
Array Declaration
Array declaration involves:
type array-variable[];
or
type [] array-variable;
27
Array Creation
• After declaration, no array actually exists.
type array-variable[];
• This creates a new array to hold size elements of type type, which reference
will be kept in the variable array-variable.
28
Array Indexing
• Later we can refer to the elements of this array through their indexes:
• array-variable[index]
• The Java run-time system makes sure that all array indexes are in the correct
range, otherwise raises a run-time error.
29
Array Initialization
• Arrays can be initialized when they are declared:
• Note:
30
Multidimensional Arrays
• Multidimensional arrays are arrays of arrays:
3) initialization
31
Operators Types
• Java operators are used to build value expressions.
1) assignment
2) arithmetic
3) relational
4) logical
5) bitwise
32
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 ;
>> 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
35
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.
anArray[0] = 100;
System.out.println("value1 == value2");
36
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.
1) if
2) if-else
3) if-else-if
4) switch
39
Iteration Statements
1) while
2) do-while
3) for
40
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 flow
of a program.
41
Type Conversion
• Size Direction of Data Type
43
Type Conversion
44
Type Conversion
45
Type Casting
46
Simple Java Program
• A class to display a simple message:
class MyProgram
{
public static void main(String[] args)
{
System.out.println(“First Java program.");
}
}
47
What is an Object?
• Real world objects are things that have:
1) state
2) behavior
48
What is a Class?
49
Object Creation
• A variable is declared to refer to the objects of type/class String:
String s;
51
Class
52
Class Definition
A class contains a name, several variable declarations (instance variables)
and several method declarations.
All are called members of the class.
53
Example: Class Usage
class BoxDim {
double wid;
double hgt;
double dep;
}
class BoxDemo {
public static void main(String args[]) {
BoxDim box = new BoxDim();
double vol;
box.wid = 10;
box.hgt = 20;
box.dep = 15;
vol = box.wid * box.hgt * box.dep;
System.out.println ("Volume is " + vol);
}} 54
Constructor
• A constructor initializes the instance variables of an object.
• It is called immediately after the object is created but before the new
operator completes.
1) it is syntactically similar to a method
2) it has the same name as the name of its class
3) it is written without return type; the default return type of a class
• Constructor is in the same class
• When the class has no constructor, the default constructor automatically
initializes all its instance variables with zero. 55
Example: Constructor (BoxDemo.java)
class BoxConst {
double width;
double height;
double depth;
BoxConst() {
System.out.println("Constructing Box");
width = 10; height = 10; depth = 10;
}
double volume() {
return width * height * depth;
}
} 56
package myjava;
public class BoxDemo {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
BoxConst mybox1 = new BoxConst();
BoxConst mybox2 = new BoxConst();
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}}
57
Parameterized Constructor
class Box {
double width;
double height;
double depth;
double volume()
{
return width * height * depth;
}
}
ParamBoxDemo.java
58
Methods
General form of a method definition:
type name(parameter-list) {
… return value;
…
}
Components:
1) type - type of values returned by the method. If a method does not return any
value, its return type must be void.
2) name is the name of the method
3) parameter-list is a sequence of type-identifier lists separated by commas
4) return value indicates what value is returned by the method. 59
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 {
void volume() {
System.out.print("Volume is ");
}
60
Parameterized Method
• Parameters increase generality and applicability of a method:
61
Access Control: Data Hiding and Encapsulation
• 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
62
Access Modifiers: Public, Private, Protected
• Public: keyword applied to a class, makes it available/visible everywhere.
Applied to a method or variable, completely visible.
PublicClassBox.java
63
Access Modifiers: Public, Private, Protected
• Private fields or methods for a class only visible within that class. Private
members are not visible within subclasses, and are not inherited.
TestPrivate.java
• 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.
MyNewPackage.TestProtected.java
64
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
65
this Keyword
• Can be used by any object to refer to itself in any class method
• Typically used to
– Chain constructors
66
this Keyword
• Keyword this allows a method to refer to the object that invoked it.
• It can be used inside any method to refer to the current object:
Box(double width, double height, double depth) {
this.width = width;
this.height = height;
this.depth = depth;
}
67
68
Garbage Collection
• Garbage collection is a mechanism to remove objects from memory when
they are no longer needed.
1) The garbage collector keeps track of how many references an object has.
69
finalize( ) Method
• A constructor helps to initialize an object just after it has been created.
• In contrast, the finalize method is invoked just before the object is destroyed:
70
Method Overloading
• It is legal for a class to have two or more methods with the same name.
• However, Java has to be able to uniquely associate the invocation of a method
with its definition relying on the number and types of arguments.
• Therefore the same-named methods must be distinguished:
1) by the number of arguments, or
2) by the types of arguments
• Overloading and inheritance are two ways to implement polymorphism.
MethodOverload.java
71
Example: Overloading
class OverloadDemo {
void test() {
System.out.println("No parameters");
}
void test(int a) {
System.out.println("a: " + a);
}
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
double test(double a) {
System.out.println("double a: " + a);
return a*a;
}
}
72
Constructor Overloading
class Box {
double width, height, depth;
Box(double w, double h, double d) {
width = w; height = h; depth = d;
}
Box() {
width = -1; height = -1; depth = -1;
}
Box(double len) {
width = height = depth = len;
}
double volume() {
return width * height * depth;
}
}
ConstructorOverload.java 73
Parameter Passing
1) simple types
2) class types
75
Call by reference
• As the parameter hold the same address as the argument,
changes to the object inside the method do affect the
object used by the argument:
class CallByRef{
public static void main(String args[]) {
Test ob = new Test(15, 20);
System.out.print("ob.a and ob.b before call: “);
System.out.println(ob.a + " " + ob.b);
ob.meth(ob);
System.out.print("ob.a and ob.b after call: ");
System.out.println(ob.a + " " + ob.b);
} }
CallbyRef.java
76
Recursion
• A recursive method is a method that calls itself:
1) all method parameters and local variables are allocated on the stack
4) upon return, all parameters and variables are removed from the stack
77
Example: Recursion
class Factorial {
int fact(int n) {
if (n==1) return 1;
return fact(n-1) * n;
}
}
class Recursion {
public static void main(String args[]) {
Factorial f = new Factorial();
System.out.print("Factorial of 5 is ");
System.out.println(f.fact(5));
} }
factorialDemo.java
78
String Handling
• String is probably the most commonly used class in Java's class library. The
obvious reason for this is that strings are a very important part of
programming.
• The first thing to understand about strings is that every string you create is
actually an object of type String. Even string constants are actually String
objects.
• For example, in the statement
System.out.println("This is a String, too");
the string "This is a String, too" is a String constant
79
String Handling
“I like Java.”
80
• The String class contains several methods that you can use. Here are a few.
• You can obtain the length of a string by calling the length( ) method.
• You can obtain the character at a specified index within a string by calling
charAt( ). The general forms of these three methods are shown here:
StringDemo2.java
81
// Demonstrating some String methods.
class StringDemo2 {
public static void main(String args[]) {
String strOb1 = "First String";
String strOb2 = "Second String";
String strOb3 = strOb1;
System.out.println("Length of strOb1: " + strOb1.length());
System.out.println ("Char at index 3 in strOb1: " +
strOb1.charAt(3));
if (strOb1.equals(strOb2))
System.out.println("strOb1 == strOb2");
else
System.out.println("strOb1 != strOb2");
if (strOb1.equals(strOb3))
System.out.println("strOb1 == strOb3");
else
System.out.println("strOb1 != strOb3");
} }
output:
Length of strOb1: 12
Char at index 3 in strOb1: s
strOb1 != strOb2
strOb1 == strOb3 82