Download Java core programming and more Lecture notes Java Programming in PDF only on Docsity! 1 Core Java - Sharad Ballepu 2 Servlets & JSPs Agenda • Introduction • Access Modifiers • Operators • Flow Control • Arrays and Strings • OOPS Explored • Exceptions • Garbage Collection • Collections • Threads • Demo Core Java 5 Introduction – My First Program Version 1 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 6 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 Introduction – My First Program Version 2 7 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 Introduction – My First Program Version 3 10 Introduction – Stack v/s Heap x = 10 y = new A() method2() method1() main() Stack Heap A B C 11 • Class – A blueprint that defines the attributes and methods • 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 Introduction - Object Oriented Concepts 12 Introduction - Data Types Data type By te s Min Value Max Value Literal Values byte 1 -27 27 – 1 123 short 2 -215 215 – 1 1234 int 4 -231 231 – 1 12345, 086, 0x675 long 8 -263 263 – 1 123456 float 4 - - 1.0 double 8 - - 123.86 char 2 0 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) 15 Modifiers – Class Attributes • public – Attribute can be accessed from any other class present in any package • private – Attribute can be accessed from only within the class • protected – Attribute can be accessed from all classes in the same package and sub-classes. • default – Attribute can be accessed only from within the same package. • final – This value of the attribute cannot be changed, can assign only 1 value • transient – The attribute value cannot be serialized • volatile – Thread always reconciles its own copy of attribute with master. • static – Only one value of the attribute per class 16 Modifiers – Methods • public – Method can be accessed from any other class present in any package • private – Method can be accessed from only within the class • protected – Method can be accessed from all classes in the same package and sub- classes. • default – Method can be accessed only from within the same package. • final – The method cannot be overridden • abstract – Only provides the method declaration • strictfp – Method conforms to IEEE standard rules for floating points • synchronized – Only one thread can access the method at a time • native – Method is implemented in platform dependent language • static – Cannot access only static members. 17 • 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 Operators - Types 20 • Relational Operators Operator Description Example > Greater than if ( x > 4) < Less than if ( x < 4) >= Greater than or equal to if ( x >= 4) <= Less than or equal to if ( x <= 4) Operators – Relational Operators/Conditional Operators Operator Description Example && Conditional and If (a == 4 && b == 5) || Conditional or If (a == 4 || b == 5) • Conditional Operators 21 • instanceof Operator Operator Description Example instanceo f Instamce of If (john instance of person) Operators – instanceof Operator/Bitwise Operators/shift operators Operator Description Example & Bitwise and 001 & 111 = 1 | Bitwise or 001 | 110 = 111 ^ Bitwise ex-or 001 ^ 110 = 111 ~ Reverse ~011 = -10 • Bitwise Operators • Shift Operators Operator Description Example >> Right shift 4 >> 1 = 100 >> 1 = 010 = 2 << Left Shift 4 << 1 = 100 << 1 = 1000 = 8 >>> Unsigned Right shift 4 >>> 1 = 100 >>> 1 = 010 = 2 22 Flow Control – if-else if-else • 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 25 Flow Control – for loop • for Syntax Example for ( initialize; condition; expression) { // stmt } for (int i = 0; i < 10; i++) { System.out.println(“In for”); } Result: Prints “In do” 10 times 26 Arrays and Strings – Arrays Declaration/Construction/Initialization • 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}; 1 2 97 5 0 7 5 3 2 8 1 27 Arrays and Strings – Arrays Representation 1 2 3 4 5 myArray int[ ] myArray = {1,2,3,4,5} Heap 30 OOPS Explored - Abstraction • Abstraction Hide certain details and show only essential details public abstract class Shape { String color; public abstract double getArea(); } • Abstract class v/s interface public interface Shape { String static final String color = “BLACK”; public abstract double getArea(); } 31 OOPS Explored - Encapsulation My YouTube videos My Cute puppy My Wedding Gift My YouTube videos My Cute cat My Hawaii trip I can share my puppy video with everyone I want to share my wedding gift only with my friends 32 Binding data and methods together OOPS Explored - Encapsulation • Encapsulation 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; } } } 35 OOPS Explored – Polymorphism - Example 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 S3 s2 s1 shape square 36 Exceptions – Exception Hierarchy Throwable ExceptionError Unchecked Exception Checked Exception 37 Exceptions – Handling exceptions • 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 } } } 40 Garbage Collection 41 Garbage Collection • What is Garbage Collection? • Can we force Garbage Collection? Runtime – gc() System - gc() • Making your objects eligible for Garbage Collection – Reassign reference variable – Set a null value – Islands of isolation 42 Garbage Collection A1 A2 A a = new A(); a.Name = ‘A1’; a = A2; A1 A a = new A(); a = null; A C B Reassign Reference Set null Islands Of Isolation Collections - Overview
Collection
ao
a
-
Co {
HashSet. TreeSet LinkdList Vector
LinkedHashSet
Hashtable LinkedHashMap HashMap TreeMap
4 > —
Indicates Implementation Indicates Inheritance
45
46 Collections – Collection types • 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 47 Collections – Lists • ArrayList Ordered collection To be considered when thread safety is a concern. Often used methods – add(), remove(), set(), get(), size() • Vector Resizable-array implementation of the List interface. Ordered collection. Should be considered when there is more of data retrieval than add/delete. Often used methods – add(), get(), remove(), set(), size() • Linked List Ordered collection. Faster insertion/deletion and slower retrieval when compared to ArrayList 50 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 main() method1() thread1.start() thread1.run() 51 Threads - Introduction TIME User validation Process report maintenance TIME User validation Process report maintenance E X E C U T IO N E X E C U T IO N Multi-threaded environment 52 Threads - Creation Extending the Thread Class Implementing the Runnable Interface public Class MyThread extends Thread { public void run() { System.out.println(“In Thread”); } } To Invoke: MyThread t1 = new MyThread(); t1.start(); public Class MyThread implements Runnable { public void run() { System.out.println(“In Thread”); } } To Invoke: MyThread t1 = new MyThread(); Thread t = new Thread(t1); t.Start(); 55 Threads – Synchronization Account Account acct = getAccount (123); MyThread t1 = new MyThread(acct); MyThread t2 = new MyThread(acct); t1.start(); t2.start(); 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; } } } run() run() T1 stack T2 stack acct acct 100 140 50 100 90 100 56