Core Java: - Sharad Ballepu
Core Java: - Sharad Ballepu
- Sharad Ballepu
sharadballepu@sharmanj.com
www.sharmanj.com
Core Java
Agenda
Introduction
Access Modifiers
Operators
Flow Control
Arrays and Strings
OOPS Explored
Exceptions
Garbage Collection
Collections
Threads
Demo
2
Programming language
Another programming language using which we can develop applets,
standalone applications, web applications and enterprise applications.
Platform Independent
A Java program written and compiled on one machine can be
executed on any other machine (irrespective of the operating system)
Object Oriented
Complies to object oriented programming concepts. Your program is
not object oriented unless you code that way
.java file
Java
Compiler
.class
file
Mac
Microsoft
UNIX
4
package com.sharadballepu.test;
public class HelloWorld
{
public static void main(String[] args)
{
System.out.println(Hello World);
}
}
package com.sharadballepu.test;
public class HelloWorld
{
public static void main(String[] args)
{
HelloWorld hw = new HelloWorld();
hw.display(args[0]);
}
public void display(String userName)
{
System.out.println(Hello + userName);
}
}
Compile the program: javac HelloWorld.java
Execute the program: java HelloWorld Sharad
Output: Hello Sharad
package com.sharadballepu.test;
public class HelloWorld
{
String userName;
public static void main(String[] args)
{
HelloWorld hw = new HelloWorld();
hw.userName = args[0];
}
public void display()
{
System.out.println(Hello + userName);
}
}
Compile the program: javac HelloWorld.java
Execute the program: java HelloWorld Sharad
Output: Hello Sharad
abstract
boolean
break
byte
case
catch
char
class
const
continue
default
do
double
else
extends
final
finally
float
for
goto
if
implements
import
instanceof
int
interface
long
native
new
package
private
protected
public
return
short
static
strictfp
super
switch
synchronized
this
throw
throws
transient
try
void
volatile
while
assert
x = 10
y = new A()
method2()
method1()
C
main()
Stack
Heap
10
Class
Object
Abstraction
Encapsulation
Inheritance
Polymorphism
An instance of a Class
Data type
Max Value
Literal Values
byte
-27
27 1
123
short
-215
215 1
1234
int
-231
231 1
long
-263
263 1
123456
float
1.0
double
123.86
char
216 1
a, \n
boolean
true, false
General rule:
Min value = 2(bits 1)
Max value = 2(bits-1) 1
(where 1 byte = 8 bits)
12
Java Modifiers
Modifier
Class
Class
Variables
Methods
public
private
protected
default
final
abstract
strictfp
transient
synchronized
native
volatile
static
Method
Variables
13
Modifiers Class
public
default
final
abstract
strictfp
Class can be accessed from any other class present in any package
Class can be accessed only from within the same package. Classes outside the
package in which the class is defined cannot access this class
Conforms that all methods in the class will conform to IEEE standard rules for
floating points
14
public
private
protected
default
final
transient
volatile
static
Attribute can be accessed from any other class present in any package
Attribute can be accessed from only within the class
Attribute can be accessed from all classes in the same package and subclasses.
Attribute can be accessed only from within the same package.
This value of the attribute cannot be changed, can assign only 1 value
The attribute value cannot be serialized
Thread always reconciles its own copy of attribute with master.
Only one value of the attribute per class
15
Modifiers Methods
public
private
protected
default
final
abstract
strictfp
synchronized
native
static
Method can be accessed from any other class present in any package
16
Operators - Types
Definition:
An operator performs a particular operation on the operands it is applied
on
Types of operators
Assignment Operators
Arithmetic Operators
Unary Operators
Equality Operators
Relational Operators
Conditional Operators
instaceof Operator
Bitwise Operators
Shift Operators
17
Assignment Operator
Operator
Description
Example
Assignment
int i = 10;
int j = i;
Arithmetic Operators
Operator
Description
Example
Addition
Subtraction
int i = 9 4;
Multiplication
int i = 8 * 6;
Division
int i = 10 / 2;
Remainder
int i = 10 % 3;
18
Unary Operators
Operator
Description
Example
Unary plus
int i = +1;
Unary minus
int i = -1;
++
Increment
int j = i++;
--
Decrement
int j = i--;
Logical Not
boolean j = !true;
Equality Operators
Operator
Description
Example
==
Equality
If (i==1)
!=
Non equality
If (i != 4)
19
Relational Operators
Operator
Description
Example
>
Greater than
if ( x > 4)
<
Less than
if ( x < 4)
>=
if ( x >= 4)
<=
if ( x <= 4)
Conditional Operators
Operator
Description
Example
&&
Conditional and
If (a == 4 && b == 5)
||
Conditional or
If (a == 4 || b == 5)
20
instanceof Operator
Operator
Description
Example
instanceof
Instamce of
Bitwise Operators
Operator
Description
Example
&
Bitwise and
Bitwise or
Bitwise ex-or
Reverse
~011 = -10
Shift Operators
Operator
Description
Example
>>
Right shift
<<
Left Shift
>>>
21
if-else
Syntax
Example
if (<condition-1>) {
// logic for true condition-1 goes
here
} else if (<condition-2>) {
// logic for true condition-2 goes
here
} else {
// if no condition is met, control
comes here
}
int a = 10;
if (a < 10 ) {
System.out.println(Less than 10);
} else if (a > 10) {
System.out.pritln(Greater than 10);
} else {
System.out.println(Equal to 10);
}
Result: Equal to 10s
22
switch
Syntax
Example
switch (<value>) {
case <a>:
// stmt-1
break;
case <b>:
//stmt-2
break;
default:
int a = 10;
switch (a) {
case 1:
System.out.println(1);
break;
case 10:
System.out.println(10);
break;
default:
System.out.println(None);
//stmt-3
Result: 10
23
do-while
Syntax
Example
do {
// stmt-1
} while (<condition>);
int i = 0;
do {
System.out.println(In do); i++;
} while ( i < 10);
Result: Prints In do 11 times
while
Syntax
Example
while (<condition>) {
//stmt
}
int i = 0;
while ( i < 10 ) {
System.out.println(In while); i++;
}
Result: In while 10 times
24
for
Syntax
Example
25
Array Declaration
int myArray[];
int[] myArray;
double[][] doubleArray;
Array Construction
int[] myArray = new int[5];
int[][] twoDimArray = new int[5][4]
Array Initialization
int[] myArray = new int[5];
for (int I = 0; I < 5; i++) {
myArray[i] = i++;
}
Heap
myArray
int[ ] myArray = {1,2,3,4,5}
27
abc
28
Constructors
29
Abstraction
Hide certain details and show only essential details
public abstract class Shape
{
String color;
public abstract double getArea();
}
public interface Shape
{
String static final String color = BLACK;
public abstract double getArea();
}
I want to share
my wedding gift
only with my
friends
I can share my
puppy video
with everyone
My YouTube videos
My YouTube videos
My Cute
My Cute
puppy
cat
My Wedding
My Hawaii
Gift
trip
31
Encapsulation
32
Inheritance
Inherit the features of the superclass
public class Car //superclass
{
public int maxSpeed;
public String color;
public int getSafeSpeed() { return maxSpeed/2.5; }
}
public class Nissan extends Car
{
public boolean inteligentKey;
}
//subclass
33
Polymorphism
One name, many forms
public abstract class Shape
{
public abstract int getArea();
}
public class Square extends Shape
{
public int getArea(int s) { return s*s; }
public int getArea() { retrun getArea(1); }
}
34
s4
square
S3
shape
s2
s1
35
Throwable
Error
Exception
Checked
Exception
Unchecked
Exception
36
Try/catch/finally
public class MyClass {
public void exceptionMethod() {
try {
// exception-block
} catch (Exception ex) {
// handle exception
} finally {
//clean-up
}
}
}
37
Try/catch/finally - 2
public class MyClass {
public void exceptionMethod() {
try {
// exception-block
} catch (FileNotFoundException ex) {
// handle exception
} catch (Exception ex) {
// handle exception
} finally { //clean-up }
}
}
Using throws
public class MyClass {
public void exceptionMethod() throws Exception {
// exception-block
}
}
38
no
Handle exceptions
In catch?
yes
Handle exception
In the catch block
More exceptions
To handle?
Execute
finally?
no
yes
yes
Clean-up code
in finally
END
39
Garbage Collection
40
Garbage Collection
41
Garbage Collection
A a = new A();
a.Name = A1;
a = A2;
A1
A2
Reassign Reference
A a = new A();
a = null;
A1
Set null
Islands Of Isolation
B
A
C
42
Collections - Introduction
String student1 = a;
String student2 = b;
String student3 = c;
String student4 = d;
String student5 = e;
String student6 = f;
abc
def
ghi
jkl
123
new Person()
def
Arrays
abc
Collections
44
Collections - Overview
LinkedHashSet
45
The sub-flavors:
Ordered - You can iterate through the collection in a specific order.
Sorted - Collection is sorted in the natural order (alphabetical for
Strings).
Unordered
Unsorted
46
Collections Lists
ArrayList
add/delete.
Vector
Ordered collection
To be considered when thread safety is a concern.
Often used methods add(), remove(), set(), get(), size()
Linked List
Ordered collection.
Faster insertion/deletion and slower retrieval when compared to ArrayList
47
Collections Set
HashSet
Not Sorted
Not Ordered
Should be used if only requirement is uniqueness
Often used methods add(), contains(), remove(), size()
LinkedHashSet
TreeSet
Not Sorted
Ordered
Subclass of HashSet
Should be used if the order of elements is important
Sorted
Ordered
Should be used if you want to store objects in a sorted fashion
Often used methods first(), last(), add(), addAll(), subset()
48
Collections Map
HashMap
Hashtable
LinkedHashMap
TreeMap
Sorted, ordered
49
Threads - Introduction
What are Threads/ Why Threads?
A thread is a light-weight process.
Used to provide the ability to perform multiple things at the same time.
method1()
thread1.start()
main()
thread1.run()
Thread Creation
There are 2 ways one can create a thread
Extending the Thread Class
Implementing the Runnable Interface
50
EXECUTION
Threads - Introduction
maintenance
Process report
User validation
EXECUTION
TIME
maintenance
Process report
User validation
Multi-threaded
environment
51
TIME
Threads - Creation
To Invoke:
To Invoke:
T1
T2
start
T1
T2
runnable
T1
blocked
T1
T2
running
T1
T2
end
53
Thread.MIN_PRIORITY
Thread.NORM_PRIORITY
Thread.MAX_PRIORITY
: 1
: 5
: 10
54
Threads Synchronization
Account
100
90acct = getAccount (123);
Account
shared object
public class Account {
private int bal;
private int acctId;
acct
acct
run()
run()
T1 stack
T2 stack
55
56