Professional Documents
Culture Documents
BASIC CONCEPTS
© Ganapathi Nayak K
1
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
© Ganapathi Nayak K
2
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
© Ganapathi Nayak K
3
Program Structure
Documentation Section
Package Statements
Import Statements
Interface Statements
Class Definitions
© Ganapathi Nayak K
4
Data Types and Variables
Java Keywords
© Ganapathi Nayak K
5
Data Types and Variables
© Ganapathi Nayak K
7
Data Types and Variables
Literals
A sequence of characters (digits, letters and other characters) that
represent constant values to be stored in variables.
Categories of literals
Integer Literals : decimal, binary (0B), octal (0) and hexadecimal (0x)
– Assign integer literal to byte or short – no error if within range
– Long literal end with L
Floating-Point Literals: Standard and Scientific notation
– Default is double precision (Optional D or d can be used)
– Float literal end with F or f
Boolean Literals: Values true and false (not same as 1 and 0)
Character Literals: Unicode character set
– Visible ASCII characters used within quotes (E.g., ‘a’, ‘6’)
– Others using escape sequences (E.g., ‘\n’, ‘\b’, ‘\”’)
String Literals: Enclose within double quotes
© Ganapathi Nayak K
8
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
© Ganapathi Nayak K
9
Data Types and Variables
Variables
Syntax: type identifier [= value][, identifier [=value]…];
Examples:
int a, b, c;
int d = 3, e, f = 5;
byte z = 10;
double pi = 3.14159;
float k = 3.56f;
char x = ‘x’;
Types of variables
Local variables
Instance variables
Class / Static variables
© Ganapathi Nayak K
10
Data Types and Variables
Local Variables
Declared in methods, constructors or blocks
Created when a method, constructor or block is entered and destroyed
when the method, constructor or block is exited
Visible only within the method, constructor or block
No default values; an initial value should be assigned before its first use
Access specifiers cannot be used
© Ganapathi Nayak K
11
Data Types and Variables
© Ganapathi Nayak K
12
Data Types and Variables
© Ganapathi Nayak K
13
Data Types and Variables
© Ganapathi Nayak K
14
Data Types and Variables
© Ganapathi Nayak K
15
Data Types and Variables
© Ganapathi Nayak K
16
Data Types and Variables
float Yes
double
© Ganapathi Nayak K
17
Data Types and Variables
byte
© Ganapathi Nayak K
18
Data Types and Variables
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)
© Ganapathi Nayak K
21
Arrays
© Ganapathi Nayak K
22
Arrays
One-Dimensional Arrays
Syntax: type array-var[];
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 [5];
Example 3:
int one [] = {1, 2, 3, 4, 5};
© Ganapathi Nayak K
23
Arrays
Two-Dimensional Arrays
Syntax: type array-var[][];
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}};
© Ganapathi Nayak K
24
Arrays
© Ganapathi Nayak K
25
Arrays
© Ganapathi Nayak K
26
Operators
© Ganapathi Nayak K
27
Operators
© Ganapathi Nayak K
28
Operators
Ternary Operator
Syntax: expression 1 ? expression 2 : expression 3;
© Ganapathi Nayak K
29
Operators
Operator Precedence
Highest
() [] • Note:
++ -- ~ ! 1. First row contains separators (and
* / % not operators), but they act as
operators in an expression.
+ -
>> >>> << 2. Within each row, all operators have
the same precedence.
> >= < <=
== != 3. Precedence can be changed using
parentheses.
&
|
&&
||
?:
= op=
Lowest
© Ganapathi Nayak K
30
Mathematical Functions
© Ganapathi Nayak K
31
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
Note:
From JDK 7 onwards, strings can be used as case labels in ‘switch’ statement
© Ganapathi Nayak K
32
Control Statements
Iteration statements
The while statement
Syntax: Same as in C and C++
© Ganapathi Nayak K
33
Control Statements
© Ganapathi Nayak K
34
Control Statements
© Ganapathi Nayak K
35
Control Statements
© Ganapathi Nayak K
36
Control Statements
catch
throw
throws
finally
© Ganapathi Nayak K
37
Class Fundamentals
© Ganapathi Nayak K
38
Class Fundamentals
© Ganapathi Nayak K
39
Class Fundamentals
© Ganapathi Nayak K
40
Class Fundamentals
© Ganapathi Nayak K
41
Class Fundamentals
© Ganapathi Nayak K
42
Class Fundamentals
© Ganapathi Nayak K
43
Class Fundamentals
Constructors
A method that
Initializes an object immediately upon creation
Has same name as class name
Has no return type, not even void
– implicit return type is type of the class
– returns the instance of the class
Can accept parameters (Parameterized constructors)
© Ganapathi Nayak K
44
Class Fundamentals
Constructors (Continued …)
Example
class Box {
double width, height, depth;
Box() {width = 10; height = 15; depth = 8;}
Box(double w, double h, double d)
{width = w; height = h; depth = d;}
double volume()
{ return width * height * depth; }
}
class BoxDemo {
public static void main(String args[]) {
Box myBox1 = new Box();
Box myBox2 = new Box(20, 12, 10);
System.out.println(“Volume of box 1 = ” + myBox1.volume());
System.out.println(“Volume of box 2 = ” + myBox2.volume());
}
}
© Ganapathi Nayak K
45
Class Fundamentals
© Ganapathi Nayak K
46
Class Fundamentals
© Ganapathi Nayak K
47
Class Fundamentals
Garbage Collection
C++ delete operator: dynamically allocated (using new operator) objects
manually released (recycled)
Java handles deallocation automatically using a technique called garbage
collection
Whenno references to an object exists (that object is assumed to be no longer
needed), the memory occupied by the object is reclaimed (at random)
Different Java run-time implementations will take varying approaches to garbage
collection
© Ganapathi Nayak K
48
Class Fundamentals
Method Overloading
Defining two or more methods in a class that share the same name, with
different parameter declarations
A type of Polymorphism – one interface, multiple methods
Overloaded methods must differ in the type and/or number of parameters
Invoking an overloaded method
– Java uses type and/or number of arguments for determining the required method
(and not the return type)
– Possibility of type promotion
In C, three versions of abs():
abs() for integer
fabs() for floating-point
labs() for long integer
In Java, abs() overloaded
© Ganapathi Nayak K
50
Overloading of Methods
Note: If the third method (and the corresponding method invocation) is not present,
we get an error for the last method invocation.
© Ganapathi Nayak K
51
Overloading of Methods
Overloading Constructors
Example:
Constructors
Box()
{ height = 0; width = 0; depth = 0; }
Box(double h, double w, double d) // for a cuboid
{ height = h; width = w; depth = d; }
Box(double len) // for a cube
{ height = width = depth = len; }
Invoke as
Box myBox1 = new Box();
Box myBox2 = new Box(10, 8, 6);
Box myBox3 = new Box(5);
© Ganapathi Nayak K
52
Passing Objects
© Ganapathi Nayak K
53
Returning Objects
© Ganapathi Nayak K
54
Recursion
© Ganapathi Nayak K
55
Access Control
Access specifiers
public : Can be accessed by any other code
» main() is declared as public
(should be accessible to Java run-time system)
private : Can be accessed by other members of its class
protected : Applies only when inheritance is used
© Ganapathi Nayak K
56
Access Control
© Ganapathi Nayak K
57
Access Control
© Ganapathi Nayak K
58
Access Control
© Ganapathi Nayak K
59
Access Control
© Ganapathi Nayak K
60
Access Control
final variable
Prevents the contents of the variable being modified
Should be initialized when it is declared
Variable is essentially a constant
Do not occupy memory on per-instance basis
Coding convention used: All uppercase identifiers
Can be initialized within a constructor (instance variable)
Examples:
final double INTEREST_RATE = 10
final int FILE_NEW = 1
© Ganapathi Nayak K
61
Array as an Object
Example:
class Length{
public static void main(String args[]) {
int a1[] = new int [10];
int a2[] = { 1, 2, 3, 4, 5 };
System.out.println (a1.length); // 10
System.out.println (a2.length); // 5
}
}
© Ganapathi Nayak K
62
Nested and Inner Classes
Nested Classes
Scope of a nested class is bounded by the scope of the enclosing class
Example: If B is defined within A, B does not exist independently of A
Nested class can access all members (including private) of the class in
which it is nested
© Ganapathi Nayak K
63
Nested and Inner Classes
Static:
Non-static (Inner):
– Can refer to them directly (similar to non-static members of the outer class)
© Ganapathi Nayak K
64
Nested and Inner Classes
© Ganapathi Nayak K
65
Nested and Inner Classes
© Ganapathi Nayak K
66
Nested and Inner Classes
© Ganapathi Nayak K
67
Nested and Inner Classes
© Ganapathi Nayak K
68
Command Line Arguments
© Ganapathi Nayak K
69
String Handling
String Class
A string is an object of type String
Defined in the package java.lang as ‘final’ (cannot be inherited)
Not an array of characters
Not terminated by NULL
Objects are immutable (cannot be altered)
Fixed length
Two peer classes StringBuffer and StringBuilder
Hold strings that can be modified after they are created
+ operator can be used for concatenating two or more strings
String s = “MIT” + “Manipal”;
System.out.println(“Value is ” + value);
© Ganapathi Nayak K
70
String Handling
© Ganapathi Nayak K
71
String Handling
Note: We can also create a string without using a constructor by directly assigning a value to it.
Example: String s7 = “Manipal”;
© Ganapathi Nayak K
72
String Handling
void getChars (int sourceStart, int sourceEnd, char target [], int targetStart)
byte [ ] getBytes ()
char [ ] toCharArray ()
String toLowerCase ()
String toUpperCase ()
© Ganapathi Nayak K
73
String Handling
© Ganapathi Nayak K
74
String Handling
boolean regionMatches (int startIndex, String str2, int str2StartIndex, int numChars)
boolean regionMatches (boolean ignoreCase, int startIndex,
String str2, int str2StartIndex, int numChars)
String [ ] split ( String regex, int limit )
Note: The “equals()” method compares the characters within the strings.
The “==” operator compares two object references to see whether
they refer to the same instance.
© Ganapathi Nayak K
75
String Handling
© Ganapathi Nayak K
76
String Handling
String trim()
© Ganapathi Nayak K
77
String Handling
int length ()
boolean isEmpty ()
String toString ()
© Ganapathi Nayak K
78
String Handling
© Ganapathi Nayak K
79
String Handling
© Ganapathi Nayak K
80
String Handling
© Ganapathi Nayak K
81
String Handling
StringBuffer Class
Strings that can be altered both in terms of length and content
StringBuffer constructors:
StringBuffer ()
© Ganapathi Nayak K
82
String Handling
int capacity ()
int length ()
StringBuffer reverse()
© Ganapathi Nayak K
83
String Handling
String toString()
void trimToSize()
© Ganapathi Nayak K
84
String Handling
StringBuffer insert (int index, char[] str, int offset, int len)
arg = boolean, char, char[], double, float, int, long, String, StringBuffer
© Ganapathi Nayak K
85
Wrapper Classes
Wrapper Classes
Contained in java.lang package
Used for wrapping primitive data into objects and vice versa
Immutable – a primitive data in stored in an object, cannot be modified
boolean Boolean
char Character
double Double
float Float
int Integer
long Long
byte Byte
short Short
© Ganapathi Nayak K
86
Wrapper Classes
© Ganapathi Nayak K
87
Wrapper Classes
© Ganapathi Nayak K
88
Wrapper Classes
© Ganapathi Nayak K
89
Wrapper Classes
© Ganapathi Nayak K
90
Wrapper Classes
© Ganapathi Nayak K
91
Autoboxing and Unboxing
Autoboxing
Automatic conversion of primitive type into corresponding wrapper class
object (boxed into wrapper class)
Occurs when an object is expected and primitive type is available
Uses valueOf() method to convert primitive to Object
Examples:
1. Integer iObject = 3;
2. public static void show (Integer iParam)
{
System.out.println (iParam);
}
In calling method:
show(3);
© Ganapathi Nayak K
92
Autoboxing and Unboxing
Unboxing
Automatic conversion of object into corresponding primitive type (unboxed
from wrapper class)
Occurs when an primitive type is expected and object is available
Uses intValue(), doubleValue() etc. to get primitive value from Object
Examples:
1. int n = iObject;
2. public static Integer show (Integer iParam)
{
System.out.println (iParam);
return iParam;
}
In calling method:
int result = show(3);
© Ganapathi Nayak K
93
Variable-Length Arguments
Varargs
New technique introduced in JDK 5
Earlier techniques:
Ifthe maximum number of arguments is small and known, create overloaded versions
of the method one for each way the method could be handled
– Example 1
Ifthe maximum number of arguments is large and unknown, put the arguments in an
array and pass the array to the method
– Example 2
© Ganapathi Nayak K
94
Variable-Length Arguments
Varargs (Continued …)
Example 1:
class OverLoad {
static void vaTest () { }
static void vaTest (int a) { }
static void vaTest (int a, int b) { }
© Ganapathi Nayak K
95
Variable-Length Arguments
Varargs (Continued …)
Example 2:
class PassArray {
static void vaTest (int v[]) {
System.out.print ("Number of args: " + v.length + “\nContents: ");
for (int x : v) System.out.print (x + " ");
System.out.println ();
}
© Ganapathi Nayak K
96
Variable-Length Arguments
Varargs (Continued …)
A variable-length argument is specified by three dots (…)
class VarArgs {
static void vaTest (int … v) {
System.out.print("Number of args: " + v.length + “\nContents: ");
for(int x : v) System.out.print (x + " ");
System.out.println();
}
© Ganapathi Nayak K
97
Variable-Length Arguments
Varargs (Continued …)
Normal parameters can be used with variable-length arguments
Normal parameters should precede variable-length arguments
There must be only one variable-length parameter
Examples:
void vaTest (int a, float b, char c, int … vals); // valid
void vaTest (int a, int … vals, float b, char c); // invalid
void vaTest (int a, int … v1, double … v2); // invalid
© Ganapathi Nayak K
98
Variable-Length Arguments
Varargs (Continued …)
Varargs methods can be overloaded
class VarArgs {
static void vaTest (int ... v) { }
static void vaTest (boolean ... v) { }
static void vaTest (double ... v) { }
© Ganapathi Nayak K
99
Variable-Length Arguments
Varargs (Continued …)
Overloaded Varargs methods can lead to ambiguity
Case 1:
class VarArgs {
static void vaTest (int ... v) { }
static void vaTest (boolean ... v) { }
© Ganapathi Nayak K
100
Variable-Length Arguments
Varargs (Continued …)
Overloaded Varargs methods can lead to ambiguity
Case 2:
class VarArgs {
static void vaTest (int ... v) { }
static void vaTest (int) { }
© Ganapathi Nayak K
101
Inheritance
Meaning of inheritance
Mechanism in which one object acquires properties of another object
Create new classes that are built upon existing (parent) class
Methods and fields of parent class can be reused
New methods and fields can be added
© Ganapathi Nayak K
102
Inheritance
© Ganapathi Nayak K
103
Inheritance
Keyword super
Used in a subclass to refer to its immediate superclass
Form 1 (Example 1)
To call superclass constructors
Super must always be the first statement inside a subclass’ constructor
Syntax: super(arg-list);
Form 2 (Example 2)
To access members of superclass hidden by subclass
Syntax: super.member
Member can be either a method or an instance variable
© Ganapathi Nayak K
105
Inheritance
© Ganapathi Nayak K
106
Inheritance
© Ganapathi Nayak K
107
Inheritance
© Ganapathi Nayak K
108
Inheritance
Multilevel hierarchy
Multiple levels of inheritance
Class A → Class B → Class C …
Example:
class A {
// Body of class A
}
class B extends A {
// Body of class B
}
class C extends B {
// Body of class C
}
© Ganapathi Nayak K
109
Inheritance
© Ganapathi Nayak K
110
Inheritance
Method overriding
When a subclass method has same name as a superclass method
If type of signatures (number and data type) are same (Example 1)
– Method in the subclass overrides the method in superclass
– When called, subclass method is used (superclass method is hidden)
If type of signatures (number and data type) are not same (Example 2)
– Two methods are overloaded
© Ganapathi Nayak K
111
Inheritance
Output: In B: 10
© Ganapathi Nayak K
112
Inheritance
Output: In A: 10
In B: 10
© Ganapathi Nayak K
113
Inheritance
Output: In A: 10
In B: MCA
© Ganapathi Nayak K
114
Inheritance
class A { }
class B extends A { }
In main(): A obj = new B(); // upcasting
© Ganapathi Nayak K
115
Inheritance
© Ganapathi Nayak K
116
Inheritance
class BankTest {
public static void main(String args[]) {
Bank b1=new Bank1();
Bank b2=new Bank2();
System.out.println (“Rate of interest”);
System.out.println (“Bank 1: "+ b1.getRate());
System.out.println (“Bank 2: "+ b2.getRate());
}
}
© Ganapathi Nayak K
117
Inheritance
© Ganapathi Nayak K
118
Inheritance
Abstract classes
Abstract class is a class that cannot be instantiated
Superclass declares the structure of a given abstraction without providing a
complete implementation of every method
Definesa generalized form that will be shared by all its subclasses, leaving it to each
subclass to fill in the details
© Ganapathi Nayak K
119
Inheritance
© Ganapathi Nayak K
120
Inheritance
© Ganapathi Nayak K
121
Inheritance
Run-time polymorphism
Not possible to instantiate objects of Abstract classes; but, object
references can be created
Run-time polymorphism implemented through the use of superclass
references
Possible to create a reference to an abstract class so that it can be used to
point to a subclass object
© Ganapathi Nayak K
122
Inheritance
class A {
final void meth() {
System.out.println ("This is a final method.");
}
}
class B extends A {
void meth() { // ERROR! Can't override.
System.out.println ("Illegal");
}
}
© Ganapathi Nayak K
123
Inheritance
final class A {
//…
}
class B extends A { // ERROR: Cannot inherit from final A
//…
}
© Ganapathi Nayak K
124
Inheritance
© Ganapathi Nayak K
125
Packages
What is a package ?
Container for classes
Classes with same name – possible in different packages
Classes in a package can be imported into required programs
Both a naming and visibility control mechanism
We can define classes inside a package that are not accessible outside that package
Wecan also define class members that are only exposed to other members of the
same package
© Ganapathi Nayak K
126
Packages
Defining a package
Include package statement as the first one in a Java source file
Any class declared within that file belongs to that package
Package statement defines a name space in which classes are stored
Absence of package statement puts class names in default package (without any
name)
Usage:
Syntax: package package-name;
Example: package myPackage;
Storing
a package: Store the package in a folder with the same name as package
name (case is significant)
© Ganapathi Nayak K
127
Packages
© Ganapathi Nayak K
128
Packages
package mypack;
class Balance {
String name; double bal;
Balance(String n, double b) { name = n; bal = b; }
void show() { System.out.println (name + " " + bal); }
}
class AccountBalance {
public static void main(String args[]) {
Balance current = new Balance ("Herbert Schildt", 1243.78);
current.show();
}
}
© Ganapathi Nayak K
129
Packages
import mypack.*;
class AccountBalance { // In the parent folder of mypack
public static void main(String args[]) {
Balance current = new Balance ("Herbert Schildt", 1243.78);
current.show();
}
}
© Ganapathi Nayak K
130
Packages
© Ganapathi Nayak K
131
Packages
Access Protection
Java provides four categories of visibility for class members
Subclasses in the same package
Non-subclasses in the same package
Subclasses in different packages
Classes that are neither in the same package nor subclasses
Access specifiers used
public: can be accessed anywhere
private: can’t be seen outside of its class
protected: can be seen outside the current package only to direct subclasses of that
class
(default
(package-private): visible to subclasses as well as other classes in the same
package)
Note: When a class is public, it must be the only public class in the file and the file
must have the same name as the class
© Ganapathi Nayak K
132
Packages
No
Private Protected Public
Modifier
© Ganapathi Nayak K
133
Packages
Importing Packages
A class from another package can be accessed using 2 methods
By specifying the fully qualified class name
Using import statement
The import statement is used immediately after package statement (if it
exists) and before any class definitions
Syntax: import pkg1[.pkg2].(classname|*);
Examples: import java.util.Date;
import java.lang.*; // basic language functions (default)
Fully qualified class name
import java.util.*;
class myDate extends Date { …}
OR
class myDate extends java.util.Date { … }
© Ganapathi Nayak K
134
Interfaces
Meaning of Interface
Java does not support multiple inheritance
class A extends B extends C { …} is not permitted
Interface: A kind of class – with the following differences from a class
Defines only abstract methods and final fields.
Does not specify any code to implement these methods
Data fields contain only constants.
Itis the responsibility of the class that implements an interface to define the code for
implementing these methods.
Syntax:
interface InterfaceName
{
variables declaration;
methods declaration;
}
Designed to support dynamic method resolution at run time
© Ganapathi Nayak K
135
Interfaces
Implementing an Interface
Syntax:
class classname extends superclass implements interface[,interface…] {
// class body
}
Rules:
Methods that implement an interface must be declared public
Typesignatures of the implementing method must match exactly the type signature
specified in the interface definition
© Ganapathi Nayak K
136
Interfaces
© Ganapathi Nayak K
137
Interfaces
Extending Interfaces
Syntax:
interface name2 extends name1
{
// body of name2
}
© Ganapathi Nayak K
138
Interfaces
© Ganapathi Nayak K
139
Interfaces
© Ganapathi Nayak K
140
The End
© Ganapathi Nayak K
141