Core Java
Core Java
Core Java
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 Compiled and Interpreted The .java file is compiled to a .class file & the .class file is interpreted to machine code
.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); } } Compile the program: javac HelloWorld.java Execute the program: java HelloWorld Output: Hello World
5
package com.sharadballepu.test; public class HelloWorld { public static void main(String[] args) { HelloWorld hw = new HelloWorld(); hw.display(); } public void display() { System.out.println(Hello World); } } Compile the program: javac HelloWorld.java Execute the program: java HelloWorld Output: 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
An instance of a Class
Abstraction
Hide certain details and show only essential details
Encapsulation
Binding data and methods together
Inheritance
Inherit the features of the superclass
Polymorphism
One name having many forms
11
Data type byte short int long float double char boolean
Byt es 1 2 4 8 4 8 2 -
Literal Values 123 1234 12345, 086, 0x675 123456 1.0 123.86 a, \n true, false
General rule: Min value = 2(bits 1) Max value = 2(bits-1) 1 (where 1 byte = 8 bits)
12
Java Modifiers
Modifier
public private protected default final abstract strictfp transient synchronized native volatile static
Class
Class Variables
Methods
Method Variables
13
Modifiers Class
public
Class can be accessed from any other class present in any package
default
Class can be accessed only from within the same package. Classes outside the package in which the class is defined cannot access this class
final
abstract
Class cannot be instantiated, need to sub-classs/extend.
strictfp
Conforms that all methods in the class will conform to IEEE standard rules for floating points
14
public
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
Method can be accessed from any other class present in any package Method can be accessed from only within the class Method can be accessed from all classes in the same package and sub-classes. Method can be accessed only from within the same package. The method cannot be overridden Only provides the method declaration Method conforms to IEEE standard rules for floating points Only one thread can access the method at a time Method is implemented in platform dependent language Cannot access only static members.
16
Operators - Types
Types of operators
Assignment Operators Arithmetic Operators Unary Operators Equality Operators Relational Operators Conditional Operators instaceof Operator Bitwise Operators Shift Operators
17
Arithmetic Operators Operator + * / % Description Addition Subtraction Multiplication Division Remainder Example int i = 8 + 9; byte b = (byte) 5+4; int i = 9 4; int i = 8 * 6; int i = 10 / 2; int i = 10 % 3;
18
Unary Operators Operator + ++ -! Description Unary plus Unary minus Increment Decrement Logical Not Example int i = +1; int i = -1; int j = i++; int j = i--; boolean j = !true;
Relational Operators Operator > < >= <= Description Greater than Less than Greater than or equal to Less than or equal to Example if ( x > 4) if ( x < 4) if ( x >= 4) if ( x <= 4)
Conditional Operators Operator && || Description Conditional and Conditional or Example If (a == 4 && b == 5) If (a == 4 || b == 5)
20
instanceof Operator Operator instanceof Description Instamce of Example If (john instance of person)
Bitwise Operators Operator & | ^ ~ Description Bitwise and Bitwise or Bitwise ex-or Reverse Example 001 & 111 = 1 001 | 110 = 111 001 ^ 110 = 111 ~011 = -10
Shift Operators Operator >> << >>> Description Right shift Left Shift Unsigned Right shift Example 4 >> 1 = 100 >> 1 = 010 = 2 4 << 1 = 100 << 1 = 1000 = 8 4 >>> 1 = 100 >>> 1 = 010 = 2
21
if-else
Example
Syntax
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
Example
Syntax
switch (<value>) { case <a>: // stmt-1 break; case <b>: //stmt-2 break; default: //stmt-3
int a = 10; switch (a) { case 1: System.out.println( 1); break; case 10: System.out.println( 10); break; default: System.out.println( None); Result: 10
23
do-while
Syntax Example
int i = 0; do { System.out.println(In do); i++; } while ( i < 10); Result: Prints In do 11 times
while
Syntax Example
for
Syntax Example
for (int i = 0; i < 10; i++) { System.out.println( In for); } Result: Prints In do 10 times
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++; } int[5] myArray = {1,2,3,4,5};
26
7 8
5 1
2 3
Heap
abc
28
Constructors
Creates instances for Classes Same name as Class name Can have any access modifier First statement should be a call to this() or super()
public class Employee { public int empid; public String name; public Employee(int empid) { this.empid = empid; } public Employee(String name, int empid) { this.name = name; this.empid = empid; } }
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(); }
Encapsulation
Binding data and methods together public class Employee { private String empName; private int salary; public String getSalary(String role) { if(Manager.equals(role)) { return salary; } } public String setSalary(String role, int newSal) { if (Admin.equals(role)) { salary = newSal; } } }
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); } } Public class Rectangle extends Shape { public int getArea(int length, int breadth) { return length * breadth; } public int getArea() { return getArea(1,1); } }
34
public class Shape { public void display() { System.out.println(In Shape); } } public class Square extends Shape { public void display() { System.out.println(In Square); } }
Shape s1 = new Shape(); s1.display(); Square s2 = new Square (); s2.display(); Shape s3 = new Square (); s3.display(); Square s4 = new Shape (); s4.display();
s4 square S3 s2 s1
35
shape
Throwable
Error
Exception
Checked Exception
Unchecked Exception
36
What do you do when an Exception occurs? Handle the exception using try/catch/finally Throw the Exception back to the calling method.
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
yes
no
Handle exception In the catch block More exceptions To handle? Execute finally?
yes yes
Clean-up code in finally
no
END
39
Garbage Collection
40
Garbage Collection
Making your objects eligible for Garbage Collection Reassign reference variable Set a null value Islands of isolation
41
Garbage Collection
A1 Reassign Reference
A2
Set null
A1
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;
Difficult to maintain multiple items of same type as different variables Data-manipulation issues Unnecessary code
43
abc
def
ghi
jkl
Arrays
abc
123
new Person()
def
Collections
44
Collections - Overview
LinkedHashSet
45
Three basic flavors of collections: Lists - Lists of things (classes that implement List) Sets - Unique things (classes that implement Set) Maps - Things with a unique ID (classes that implement Map)
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
Resizable-array implementation of the List interface. Ordered collection. Should be considered when there is more of data retrieval than Often used methods add(), get(), remove(), set(), size()
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
Not Sorted Ordered Subclass of HashSet Should be used if the order of elements is important
TreeSet
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
Not Sorted, not ordered Can have one null key and any number of null values Not thread-safe Often used methods get(), put(), containsKey(), keySet()
Hashtable
Not Sorted, not ordered Cannot have null keys or values Thread-safe
LinkedHashMap
Not sorted, but ordered
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.
Thread Creation There are 2 ways one can create a thread Extending the Thread Class Implementing the Runnable Interface
50
Threads - Introduction
EXECUTION
TIME
EXECUTION
TIME
Threads - Creation
public Class MyThread extends Thread { public void run() { System.out.println( In Thread); } }
public Class MyThread implements Runnable { public void run() { System.out.println( In Thread); } }
To Invoke:
To Invoke:
T1
T2
T1
start
blocked
T1
T2
T1
T2
T1
T2
runnable
running
end
53
From the Thread class public void start() public void run() public static void sleep(long millis) throws InterruptedException public static void yield() public final void join() public final void setPriority(int newPriority)
: 1 : 5 : 10
public final void wait() public final void notify() public final void notifyAll()
54
Threads Synchronization
Account acct = getAccount (123); 100 90 MyThread t1 = new MyThread(acct); MyThread 100 50 t2 = new MyThread(acct);
Account
shared object
public class Account { private int bal; private int acctId; public Account(int acctId) { this.acctId = acctId; } public boolean withdraw(int amt) { if (bal > 0) { // give money // other related activities bal = bal amt; } } }
acct run()
acct run()
T1 stack
T2 stack
55
56