Introduction To Core Java (At A Glance)
Introduction To Core Java (At A Glance)
BT-GenIUS | Telecom1
Tata Consultancy Services
Anshu Katyal
Saikat Das
1
Java Features
Full Object Oriented, Strictly & Strongly Typed Language
Abstraction
it provides a mechanism using which we can hide the details of
implementation.
A good abstraction is the one that emphasizes details that are
Inheritance
• Inheritance is a mechanism to reuse code
Polymorphism
Polymorphism means, behaving differently at different time
3
Hello WORLD!!!
Hello Class Program
public class Hello
{
public static void main(String argv[])
{
System.out.println(“Hello World!!!”);
System.exit(0);
}
}
The System.exit method is used to return value back to
OS
System.out.println is a print statement.(Java.lang Package)
4
Compile/Execute
The file name should be same as class name
Class is same as an Object. Object is an instance of a Class.
javac <filename> compiles the java code File name has a .java
extension eg. javac Hello.java
It produces a class file (contains java byte code for Java Virtual
Machines JVM). Eg. Hello.class
java <filename without ‘.class’> executes the program e.g. java Hello
<arguments if any>
5
Other Utilities
javap -package java.lang.Integer lists the methods and
variables that are available in the package
java.lang.Integer.
javap -c <classname>. Produces a byte code of your
program. Bytecode is written in Java Virtual Machine.
Javadoc <filename> produces a HTML file which is a
documentation of your program. One can see the
documentation using a browser.
6
Program Structure/Environment
Java
Is interpreted (C/C++ are Compiled)
No Preprocessor
No #define, #ifdef, #include, ...
Main method (for Java applications)
Embedded in a Class
public class Xyz
{
public static void main (String args[]) {
…
}
}
Each class can define its own main method
Program’s starting point depends on how the interpreter is invoked.
$ java Xyz
7
Names and Types
variables
Functions or Methods
Classes & Objects
Types of variables(8) - int, float, double, boolean,
long, byte, char,
Arrays (unlike C or C++, in Java arrays are treated as
an Object.)
Life time of a variable
8
Types of Methods and
Variables
Instance variable.
Static variables and Static Methods
public, private and protected variables and methods
Constructor Method
Automatic Variables
9
Import
Import Statement
Without an import statement
java.util.Calendar c1;
After the import statement
import java.util.Calendar;
...
Calendar c1;
Saves typing
10
Command Line Arguments
Command Line Args are passed to main method
public class Echo
{
public static void main(String argv[])
{
for (int i=0; i<argv.length; i++)
System.out.print(argv[i] + ” ”);
System.out.print("\n");
System.exit(0);
}
}
main has a return type of void (not int)
The System.exit method is used to return value back to OS
The length property is used to return array size
11
Lexical Issues
Whitespace ( space, tab, newline)
Identifiers(AvgTemp , _count, $a4, 2count)
Literals(100 98.6 ‘X’ “This is a test”)
Comments(//, /*….*/, /** ….*/)
Separators (“[ ]”,”( )”,”{ }”,” ; ”,” . ”,” , ”)
Keywords (49)
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
12
Data Types
Integers
long (64) –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
Int( 32) –2,147,483,648 to 2,147,483,647
short (16) –32,768 to 32,767
byte (8) –128 to 127
Floating Point
double (64) 4.9e–324 to 1.8e+308
float (32) 1.4e−045 to 3.4e+038
Characters(Unicode)
char (16) 10 to 255 ( 0 to 127 are same as ASCII)
Boolean
true or false
13
•Scope & Lifetime of a Variable
•Type Conversion and Casting
Java’s Automatic Conversions
Casting Incompatible Types
Automatic Type Promotion in Expressions
The Type Promotion Rules
14
Arithmetic Operators Bitwise Operators
Operator Result
+ Addition Operator Result
– Subtraction (also unary ~ Bitwise unary NOT
minus) & Bitwise AND
* Multiplication | Bitwise OR
/ Division ^ Bitwise exclusive OR
% Modulus >> Shift right
++ Increment(Pre & Post) >>> Shift right zero fill
+= Addition assignment << Shift left
–= Subtraction assignment &= Bitwise AND assignment
*= Multiplication assignment |= Bitwise OR assignment
/= Division assignment
%= Modulus assignment
–– Decrement
15
Relational Operators Boolean Logical Operators
Operator Result
== Equal to Operator Result
!= Not equal to & Logical AND
> Greater than | Logical OR
< Less than ^ Logical XOR (exclusive OR)
>= Greater than or equal to || Short-circuit OR
<= Less than or equal to && Short-circuit AND
! Logical unary NOT
&= AND assignment
|= OR assignment
^= XOR assignment
== Equal to
!= Not equal to
?: Ternary if-then-else
16
Operator Precedence
Highest
() [] .
++ –– ~ !
* / %
+ –
>> >>> <<
> >= < <=
== !=
&
^
|
&&
||
?:
= op=
Lowest
17
Expressions
Arithmetic expressions in Java are similar to C/C++
Example
int i = 5 + 12 / 5 - 10 % 3
= 5 + (12 / 5) - (10 % 3)
=5+2-1
=6
Operators cannot be overloaded in Java
Integer division vs. floating point division
18
Control Statements
If-else statement
Switch
break & continue
return
goto
Iteration Statements
for statement
while
Do while
19
For Statement
for (i=0, j=0; (i<10) && (j<20); i++, j++)
{
…
}
Comma separation is Allowed in initialization and test sections
Makes Java syntactically closer to C
Variable declaration
variables can be declared within for statement, but can’t be
overloaded
int i;
for (int i=0; i<n; i++) { … } // Not valid in Java
declaration is all or nothing
20
If, While, Do While, Switch
These are (essentially) the same as C/C++
if (x != 2)
y=3; do {
System.out.println ("X=" + x);
if (x == 3) x *= 2;
y=7; } while(x<100);
else
y=8;
char c;
if (x >= 4) { ...
y=2; switch (c) {
k=3;
}
case 'Q':
return;
while (x<100) { case 'E':
System.out.println process_edit();
("X=" + x); break;
x *= 2;
} default:
System.out.println ("Error");
}
21
Classes
A class is a template for an object.
Objects
Instances of classes are called objects
Object variables store the address of an object
Different from primitive variables (which store the actual value)
Primitive Data Type example
int i=3;
int j=i;
i=2;
Object Example
java.awt.Button b1 = new java.awt.Button("OK");
java.awt.Button b2 = b1;
b2.setLabel("Cancel"); // Change is visible via b1 also
b1 = new java.awt.Button("Cancel")
No explicit dereferencing (i.e., no &, * or -> operators)
No pointers
null = "Absence of reference" = a variable not pointing to an object 22
Name Space
No globals
variables, functions, methods, constants
Scope
Every variable, function, method, constant belongs to a Class
Every class is part of a Package
Fully qualified name of variable or method
<package>.<class>.<member>
Packages translate to directories in the “class path”
A package name can contain multiple components
java.lang.String.substring()
COM.Ora.writers.david.widgets.Barchart.display()
- This class would be in the directory
“XXX/COM/Ora/writers/david/widgets”, where XXX is a
directory in the “class path”
23
Package; Import
A package is a collection of related classes and interfaces that provides
access protection and namespace management.
Packages are created using the package keyword
Package Statement
Specifies the name of the package to which a class belongs
package Simple_IO; // Must be the first statement
public class Reader {
…
}
Optional
Import Statement
Without an import statement
java.util.Calendar c1;
After the import statement
import java.util.Calendar;
...
Calendar c1;
Saves typing
import java.util.*; // Imports all classes
24
Access Rules
Packages are accessible
If associated files and directories exist and have read permission
Classes and interfaces of a package are accessible
From any other class in the same package
Public classes are visible from other packages
Members of a class (C) are accessible
[Default] From any class in the same package
Private members are accessible only from C
Protected members are accessible from C and subclasses of C
Public members are accessible from any class that can access C
Local variables declared within a method
Are not accessible outside the local scope
25
Access Control
Private Default Protected Public
Class
Sub class,
same package
Other class,
same package
27
Objects are handled by Reference
Objects in Java are handled "by reference"
Comparison is by reference
Following is true if b1, b2 point to the same object
if (b1 == b2) { … }
if (b1.equals(b2)) { … } // member by member comparison
Assignment copies the reference
b1 = b2;
b1.clone(b2); // Convention for copying an object
Parameters passing is always by value
The value is always copied into the method
For objects, the reference is copied (passed by value)
The object itself is not copied
It is possible to change the original object via the reference
28
Parameter Passing Example
class ParameterPassingExample {
static public void main (String[] args) {
int ai = 99;
StringBuffer as1 = new StringBuffer("Hello");
StringBuffer as2 = new StringBuffer("World");
System.out.println ("Before Call: " + show(ai, as1, as2)); Before Call : i= 99 s1='Hello'; s2='World'
set(ai,as1,as2); Before Change: i= 99 s1='Hello'; s2='World'
System.out.println ("After Call: " + show(ai, as1, as2)); After Change : i= 1 s1='Hello, World'; s2='Hello, Wo
After Call : i= 99 s1='Hello, World'; s2='World'
}
static void set (int fi, StringBuffer fs1, StringBuffer fs2) {
System.out.println ("Before Change: " + show(fi, fs1, fs2));
fi=1;
fs1.append(", World");
fs2 = new StringBuffer("Hello, World");
System.out.println ("After Change: " + show(fi, fs1, fs2));
}
static String show (int i, StringBuffer s1, StringBuffer s2) {
return "i=" + i + "s1='" + s1 + "'; s2='" + s2 + "'";
}
}
29
Constants
Constants
Value of variable is not allowed to change after initialization
Example
final double PI = 3.14159;
Initialization can be done after declaration
final boolean debug_mode;
…
if (x<20) debug_mode = true; // Legal
else debug_mode = false; // Legal
…
debug_mode = false; // Error is caught at compile time
Value of variable cannot change; value of object can change
final Button p = new Button("OK");
p = new Button ("OK"); // Illegal. P cannot point to
// a different object
p.setLabel ("Cancel"); // Legal.
30
Input/Output
java.io.OutputStream - A byte output stream
System.out (C:stdout; C++:cout)
System.err (C:stderr; C++:cerr)
Convenience methods: print, println
send characters to output streams
31
Echo.java
A version of Echo that reads in data from System.in
import java.io.*;
class Echo {
public static void main (String[] args) throws IOException
{
BufferedReader stdin = new BufferedReader
(new InputStreamReader(System.in));
String message;
32
THANK YOU
QUESTION
???
33
BT-GenIUS | Telecom1
Tata Consultancy Services
Saikat Das
Anshu Katyal
34
Array Declaration
Array Declaration
Example
int[] scores = new int[10];
Variable type is "int[]"
Elements range from scores[0] … scores[9]
Automatic bounds checking
Each array has a public constant, length
scores.length
- this evaluates to 10
Alternate declarations
float[] prices;
float prices[];
35
Arrays
Initializer lists can be specified
int[] units = { 147, 323, 89 };
No new operator used
No size specified
[C] 79 87 94 82 67 98 87 81 74 91
[Java]
79 87 94 82 67 98 87 81 74 91
0,0 0,1 0,2 0,3 0,4 1,0 1,1 1,2 1,3 1,4 37
Multi-Dimensional Arrays
Each row (inner array) is independent of others
Can reassign part of the array
my_array[1] = new byte[22];
Each row can have a different size than other rows
int[][] table = { {28, 84, 47, 72}, {69, 26}, {91, 40, 28},
{42, 34, 37}, {13, 26, 57, 35} };
Can have partial declarations
38
Class Example
Declaration
import java.lang.Math;
public class Circle {
public int x, y, r; // (x,y) of Center; radius
public double circumference () { return 2 * Math.PI * r; }
public double area () { return Math.PI * r * r; }
}
Use
Circle c;
c = new Circle();
c.r = 2;
double a = c.area();
39
Constructors
Constructors
Perform initialization of objects
Declaration
public class Circle {
private int x, y, r;
public Circle (int ar) { this.x=0; y=0; r=ar; }
… // Note the optional use of "this" above
}
Use
Circle c = new Circle (2);
double a = c.area();
Can have more than one constructor
public Circle (int ax, int ay, int ar) { x=ax; y=ay; r=ar; }
Can overload the default constructor
public Circle () { x=0; y=0; r=1; }
What if a class does not define ANY constructors?
What if a class defines constructors, but not one with NO arguments?
40
Constructors
One constructor can call another (unlike C++)
Uses "this"
public Circle (int ax, int ay, int ar) { x=ax; y=ay; r=ar; }
public Circle (int ar) { this(0, 0, ar); }
Call to an alternate constructor MUST appear first
Before any other statements
Before variable declarations
41
Class Variables
Class variables
import java.lang.Math;
public class Circle {
static int numCircle = 0;
private int x=0, y=0, r=1; // Notice the initializers
public Circle() { num_circles++; }
public Circle (int ar) { this(); r=ar; }
public double circumference () { return 2 * Math.PI * r; }
public double area () { return Math.PI * r * r; }
}
Referencing Class variables
From within the class: this.numCircle (or just numCircle)
this.getNumCircle();
From outside the class
43
(Lack of) Globals
Java does not allow global variables
Class variables can substitute for global variables
Advantage: no possibility of a collision in variable names
Example declaration in java.lang.Math:
44
Inheritance
Need a class with ability to draw Circles
Approach 1 (Not ideal)
public class GraphicCircle {
// Keep an instance var. to keep circle stuff
public Circle c;
// Delegate functionality to c
public double area() { return c.area(); }
public double circumference () {return c.circumference();}
…
45
Inheritance
Approach 2: Inheritance
A "GraphicCircle" isa (more specific version of) "Circle"
public class GraphicCircle extends Circle {
// Only need the 'additional' things
Color outline, fill;
public void draw (Graphics page) { … }
}
Terms and Concepts
Superclass, base class, parent class
Circle GraphicCircle
GraphicCircle
46
Inheritance
GraphicCircle inherits all variables and methods
GraphicCircle gc = new GraphicCircle ();
gc.draw(); // Can invoke GraphicCircle methods
gc.x = 5; // Can access Circle fields
a = gc.area(); // Can invoke Circle methods
GraphicCircle objects are also Circle objects
Circle c;
c = gc; // Assignment is legal
a = c.area(); // Code can treat c as any other Circle
c.draw(); // Illegal (draw is defined in GraphicCircle)
47
Class Hierarchy
All classes (except one) have a single superclass
No multiple inheritance
Object is the default superclass
Number Integer
Object Float
Boolean
String Byte 48
Constructor Chaining
A subclass invokes a superclass constructor
Explicitly - First line is a call to the superclass constructor
class GraphicCircle {
…
public GraphicCircle (int r, Color o, Color f) {
super(r); // Must be first line
this.outline = o;
this.fill = f;
}
Implicitly
If first line of constructor is not a call to a constructor, super() is automatically
invoked
- What if supertype doesn't define a constructor with no arguments?
- What if first line is a call to another constructor of the form this(…)?
Note: Body of supertype constructor executes first (Like C++)!
49
Overriding Methods
Subclass can redefine method of superclass
class Circle { …
public void reset () { x=0; y=0; r=1; }
}
class GraphicCircle { …
public void reset () {
x=0; y=0; r=1;
fill = Color.getColor ("black");
}
}
Subclass method can call superclass method
class GraphicCircle { …
public void reset () {
super.reset();
fill = Color.getColor("black");
}
}
50
Polymorphism; Final Modifier
Actual method to call is determined at runtime
Depends on actual object’s type (not variable type)
Circle[] c[2];
c[0] = new Circle();
c[1] = new GraphicsCircle();
for (int i=0; i<2; i++)
c[i].reset();
C++ requires virtual keyword to implement polymorphism
C++ default (without keyword): resolution is done at compile time
class Circle { …
public final void reset () { x=0; y=0; r=1; }
}
class GraphicCircle { …
public void reset () { } // No longer valid!
} 51
Finalize Methods
Finalize: Similar to C++ destructor
A place to clean up an object before memory is deallocated
Invoked before garbage collection
Typically used for closing files, releasing resources, etc.
public class FileOutputStream extends OutputStream {
… // From java.io.FileOutputStream
protected void finalize() throws IOException {
if (fd != null) close(); // Closes file descriptor
}
}
Not very common in Java (compared to C++)
Most cleanup is done automatically by the garbage collector
53
Visibility Modifiers
Public, Private, Protected, Package
public class Circle { // With mixed visibility
public int x; // Public visibility
protected int y; // Protected visibility
int r; // Package visibility (default)
private int numCircle; // Private visibility
int area() { … }
}
Package visibility is default
classes in same package are friend-ly to each other
54
Visibility Modifier Guidelines
Public
Use this for methods, constants that are part of the public API
Most variables should not be public
Protected
For members that might be useful to subclasses (e.g. Circle’s
x,y,r)
But not for public use
Package
For things that “cooperating classes” need access to
Private
Fields and methods that should be hidden from everyone else
55
Circle Class
public class Circle {
protected int x=0, y=0, r=1;
private static int numCircle=0; // No one has access
/* Constructors */
public Circle () { numCircle++; }
public Circle (int ar) { this(); r=ar; }
Class
Cannot be instantiated
57
Abstract Class Example
public abstract class Shape {
public abstract double area(); // Note: no definition
public abstract double circumference();
}
public class Circle extends Shape {
protected int x, y, r;
public Circle(int ar) { r=ar; }
public double area() { return Math.PI * r * r; }
public double circumference() { return 2 * Math.PI * r; }
}
public class Rectangle extends Shape {
protected int x, y, w, h;
public Rectangle (int aw, int ah) { w=aw; h=ah; }
public double area() { return w * h; }
public double circumference() { return 2 * (w + h); }
}
58
Abstract Class Example
Example usage
public static void main () { …
Shape[] shapes = new Shape[3];
shapes[0] = new Circle(2);
shapes[1] = new Rectangle (3,4);
shapes[2] = new Rectangle (2,3);
…
double total_area = 0;
for (int i=0; i<shapes.length; i++)
total_area += shapes[i].area();
}
Subclasses of Shape can be assigned to an array of Shape
Area() method can be invoked on any kind of Shape
Declared as an abstract method in Shape
59
Inheritance
Example Hierarchy
Shape - abstract area(), circumference()
Circle - area(), circumference()
GraphicCircle - draw()
In C++
Multiple Inheritance
Shape
GraphicCircle GraphicRectangle
60
Interface
Java
No multiple inheritance
Java's solution: interface
public interface Drawable {
public void setColor (Color c);
public void setPosition (int x, int y);
public void draw (Graphics dw);
}
Interface
Looks like an abstract class; simulates some Multi-Inheritance
But uses keyword interface instead of abstract and class
61
Interface
public class GraphicRectangle
extends Rectangle implements Drawable
{
private Color c;
public GraphicRectangle (int w, int h) { super(w,h); }
62
Using Interfaces
Shape[] shapes = new Shape[3];
Drawable[] drawables = new Drawable[3];
double total_area = 0;
for (int i=0; i<shapes.length; i++) {
total_area += shapes[i].area();
drawables[i].setPosition(i*10, i*10);
drawables[i].draw(gc); // Assume gc is defined somewhere
} 63
Multiple Interfaces
Each user defined class
Extends exactly one other class
Implements 0, 1, or more interface
public class GraphicRectangle
extends Rectangle
implements Drawable, java.lang.Cloneable,
java.lang.Serializable
{
...
}
Interface
Provides a way to simulate multiple inheritance
Every class that implements an interface MUST define all methods of that
interface
64
Interface Hierarchy
Interfaces can be subtypes of other interfaces
Results in an interface hierarchy
Directed, Acyclic Graph (not a tree, like the class hierarchy)
public interface Transformable
extends Scalable, Rotateable, Reflectable { ... }
public interface GraphicObject
extends Drawable, Transformable { ... }
public class Shape implements GraphicObject { ... }
65
Case Study on Inheritance
Case Study
Solution: Lewis: ../chap08/applications/Accounts2.java
Bank_Account
Generic account with ability to make deposits and withdrawals
Savings_Account
A kind of Bank_Account
Collects interest
Bank_Account
Bonus_Saver_Account
A kind of Savings_Account
Checking_Account
A kind of Bank_Account
Bonus_Saver_Account
Has overdraft protection
66
Define Class Hierarchy
public class Bank_Account {
...
}
public class Savings_Account extends Bank_Account {
...
}
public class Bonus_Saver_Account extends Savings_Account {
...
}
public class Checking_Account extends Bank_Account {
...
}
67
Define Methods
public class Bank_Account {
public Bank_Account(int account_num,double init_bal) {...}
public void deposit (double amount) { ... }
public void withdrawal (double amount) { ... }
}
69
Define Methods (Details, cont.)
public class Savings_Account extends Bank_Account {
protected double rate;
70
Define Methods (Details, cont.)
public class Checking_Account extends Bank_Account {
private Savings_Account overdraft;
71
THANK YOU
QUESTION
???
72