Introduction To Java
Introduction To Java
Objective
To explain the philosophy behind the Java Language Design To familiarize the language constructs and core concepts Act as a kick-start course to help the learner pursue selfstudy going forward
Course Contents
1. Feel of Java
2. Language Basics
3. Classes and Objects 4. Inheritance, Interfaces and Abstract classes
Part I
Java Evolution
Created by James Gosling for Sun Microsystems in 1991
Motivation
The need for platform independent language that could be embedded in various consumer electronic products like toasters and refrigerators.
At about the same time, the World Wide Web and the Internet were gaining popularity and it needed a programming language
Hands-on
Compile & Run a Java Program Command-line (notepad, javac, java) IDE (Eclipse) Fixing compile-time errors
Command-line arguments
//This program prints out Hello World public class MyProgram { public static void main(String [] args) { System.out.println(Hello World!); } }
Access Modifier (public, private, protected, default) Blocks
Always remember
1. Your Java programs should end with the .java extension. 2. Filenames should match the name of your public class.
For e.g., Class Hello should be coded in Hello.java
3.There can be only one public class per file. A single source file can contain any number of non-public classes.
Part II
Language Basics
Lets Code
Program to calculate sum and average of 3 numbers
//This class will calculate the sum and average public class SumAndAvg { public static void main(String [] args) { SumAndAvg obj = new SumAndAvg (); obj.calculateSumAndAvg(5,10,12); } public void calculateSumAndAvg(int a,int b,int c) { int sum=0; double avg=0.0; sum = a+b+c; avg = sum / 3; System.out.println("Sum:"+sum+" Avg:"+avg); } }
Identifiers
Identifiers are tokens that represent names of variables, methods, classes, etc. E.g.: Hello, main, System, out. Identifiers must begin with either a letter, an underscore _, or a dollar sign $. Letters may be lower or upper case. Subsequent characters may use numbers 0 to 9. You cannot use Java reserved keywords (Keywords are predefined identifiers reserved by Java for a specific purpose) as identifier names
Reserved Keywords
Literals
Literals are tokens that do not change - they are constant.
For E.g.:
Boolean Literals
Character Literals String Literals
Contains
true or false Unicode character Signed integer Signed integer
Default
false \u0000 0 0
Size
1 bit 2 bytes 1byte 2 bytes
Range
NA \u0000 to \uFFFF -128 to 127 -32768 to 32767 -2147483648 to 2147483647
int
Signed integer
4 bytes
long
Signed integer
8 bytes
-9223372036854775808 to 9223372036854775807
float
0.0
4 bytes
double
0.0
8 bytes
Arithmetic Operators
Note: When an integer and a floating-point number are used as operands to a single arithmetic operation, the result is a floating point. The integer is implicitly converted to a floating-point number before the operation takes place.
For e.g.: i=1;j=2; i++; //2 --j; //1 k = i++ + ++j; //?
Relational Operators
Logical Operators
&& and &
Name Logical AND Boolean Logical AND Logical OR Boolean Logical OR Operator && & || |
|| and |
Exclusive OR
Logical Not
^
!
XOR (^)
NOT (!)
Control Structures
Control structures allows us to change the ordering of how the statements in our
programs are executed
Branching Statements
unlabeled break: 1. break a) Labeled b) Unlabeled 2. continue a) Labeled b) Unlabeled for(int x = 0; x < 10; x++ ){ System.out.println(x); if (x % 5 == 0) break; }
1. return
labeled break:
searchLabel: for( int i=0; i<10; i++ ){ for( int j=0; j<i; j++ ){ if( i == j ){ break searchLabel; } } }
Part III
Procedural vs Object-Oriented
Procedural Programming
Object-Oriented Paradigm
Data was given first priority More easy mapping to real-world problems
Objects
Objects in the physical world can easily be modeled as software objects using the properties as data and the behaviors as methods
Classes
Class can be thought of as a template, a prototype or a blueprint of an object is the fundamental structure in object-oriented programming Two types of class members: Fields (properties, variables) specify the data types defined by the class Methods (behavior) specify the operations
Classes provide the benefit of reusability. Software programmers can use a class over and over again to create many object instances.
Creation of Objects
To create an object instance of a class, we use the new operator.
For example, if you want to create an instance of the class String, we write the following code,
String str2 = new String(Hello world!);
String class is a special (and only) class you can create an instance without using new keyword as shown above
Taking a problem and breaking it into small, manageable pieces is critical to writing large programs.
Should be called after object instance is created More common than static methods
Static methods
Parameter Passing
Pass-by-Value when a pass-by-value occurs, the method makes a copy of the value of the variable passed to the method. The method cannot accidentally modify the original argument even if it modifies the parameters during calculations. all primitive data types when passed to a method are pass-byvalue. Pass-by-Reference When a pass-by-reference occurs, the reference to an object is passed to the calling method. This means that, the method makes a copy of the reference of the variable passed to the method. However, unlike in pass-by-value, the method can modify the actual object that the reference is pointing to, since, although different references are used in the methods, the location of the data they are pointing to is the same.
Pass-by-Value
Pass-by-Reference
Part IV
What is Inheritance
Inheritance is the concept of a child class (sub class) automatically inheriting the variables and methods defined in its parent class (super class). A primary feature of object-oriented programming along with encapsulation and polymorphism
Why Inheritance?
Benefits of Inheritance in OOP : Reusability Once a behavior (method) is defined in a super class, that behavior is automatically inherited by all subclasses. Thus, you write a method only once and it can be used by all subclasses. Once a set of properties (fields) are defined in a super class, the same set of properties are inherited by all subclasses. A class and its children share common set of properties A subclass only needs to implement the differences between itself and the parent.
Object class
Object class is mother of all classes
In Java language, all classes are sub-classed (extended) from the Object super class Object class is the only class that does not have a parent Class
Defines and implements behavior common to all classes including the ones that you write clone(); equals(Object obj); getClass(); hashCode(); toString(); ..
extends keyword
public class Person { String name; String address; public Person() { System.out.println(Inside Person:Constructor); } } public class Student extends Person { String class; int marks; public Student(){ System.out.println(Inside Student:Constructor); } } A subclass inherits all of the public and protected members (fields or methods) of its parent, no matter what package the subclass is in When a sub-class is instantiated, constructor-chaining happens
super keyword
public class Person { String name; String address; public Person(String name) { System.out.println(Inside Person:Constructor); } } public class Student extends Person { String class; int marks; public Student(String name, int marks){ super(name); this.marks = marks; System.out.println(Inside Student:Constructor); } }
Note: The super() call must occur as the first statement in a constructor The super() call can only be used in a constructor (not in ordinary methods)
Overriding methods
public class Person { public String getName(){ System.out.println(Person: getName"); return name; } } public class Student extends Person { public String getName(){ System.out.println(Student: getName"); return name; } }
Polymorphism
Polymorphism in a Java program The ability of a reference variable to change behavior according to what object instance it is holding. This allows multiple objects of different subclasses to be treated as objects of a single super class, while automatically selecting the proper methods to apply to a particular object based on the subclass it belongs to Person p = new Person(); Student s = new Student(); Person ps = new Student(); p.getName(); //Person: getName s.getName(); //Student: getName ps.getName(); //Student: getName
When to use?
Abstract methods are usually declared where two or more subclasses are expected to fulfill a similar role in different ways through different implementations (Polymorphism) These subclasses extend the same Abstract class and provide different implementations for the abstract methods Use abstract classes to define broad types of behaviors at the top of an object-oriented programming class hierarchy, and use its subclasses to provide implementation details of the abstract class.
What is an Interface?
It defines a standard and public way of specifying the behavior of classes Defines a contract All methods of an interface are abstract methods Defines the signatures of a set of methods, without the body (implementation of the methods) A concrete class must implement the interface (all the abstract methods of the Interface) It allows classes, regardless of their locations in the class hierarchy, to implement common behaviors
Why Interface?
Reason #1 To reveal an object's programming interface (functionality of the object) without revealing its implementation
Reason #2 To have unrelated classes implement similar methods (behaviors) One class is not a sub-class of another
Reason #3 To model multiple inheritance - you want to impose multiple sets of behaviors to your class Each set is defined as an interface A class can implement multiple interfaces while it can extend only one class
Part V
Concept of Strings
is a sequence of characters is immutable (once created and initialised cannot be changed) String class differs from other classes in that you can use + and += operators
String Methods
StringBuffer class
Problem with String objects: Once created, can no longer be modified (It is a final class) A StringBuffer object Similar to a String object But, mutable or can be modified Unlike String in this aspect Length and content may be changed through some method calls
StringBuffer Methods
Arrays Why?
Suppose we have here three variables of type int with different identifiers for each variable. int number1; int number2; int number3; number1 = 1; number2 = 2; number3 = 3;
As you can see, it seems like a tedious task in order to just initialize and use the variables especially if they are used for the same purpose.
Arrays What?
In Java and other programming languages, there is one capability wherein we can use one variable to store a list of data and manipulate them more efficiently. This type of variable is called an array. An array stores multiple data items of the same data type, in a contiguous block of memory, divided into a number of slots.
Arrays In Java
Declaring an Array int nums[]; int []nums; Instantiation int []nums; nums = new int[20]; int []nums = new int[20]; int []nums = {1,2,3,4,5};
Multidimensional Arrays
// integer array 512 x 128 elements int[][] twoD = new int[512][128];
// integer array 4 rows x 2 columns int [][] arr42 = {{ 1,2 }, {3,4}, {5,6}, {7,8} };
// to access element of 3rd row and 2nd column int elt = arr42[2][1];
Part VI
Exception Handling
What is an Exception?
Exceptional event - typically an error that occurs during runtime Cause normal program flow to be disrupted Examples Divide by zero errors Accessing the elements of an array beyond its range Invalid input Hard disk crash Opening a non-existent file Heap memory exhausted
Exception Example
class DivByZero { public static void main(String args[]) { System.out.println(3/0); System.out.println(Pls. print me.); } }
Catching Exceptions
Syntax: try { <code to be monitored for exceptions> } catch (<ExceptionType1> <ObjName>) { <handler if ExceptionType1 occurs> } ... } catch (<ExceptionTypeN> <ObjName>) { <handler if ExceptionTypeN occurs> }
class DivByZero { public static void main(String args[]) { try { System.out.println(3/0); System.out.println(Please print me.); } catch (ArithmeticException exc) { //Division by zero is an ArithmeticException System.out.println(exc); } System.out.println(After exception.); } }
class DivByZero { public static void main(String args[]) { try { System.out.println(3/0); System.out.println(Please print me.); } catch (ArithmeticException exc) { //Division by zero is an ArithmeticException System.out.println(exc); } finally { //you cannot divide by zero System.out.println(You cannot divide 3 by 0. Pass another number); } System.out.println(After exception.); } } Contains the code for cleaning up after a try or a catch
Garbage Collection
Part VII
What is GC?
The Java virtual machine's heap stores all objects created by a running Java application. Objects are created by the program through new keyword, but never freed explicitly by the program > No need to call free(). Garbage collection is the process of automatically freeing objects that are no longer needed An object is determined to be no longer needed when there is no other object referencing to it
Disadvantages:
GC could add overhead GC can occur in an non-deterministic way
GC API
finalize() method in Object class > Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. gc() method in System class > Runs the garbage collector. > Calling the gc method suggests that the Java Virtual Machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse. > When control returns from the method call, the Java Virtual Machine has made a best effort to reclaim space from all discarded objects.
Collections
Part VIII
What is a collection?
A collection object sometimes called a container is simply an object that groups multiple elements into a single unit Collections are used to store, retrieve, manipulate, and communicate aggregate data
Collections Framework
Interfaces: These are abstract data types that represent collections. Implementations: These are the concrete implementations of the collection interfaces. Algorithms: These are the methods that perform useful computations, such as searching and sorting, on objects that implement collection interfaces.
Interfaces
Collection Interface
public interface Collection extends Iterable { // Basic operations int size(); boolean isEmpty(); boolean contains(Object element); boolean add(E element); //optional boolean remove(Object element); //optional Iterator<E> iterator(); // Bulk operations boolean containsAll(Collection<?> c); boolean addAll(Collection<? extends E> c); //optional boolean removeAll(Collection<?> c); //optional boolean retainAll(Collection<?> c); //optional void clear(); //optional // Array operations Object[] toArray(); <T> T[] toArray(T[] a); }
Collections Interface
Interfaces
Implementations Hash table Resizable array Tree TreeSet ArrayList LinkedList Linked list Hash table + Linked list LinkedHashSet
HashSet
HashMap
TreeMap
LinkedHashMap
Further Reading
Part IX
References
Thank You