Sunteți pe pagina 1din 60

Core Java

Chapter 1: Introduction

1
Core Java
1.1 What is Java?
- Java is a high level, robust, secure Object Oriented Programming (OOP) language
- Java was developed by James Gosling at Sun Microsystems in 1995
- Java was acquired, and is now facilitated by Oracle Corporation
- Java can be used to develop applications for desktop, web and mobile devices
- Java is one of the most popular programming language in use (almost 3 Billion devices run java)
- A software environment in which a program runs is known as a platform, since Java has its own JVM, Java is also a platform

1.2: Java Platforms / Editions / Environment


- Java Development Kit (JDK) to write and compile Java Programs
- Java Virtual Machine (JVM) to is an abstract machine (set of specifications) that runs compiled Java programs
- Java Runtime Environment (JRE) is the actual implementation of a JVM
- Eclipse is an Integrated Development Environment (packaged with a JDK & JVM) to write, compile and run Java Programs
- Java Standard Edition (Java SE) for standalone desktop applications
- Java Enterprise Edition (Java EE) for web and enterprise applications, Servlets, JSP’s, WebServices and EJB’s
- Java Platform SDK API’s specification can be found at https://docs.oracle.com/javase/7/docs/api/

2
Core Java
1.3 Types of Java Applications
- Standalone Applications or desktop applications
- Web Applications that run on the server side and create dynamic web pages, Servlets, JSP’s etc
- Enterprise Applications that are distributed in nature, Java EJB’s
- Mobile Applications

1.4 Internals of a JVM


- The JVM loads code, verifies code, and provides a runtime environment to execute code

3
Core Java
1.4 Features of Java

1.4.1 Simple

- syntax is based on C++


- removed confusing concepts that exist in C++ like pointers operator overloading etc …
- automatic garbage collection in Java therefore there is no need to remove unreferenced objects

1.4.2 Object-Oriented

- Java is an Object Oriented Programming (OOP) Language


- programming problems are modelled as objects and relationships between objects

4
Core Java
- use of OOP concepts like Class, Object, Inheritance, Polymorphism, Abstraction and Encapsulation

1.4.3 Platform Independent

- Java is platform independent


- This means that Java programs can be executed on any operating system (Windows, Mac OS, Linux etc …)
- Programming statements are written in English like statements
- Programming statements have to be converted (Compiled) to machine code for computers to understand
- Java uses a 2 step compilation process. First converts to byte code and then to machine language
- Compiler converts programming statements to byte code
- Java Virtual Machine (JVM) converts byte code to machine code to the specific platform
- Java programs can be run on any computer or OS that has a JVM
- Write once, compile once, run anywhere (WORA)

1.4.4 Secure

- Java programs run inside a JRE (its own runtime environment) unlike other C++ which runs in the runtime of the OS
- The Java Class Loader adds security by separating Java packages from other folders in the local file system
- Byte Code Verifier checks the code fragments or illegal code that violate access rights to objects
- Security Manager what resources a class can access when reading and writing from the local disk
- The Java Platform provides the infrastructure to build secure applications using SSL, JAAS, Cryptography etc …

1.4.5 Robust

- Robust simply means strong


- Java use features like memory management, lack of pointers, exception handling, automatic garbage collection etc …
- Such features make Java a robust platform / programming language

1.4.6 Architecture Neutral

- There are no hardware / implementation dependent features

5
Core Java
- For eg: For an int primitive data type C/C++ uses 2 bytes on a 32-bit architecture and 4 bytes in a 64-bit architecture
- Whereas Java always uses 4 bytes for an int primitive data type regardless of the underlying architecture

1.4.7 Portable

- Java byte code can be moved to (copied) to run on any platform or OS

1.4.8 High Performance

- Java is built for high performance and speed since byte code is close to native machine code
- Sufficient speed and performance for Web and Enterprise applications
- However, C/C++ tend to perform faster than Java because there is no byte code in C/C++

1.4.9 Distributed

- We can build distributed applications with Java where different parts of the application run on different machines
- Distributed computing is achieved in Java through features like Remote Method Invocation (RMI)

1.4.10 Multi-threaded

- A thread is like a separate program


- We can write Java programs that deal with many tasks at the same time using multiple threads

1.5 C++ Vs Java

C++ is platform-dependent. Java is platform-independent.

C++ is mainly used for system programming. Java is mainly used for application programming. It is widely used
in window, web-based, enterprise and mobile applications.

6
Core Java
C++ supports goto statement. Java doesn't support goto statement.

C++ supports multiple inheritance. Java doesn't support multiple inheritance through class. It can be
achieved by interfaces in java.

C++ supports operator overloading. Java doesn't support operator overloading.

C++ supports pointers. You can write pointer program in Java supports pointer internally. But you can't write the pointer
C++. program in java. It means java has restricted pointer support in
java.

C++ uses compiler only. Java uses compiler and interpreter both.

C++ supports both call by value and call by reference. Java supports call by value only. There is no call by reference in
java.

C++ supports structures and unions. Java doesn't support structures and unions.

C++ doesn't have built-in support for threads. It relies on Java has built-in thread support.
third-party libraries for thread support.

C++ doesn't support documentation comment. Java supports documentation comment (/** ... */) to create
documentation for java source code.

C++ supports virtual keyword so that we can decide Java has no virtual keyword. We can override all non-static
whether or not override a function. methods by default. In other words, non-static methods are
virtual by default.

7
Core Java
C++ doesn't support >>> operator. Java supports unsigned right shift >>> operator that fills zero at
the top for the negative numbers. For positive numbers, it works
same like >> operator.

C++ creates a new inheritance tree always. Java uses single inheritance tree always because all classes are
the child of Object class in java. Object class is the root of
inheritance tree in java.

8
Core Java

Chapter 2: Basic Structure of A Java Program

9
Core Java
2.1: Package
- A package is a grouping of related classes and interfaces
- When we write package (first line of a class or interface) we are telling the compiler to include the file in the package
- Two or more files can have the same name as long as they belong different packages
- Using packages prevents Naming Conflicts
- The compiler will create a folder with the package name, and save the file in the folder
- Java is case sensitive. “HelloWorld” is NOT the same as “helloworld”
- The naming convention for package names is lower case alphanumeric separated by dots

Example:
package com.tutorials.helloworld;

Java (JDK) also comes with built in packages for specific tasks
- java.io
- java.utils
- java.math
- java.awt
- java.net
- etc …

2.2: Class
- A class is the basic building block of an OO language like Java
- A class is a template the describes the data and behavior associated with instances of that class
- When you instantiate a class you create an object that looks and feels like other instances of the same class
- Naming convention for class names is alphanumeric camel case, class names can include _ etc…, cannot start with a number
- The main(String[] args) is the entry point of all Java applications, it is the first method that will be called
- Comments are ignored by the compiler, and added to programs to make programs more readable for other developers

10
Core Java
2.2: Executing a Java Program
- Install JDK (includes a JRE) or JRE
- Write the program in file with a .java extension
- Compile the program
- Run the program

2.2: Example Java Program


class Simple {
public static void main(String args[]) {
System.out.println("Hello Java");
}
}

11
Core Java

Chapter 3: Primitive Data Types, Variables & Operators

12
Core Java
3.1: Data Types in Java
- There are 2 high level data types in Java, namely primitive and Non-primitive datatypes
- In Java, primitive data types are passed by value and non-primitive data types are passed by reference

13
Core Java
3.2: Primitive Data Types in Java
- There are 8 basic data types pre-defined in Java
- Primitive data types in Java are reserved lowercase keywords (cannot be used as variable names)
- byte: The byte data type stores integers, has a range of -128 to 127, and requires 1 byte of storage space
- short: The short data type stores integers, has a range of -32,678 to 32767, and requires 2 bytes of storage space
- int: The int data type stores integers, has a range of -231 to 231-1, and requires 4 bytes of storage space
- long: The long data type stores integers, has a range of -263 to 263-1, and requires 8 bytes of storage space
- float: The float data type stores decimals, has a precision of 7 digits, and requires 4 bytes of storage space
- double: The double data type stores decimals, has a precision of 15 digits, and requires 8 bytes of storage space
- char: The char is to store single Unicode characters like ‘A’, ‘a’, ‘3’, ‘%’,’@’ etc .., and requires 2 bytes of storage space
- boolean: The boolean is a special data type that can hold only 2 values true and false

3.3: What are Variables?


- Variables are names given to data that we need to store and manipulate in our programs
- The declaration of a variable first states the data type of the variable followed by it’s name
- After declaring a variable, you need to give it an initial value, this is known as initialization
- Variables of primitive types that are declared and not initialized will be assigned default values
- The data type of the variable refers to the type of data that the variable will store
- After you declare a variable, the program will allocate a certain area of the computer memory to store this data
- Variable names can contain letters, numbers, _ underscores, and $ dollar signs
- However, variable names cannot start with a number
- Best practice naming convention for variable names is camel case
- Variable names must be meaningful and designed to indicate the intent of it’s use to the casual reader
- Java reserved keywords like package, class, interface, if, else, while, System etc … cannot be used as variable names

byte userAge = 20;


short numberof Courses = 12;
int numberOfStudents = 500;
long populationOfMorrisville = 1021313012678L;

14
Core Java
float hourlyBillingRate = 60.75;
double noOfHours = 160.50;
char grade = ‘A’;
boolean promote = true;

3.4: Type Casting


- Sometimes it is necessary to convert one data type to another like float to int, long to short, double to int, etc …
- This is known as type casting
- Widening primitive conversion is assigning a smaller data type to a larger data type, for example short to a double, etc …
- Narrowing primitive conversion is assigning a larger data type to a smaller data type, for example double to a int, etc …
- Widening primitive casting is exactly like an assignment, we do not need to do anything different
- Whereas, for Narrowing primitive casting, we need to explicitly cast as shown in example below
- Narrowing conversion is not safe (loss of data), and should be avoided unless absolutely necessary

3.5: Assignment & Basic Operators


- Assignment Operators: =, +=, -= , *=, ++, -- are the assignment operators in Java
- Basic Operators: + (addition), - (subtract), * (multiply), / (divide), % (mod) are the basic math operators in Java
- The = sign has a different meaning in programming from the = sign we learnt in math.
- The assignment operator = means we are the assigning the value on the right operator to the variable on the left
- In programming x = y and y = x are different and have a different meaning
- There are other operators in Java, like relational operators, bit shift operators and bitwise operators
- Complete set of Java operators in the diagram below

15
Core Java

Operator Type Category Precedence

Unary Postfix expr++ expr--

Prefix ++expr --expr +expr -expr ~ !

Arithmetic Multiplicative */%

Additive +-

Shift Shift << >> >>>

Relational Comparison < > <= >= instanceof

Equality == !=

Bitwise bitwise AND &

bitwise exclusive OR ^

bitwise inclusive OR |

Logical logical AND &&

logical OR ||

Ternary Ternary ?:

Assignment Assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

16
Core Java

Chapter 4: Arrays & Strings

17
Core Java
4.1: Arrays
- Array is an advanced data structure
- An array is a collection of data that is of the same data type and is related to each other
- Arrays have to be declared and initialized like primitive data types
- Unlike with primitive data types, in the case of an array the size of the Array has to be specified during initialization
- The size tells the compiler the memory required to hold the Array. Once initialized, the size of the array cannot be changed
- During initialization, if no values are specified, the array is created with default values of the respective data type
- Array values are updated by accessing them using their indexes. Indexes are of int data type.
- The first element of the array has an index of 0, the second element has an index 1, and so on …
- The last element of the array will have an index of the array length – 1
- There are 2 types of arrays in java, a single dimensional array, and 2-Dimensional Array (also called multi-dimensional array)
- In a multi-dimensional array, data is stored in a row / column form based on an index (also known as matrix form)

4.1: Declaration & Intialization of a Single Dimensional Array


Declaration:
- int[] userAges;
- int userAges[];

Initialization:
- int[] userAges = new int[] {21, 22, 23, 24, 25};

18
Core Java
- int[] userAges = {21, 22, 23, 24, 25};
- int[] userAges = new int[5];
userAges[0] = 21;
userAges[1] = 22;
userAges[2] = 23;
userAges[3] = 24;
userAges[4] = 25;

Length of the Array:


- userAges.length;

4.2: Declaration & Intialization of a Multi-Dimensional Array


Declaration:
- int[][] userAges;
- int userAges[][];

Initialization:
- int[][] userAges = new int[] {{21, 22, 23}, {33,34,35}};
- int[][] userAges = {{21, 22, 23}, {33,34,35}};
- int[][] userAges = new int[2][3];
userAges[0][0] = 21;
userAges[0][1] = 22;
userAges[0][2] = 23;
userAges[1][0] = 33;
userAges[1][1] = 34;
userAges[1][2] = 35;

Length of the Array:


- userAges.length;
- userAges[0].length;

19
Core Java
4.3: Array Methods
- Arrays come with a number of pre-written methods
- Array methods are found in the java.utils.Arrays class, in the java.utils package of the JDK
- To access Array methods in a class we have to import the Arrays class, import java.utils.Arrays;
- The import statement tells the compiler where to find the code for these methods
- Some example methods are explained below using int arrays. These methods can be applied to Arrays of all types

boolean isEquals = equals(int[] arr1, int[] arr2);


- The equals() method checks if two arrays are equal to each other, it returns true if they are equal, and false otherwise
- equals() means both Arrays have the same elements in the same order

int[] destinationArray = copyOfRange(int[] sourceArray, int fromIndex, int toIndex);


- The copyOfRange() copies contents of one array to another, from the source array to the destination array
- copyOfRange() method takes 3 arguments as input, and returns an output. Note the data types of the arguments and output

String toString(int[] arr);


- The toString() method returns a String that represents the contents of the Array
- This makes it easy for us to display or print the Array

void sort(int[] arr);


- The sort() method sorts the elements of the array in ascending order
- Note that the sort() method does not return a new array, it simply modifies the array that is passed in to it

int foundIndex = binarySearch(int[] arr, int searchKey);


- The binarySearch() method checks if the searchKey is present in a sorted Array. It can only be called on a sorted array
- If it the searckKey is found the index of the searchKey in the Array is returned, if not a negative number is returned

20
Core Java
4.4: Strings
- Strings are an Advanced Data Type
- A String is a piece of text like “Hello World”, “This is Chapter Section 4.2”, “What is your name?”
- A String has to be declared, instantiated, initialized, and are represented in double quotes
- You can also assign an empty String to a String variable
- Adding one String to the end of another String is called concatenation. With Strings + acts as the concatenation operator
- You need to escape special unprintable characters with a “\”. Tab “\t”, newline “\n”, backslash ”\\”, double quotes “\”

4.5: Declaration, Instantiation and Initialization of Strings


Declaration
- String exampleString;

Instantiation
- String exampleString = new String();

Initialization
- String exampleString = new String(“Hello World”);

Declaration, Initialization & Instantiation


- String exampleString = new String(“Hello World”);
- String exampleString = “Hello World”;
- String exampleString = “”;
- String exampleString = “1234aaaBBB!!!@#$^%”;
- String exampleString = “Welcome \n\t This is a \”Java\” Tutorial \n\t We will learn \”Core Java\” in this tutorial”;

Concatenation
- String exampleString = “Hello” + “ “ + “World”;

21
Core Java
4.6: String Methods
- The String class is part of the java.lang package.
- You do not have explicitly import java.lang in a class. It is provided implicitly to every Java class
- The String class comes with a list of methods, we will study a few here, browse java.lang.String docs to learn about others

int length();
- The length() method counts the characters in the String. Empty space (“ “) is also a character, and adds to the size

String toUpperCase() / String toLowerCase();


- The toUpperCase() / toLowerCase() method is used to convert all characters of the String to upper / lower case letters

String substring(int startIndex) / String substring(int startIndex, int endIndex);


- The substring() method is used to extract a substring from a longer String.
- substring(1, 8) will extract “ello Wo” from the longer String “Hello World”

char charAt(int index);


- The charAt() method returns a single character at a specified location

boolean equals(String toCompareWith);


- The equals() method is used to compare 2 strings
- equals() returns true if the 2 Strings are identical and false otherwise

String[] split(String seperator);


- The split() method splits a String into substrings based on the user-defined separator, also known as the delimiter
- After splitting the String the split() method returns an Array of the resulting substrings

22
Core Java
4.7: Primitive Type Vs Reference Type
- All data types in Java can be classified as either a primitive type or reference type
- There are only 8 primitive types, the rest are reference types
- byte, short, int, long, float, double, boolean & char are primitive types
- Array, String, and all other classes and interfaces in Java are reference types
- With the primitive type the variable stores it’s own data
- Where as with a reference type, the variable does not store it’s own data, but rather stores a pointer to the data
- The pointer is the memory address of where the actual data is stored
- Reference data types are Immutable, once created which means that the value cannot be changed
- So, when we update a Reference Type, a new object is created and only the memory address of the variable is changed

23
Core Java

Chapter 5: Accepting User Inputs

24
Core Java
5.1: Scanner
- There are a few ways to accept user inputs in Java, like the String[] args in main, Scanner etc …
- Most popularly used is the Scanner Object
- The Scanner object needs to be declared, instantiated, and initialized like all objects in Java
- The Constructor of the Scanner object takes System.in as an input argument
- System.in tells the compiler that you want to get input from the standard input device, usually the keyboard
- The Scanner object is part of the java.util package
- The Scanner object has built in methods to read various primitive data types and Strings. A char is read as a String
- The method nextDouble() is an exception, it requires an nextLine() after it to read the newline “\n” control character

Declare, Intialize and Instantiate a Scanner with it’s Constructor


Scanner inputScanner = new Scanner(System.in);

Scanner methods to scan primitive inputs & Strings


byte inputByte = inputScanner.nextByte();
short inputShort = inputScanner.nextShort();
int inputInt = inputScanner.nextInt();
long inputLong = inputScanner.nextLong();
float inputFloat = inputScanner.nextFloat();
double inputDouble = inputScanner.nextDouble();
boolean inputBoolean = inputScanner.nextBoolean();

A few other methods


String intputPattern = inputScanner.findInLine(String pattern);
boolean hasNext = inputScanner.hasNext();

References
Java documentation for java.util.Arrays.java
https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html

25
Core Java

Chapter 6: Control Flow Statements

26
Core Java
6.1: Comparison Operators

- Comparison Operators are binary and return a true or false value based on the comparison

Equals (==)
(x == y) returns true if x is equal to y, and returns false otherwise

NotEquals (!=)
(x != y) returns true if x is not equal to y, and false otherwise

Greater than (>)


(x > y) returns true if x (the variable on the left) is greater than y (the variable on the right), false otherwise

Less than (<)


(x < y) returns true if x (the variable on the left) is lesser than y (the variable on the right), false otherwise

Greater than or equal to (>=)


(x >= y) returns true if x (the variable on the left) is greater than or equal to y (the variable on the right), false otherwise

Less than or equal to (>=)


(x <= y) returns true if x (the variable on the left) is lesser than or equal to y (the variable on the right), false otherwise

The AND operator (&&)


(x == y) && (a <= b) && (c != d) returns true if all conditions of the expression are true, false otherwise

The OR operator (||)


(x == y) || (a <= b) || (c = d) returns true if all conditions of the expression are true, false otherwise

27
Core Java
6.2: Decision Making Statements

- Decision making statements involve some form of comparison


- The program proceeds differently depending on the result
- The 3 decision making statements in Java are If Else statements, the Switch statement, and the Ternary Operator
- The most commonly used is the If Else statement
- The Switch statement is similar to the If Else statement, except it works on a single value of a variable
- The Switch statement does not work on conditions, ranges or expressions
- You can use byte, short, char, int or String variable for switching
- The Ternary is a simplified form of an If Else statement, that is convenient to use when assigning values to a variable
- When using char or String you need to pay attention to the upper/lower case of the variable as Java is case sensitive

If Else Statement

If( condition 1 is met ) {


Do Task A;
} else if( condition 2 is met ) {
Do Task B;
} else if( condition 3 is met ){
Do Task C;
} else if( condition 4 is met ){
Do Task D;
} else {
Do Task E;
}

Ternary Statement

condition ? Value to return if condition is true : value to return if condition is false;

28
Core Java
Switch Statement

switch( variable used for switching ) {


case zerocase:
case firstcase:
Do Task A;
break;
case secondcase:
Do Task C;
break;
case thirdcase:
Do Task C;
break;
default:
Do Task D;
break;
}

6.2: Looping Statements

- There are 4 looping statements in Java, for statement, enhanced for statement, while statement, and do while statement
- Each run of the looping statement is called a loop. Scope of the loop is the block of code between the curly brackets { and }
- The for, while and do while loops execute a block of code repeatedly as until the test condition remains valid
- The for loop uses a counter increment and is commonly used for a fixed number of required runs known in advance
- The while loop uses only a test condition, and is usually used where the number of required runs is not known in advance
- The enhanced for statement is a simplified for statement used when reading Collections, like arrays
- for and while loops check the condition before the run of each loop, whereas do while loop checks after the run of each loop
- It can happen that the for, and while loops, the loop is not even entered even once (if the condition is not met to start with)
- Whereas, for the do while loop, the condition is checked after each run, this ensures that the do while loop runs atleast once
- Loops can be assigned labels, and loops can be controlled (use of branching statements) by their labels

29
Core Java
For Loop

loop1:
for( int i=0; i<10; i++) {
System.out.println(“Hello World”);
}

int[] numbers = {1, 2, 3, 4, 5, 6};


for( int i=0; i<numbers.length; i++ ) {
System.out.println(“Element at array index “ + i + “ is “ + numbers[i]);
}

char[] characters = {‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’};


for( int i=0; i<numbers.length; i++ ) {
System.out.println(“Element at array index “ + i + “ is “ + numbers[i]);
}

Enhanced For Loop

int counter = 0;
int[] numbers = {1, 2, 3, 4, 5, 6};
for( int oneArrayNumber: numbers ) {
System.out.println(“Element at array index “ + counter + “ is “ + oneArrayNumber);
counter++;
}

30
Core Java
While Loop

int counter = 5;
int[] numbers = {1, 2, 3, 4, 5, 6};
while( counter > 0 ) {
System.out.println(“Element at array index “ + counter + “ is “ + numbers[counter]);
Counter --;
}

Do While Loop

int counter = 5;
int[] numbers = {1, 2, 3, 4, 5, 6};
do {
System.out.println(“Element at array index “ + counter + “ is “ + numbers[counter]);
counter --;
} while( counter < 0 );

6.3: Branching Statements

- Branching statements are statements that instruct the program to branch to another line of code
- Branching statements are commonly used in loops and other control statements
- The 2 branching statements in Java are break; and continue;
- The break; statement is commonly used in Switch statements, and Loops
- The break; causes the loop to exit prematurely when some condition is met
- The continue statement is used in Loops
- When we use the continue; statement the rest of the loop after break; is skipped for that iteration

31
Core Java
6.4: Exception Handling

- Exception Handling helps us control the flow of a program when an error occurs
- If we believe that a certain block of code may cause an error, we should try to manage it with Exception Handling
- Exception Handling in Java is achieved through the try catch finally statement
- If an exception occurs the program terminates unless we manage the error by catching it
- There Exception Handling is good way to identify what went wrong in the execution of the program
- You can have more than one catch block, if more than one type of error is anticipated
- The Exception class is a super class of all specific Exception classes like ArrayIndexOutofBoundsException class, etc …
- You can also catch multiple Exception subclasses in multiple catch blocks as required
- Like catching exceptions, we can also define conditions for when an error should occur. This is known as throwing an error
- The Exception class is in the java.lang package. Different Exception sub classes can be part of different packages

try {
Do Task A
} catch ( ArrayIndexOutOfBoundsException ex ) {
Do Task B
} catch( InputMisMatchException ex ) {
Do Task C
} catch( Exception ex ) {
Do Task D
} finally {
Always Do Task E
}

throw new Exception( “An Error Has Occurred here …” );

32
Core Java

Chapter 7: Object Oriented Programming (Part 1)

33
Core Java
7.1: What is Object Oriented Programming (OOP)

- OOP is an approach where programming problems are broken down to objects that interact with each other

7.2: Class

- A Class is a blueprint or template to create or build an Object


- A Class is a template the describes the data and behavior associated with objects that are created from it
- Every Class has a name and body. The body (scope) of the class is defined using curly brackets { … }
- The name of class uses camel case and must start with a Capital letter
- Every class is Java is implicitly the sub class of the Object class in Java

7.3: Objects

- Objects are created from classes (templates), and have a state and behavior
- One or more objects can be created from a Class
- An Object is an advanced (reference) data type like Strings, and Arrays
- Like other advanced data types, Objects must be declared, instantiated and initialized

7.4: Fields

- Fields are variables that are declared in a class. Like any other variable, fields are used to store data
- Fields can be primitive variables, or advanced (reference) variables like Arrays, Strings, or other Objects
- Field values determine the state of the Class

7.5: Methods

- Methods are blocks of code in a class that perform certain specific tasks
- Methods have a name, signature and body. The body (scope) of the method is defined using curly brackets { … }
- Methods take zero or more input parameters, perform a certain task, and return zero or 1 output parameter
- Method input / output parameters can be either primitive or advanced (reference) data types

34
Core Java
- The signature (definition) of a method is its name and input parameters (type and order of input variables)
- A class cannot have more than one method with the same signature
- Methods define the behavior of the Class
- Methods in a class can access all fields of the Class
- If a method does not return anything, then void must be specified as it’s return type

7.6: Constructors

- A Constructor is a method used to create (instantiate) an Object


- Constructors have the same name as the class, and do not specify a return type
- Constructors have a name and body, but do NOT have a return type
- A Constructor takes zero or more input parameters, and perform certain tasks to create the Object
- Constructors input parameters can be either primitive or advanced (reference) data types
- The signature (definition) of a Constructor is its name and input parameters (type and order of input variables)
- A class cannot have more than one Constructor with the same signature

7.7 Getters / Setters

- Getters / Setters are methods that are used to get / set the value of fields in a Class

7.8 Modifiers

- Modifiers are Java keywords that modify a property of a field, method, class or interface
- Modifiers define where, when, how and by whom modified members can be accessed and modified

7.8 Access Modifiers

- Access modifiers control access to fields, methods, classes and interfaces


- They are Java keywords that define who and where a modified field, method, class or interface can be accessed
- default, public, protected and private are access modifiers
- default (also known as package-private) members can only be accessed by other classes in the same package

35
Core Java
- public members can be accessed by any class in the system (project)
- private members can only be accessed within a class
- protected members can be accessed by either classes in the package (package-private) or by subclasses of the class

7.9 Static

- static is a non-access modifier in java


- A static member belongs to the class itself and is not associated with instances of the class
- Fields, methods, classes and interfaces can be modified to be static members
- A static member is shared between all instances of a class, and is used widely for memory management
- A static member is also used to represent a common member to all instances (Objects instantiated) of a class

7.10 Final

- final is also a non-access modifier in Java


- A final member can only be initialized, and cannot be modified in the program
- The value of a final member cannot be changed or modified once a value has been assigned
- A final member has to be initialized during creation of instance (object).
- Note: Interfaces cannot be modified by final, however fields and methods within an interface can be modified by final

public class Student {


// Body (Scope) of Class
static final public university = “North Carolina State”;
public final String name = “Not Available”;
private int age;
protected String[] courses;

public ExampleClass() {
}

ExampleClass(String name) {

36
Core Java
// Body (Scope) of Constructor
this.name = name;
}

String determineAgeCategory(int age) {


// Body (Scope) of Constructor
}

String getAge() {
return age;
}

void setAge(int age) {


this.age = age;
}
}

37
Core Java

Chapter 8: Object Oriented Programming (Part 2)

38
Core Java
8.1 Inheritance (“IS A” relationship)

- Inheritance is a key concept in Object Oriented Programming (OOP), also defined as the “IS A” relationship between classes
- Graduate “IS A” Student, UnderGraduate “IS A” Student, Car “IS A” Vehicle, Truck “IS A” Vehicle
- Inheritance allows us a create a sub (child) classes from super (parent) classes to inherit properties of the super class
- With Inheritance, one super (parent) class can have multiple sub (child) classes that inherit from it
- Multiple Inheritance is a concept where one sub (child) class can have multiple super (parent) classes
- Multiple inheritance is NOT allowed in Java. Some programming languages like C++ allow multiple inheritance
- The extends Java keyword is used to define that a class is the child of a parent class
- The child class inherits all public and protected fields and methods of the parent class
- The child class does NOT inherit private methods of the parent class
- When a child class is created (instantiated) it must the call the constructor of the parent class first using the super() keyword
- Whenever, an instance of a subclass is created, an instance of the parent class is created

8.2 Aggregation or Contains (“HAS A” relationship)

- Contains is also a key concept in OOP, also defined as the “HAS A” relationship between classes
- Contains allow Classes to contain other classes as fields
- Car “HAS A” Engine, Car “HAS A” Steering Wheel, Student “HAS A” Name, Student “HAS A” Id
- A class can contain multiple fields of the same type, Aeroplane “HAS A” Engine1, Aeroplane “HAS A” Engine2

8.3 Overloading a method

- Overloading a method means creating multiple methods with the same name, but different signatures
- In Java, you can overload methods in the same class
- The signature of a method is a combination of the types of input arguments, and sequence order of its input parameters
- Sequence Order: (int a, String s) is different from (String s, int a)

8.4 Overriding a method

- Overriding a method means writing a new version of the same parent class method in a child class

39
Core Java

8.5 Polymorphism

- Polymorphism refers to a programs ability to use the correct method for an object based on its runtime type
- In other words, Polymorphism is the ability to use the overridden version of method of a subclass
- Static binding is when the type of the object is determined by the compiler at compile time
- Dynamic binding is when the type of object is determined during runtime (type of object is not known during compile time)
- Polymorphism is achieved through dynamic binding

8.6 Covariant Return Type

- The covariant return type specifies that the return type may vary in the same direction as the subclass
- i.e., it is possible to change the return type of an overridden method to a subclass of the return type of the parent method
- This is a new feature as of Java 5

8.7 Instance Initializer Block

- The Instance Initializer block is used to initialize the instance data members (fields) of an object
- It is executed during the creation (instantiation) of an object, before the constructor is executed
- Note: (1) super() is executed first, instance initializer is executed next, constructor of the class is executed last

8.8 The instanceof Operator

- The Java instanceof operator is used to test whether an object is an instance of the specified type (class or interface)
- The instanceof operator returns a Boolean value, true/false
- Sample syntax: car1 instanceof CAR

8.9 Abstract

- abstract is a Java modifier (keyword) that can be applied to parent classes or method’s in a parent class

40
Core Java
- An abstract class is strictly a base class for other sub classes to inherit (derive) from
- abstract classes can only be declared, and cannot be instantiated
- Only child classes of abstract super classes can be instantiated and initialized
- Similarly, abstract methods are the base declaration of a method for other sub class to define the behavior of the method
- In other words, abstract methods are methods that have no body, the body must be implemented in subclasses
- abstract methods can only be declared in abstract super classes

8.10 Interfaces

- Interfaces are like abstract classes and cannot be instantiated. Instead, they must be implemented by classes
- The Java keyword implements is used to specify that a class implements an interface
- Since Java does not allow multiple inheritance, interfaces provide a way to simulate multiple inheritance
- When a class implements an interface, it must implement all the methods of the interface
- By default all methods in an interface are abstract and public (no need explicitly specify abstract and public)
- All fields in an interface are public, static and final without having to specify these modifiers
- A class can extend (inherit) only one super class, but can implement many (zero or more) interfaces

8.11 Abstract Class Vs Interface

Abstract class Interface

1) Abstract class can have abstract and non-abstract Interface can have only abstract methods. Since Java 8, it can have default
methods. and static methods also.

2) Abstract class doesn't support multiple inheritance. Interface supports multiple inheritance.

3) Abstract class can have final, non-final, static and Interface has only static and final variables.
non-static variables.

41
Core Java
4) Abstract class can provide the implementation of Interface can't provide the implementation of abstract class.
interface.

5) The abstract keyword is used to declare abstract class. The interface keyword is used to declare interface.

8.12 Encapsulation

- Encapsulation is java is the process of wrapping data and code together into a single unit, and hiding data
- Data hiding is achieved through access modifiers and getters/setters

8.13 Object Cloning

- Object cloning is a way to create an exact copy of an object by using the Object.clone() method
- Cloning saves us the trouble of having to create, instantiate and initialize a new object copy

8.14 Call by Value Vs Call by Reference

- Java uses call by value for primitive data types, and call by reference for advanced data types (arrays and objects)
- Call by value means changes made to method parameters are local only to the scope of the method
- Whereas, call by reference means that changes made to method parameters reflect outside the scope the method

8.15 Annotations

- Annotations are metadata that we add to the code to provide extra information to the compiler
- Annotations start with the @ sign
- @Overriden is one such annotation that tells the compiler that a method from a parent class or interface is being overridden

public abstract class Student {

public int id;

42
Core Java
public Student(int id) {
this.id = id;
}

protected abstract String calculateGrade();


}

public Interface InternationalStudent {

public static final feeType = “International”;

public abstract boolean getVisaExtension();


public abstract String changeVisaType();
}

public class Graduate extends Student implements InternationalStudent {

public Graduate(int id) {


super(id);
}

@Overriden
public boolean getVisaType() {
// Implement body of the abstract method here
}
}
}

43
Core Java

Chapter 9: Collections (Iterable Interface)

44
Core Java
9.1 The Java Collections Framework

- The Java Collections Framework is a set of classes and interfaces to organize and manipulate groups of Objects
- Operations on data such as searching, sorting, insertion, deletion etc … can be performed using the Collections framework
- Classes and interfaces of the Collections framework are part of the java.util package

9.2 Wrapper Classes

- There are 8 primitive types in Java


- Java being an Object Oriented Programming language, and it is often required that we convert Java primitives to Objects
- To facilitate this conversion, Java provides what is known as Wrapper classes
- Each primitive type in Java has a corresponding Wrapper class
- Byte is the wrapper for byte
- Short is the wrapper class for short
- Integer is the wrapper class for int
- Long is the wrapper class for long
- Float is the wrapper class for float
- Double is the wrapper class for double
- Character is the wrapper class for char
- Boolean is the wrapper class for boolean

9.3 Autoboxing and Unboxing

- Since wrappers are Objects, to convert a primitive to a wrapper we have to declare, initialize and instantiate the wrapper
- And, to convert a wrapper to a primitive we have to call a method of the wrapper Object
- Since these commonly used in Java, Autoboxing and Unboxing are shortcuts provided perform these conversions
- Autoboxing is a shortcut to convert primitives to wrappers, and Unboxing is a shortcut to convert wrappers to primitives
- Wrapper classes also provide methods to convert Strings to primitives and vice versa

45
Core Java
Regular Conversion

Byte byteObject = new Byte(true);


Short shortObject = new Short(120);
Integer intObject = new Integer(1000);
Long longObject = new Long(8993456689L);
Float floatObject = new Float(102.35);
Double doubleObject = new Double(1200.25);
Boolean booleanObject = new Boolean(true);
Char characterObject = new Char(‘A’);

Byte bytePrimitive = byteObject.byteValue();


int intPrimitive = intObject.intValue();
short shortPrimitive = shortObject.shortValue();
long longPrimitive = longObject.longValue();
float floatPrimitive = floatObject.floatValue();
double doublePrimitive = doubleObject.doubleValue();
boolean booleanPrimitive = booleanObject.booleanValue();
char characterPrimitive = characterObject.charValue();

Autoboxing & Unboxing

Integer intObject = 1000;


Long longObject = 8993456689L;
Boolean booleanObject = true;

int intPrimitive = intObject;


long longPrimitive = longObject;
boolean booleanPrimitive = booleanObject;

46
Core Java
9.4 Iterable Interface

- The iterator interface provides the facility to iterate the elements in the Collections framework in a forward direction (only)

47
Core Java
9.5 Collection Interface

- The collection interface allows us to represent a group of Objects as a single unit of data

9.6 List Interface

- List Interface is the sub-interface of Collection.


- It contains methods to insert and delete elements based on an index

9.7 Queue Interface

- The Queue interface orders the element in FIFO(First In First Out) manner
- In FIFO, first element is removed first and last element is removed at last

9.8 Set Interface

- The Set interface allows to conatin only unique elements. No duplicates


- List and Queues allow duplicates, Sets do not

9.9 Deque Interface

- The Deque Interface is a sub-interface of Queue that supports element insertion and removal at both ends
- Deque is an acronym for "double ended queue"

9.10 SortedSet Interface

- The SortedSet Interface is a sub-interface of Set that supports elements of a Set in sorted order

48
Core Java
9.11 ArrayList

- ArrayLists implement the List interface


- ArrayLists use dynamic arrays to store elements
- ArrayLists can contain duplicate elements
- ArrayLists maintain insertion order
- ArrayList is non synchronized
- ArrayLists use random access because array works on the basis of an index
- ArrayList manipulation is slow because lot of shifting occurs when elements are removed from the List

9.12 LinkedList

- LinkedList implements the List, Queue & Deque interfaces


- Java LinkedList uses the linked list datastructure to provide a doubly linked list to store data
- LinkedLists can contain duplicate elements
- LinkedList maintains insertion order
- LinkedList is non synchronized
- LinkedList manipulation is fast because no shifting needs to occur
- LinkedList can be used as a stack or queue

9.13 Vector

- Vector implements the List interface, and are much like ArrayLists with some differences
- Vectors use dynamic arrays to store elements
- Vectors can contain duplicate elements and maintain insertion order
- Vectors is synchronized
- Vectors use random access because array works on the basis of an index
- Vectors manipulation is slow because lot of shifting occurs when elements are removed from the List

49
Core Java
9.14 Stack

- Stack represents a last-in-first-out (LIFO) stack of Objects.


- Stack extends Vector with 5 operations that allow a vector to be treated as a stack

9.15 PriorityQueue

- PrioriyQueues implements the Queue interface


- PriorityQueues are Queues (FIFO’s, insert from the back, and remove from the front), but with a priority

9.16 ArrayDeque

- ArrayDeque implements the Deque interface


- ArrayDeque provides the facility of a Deque using an ArrayList
- Unlike Queue’s, with Deques, we can insert and remove values from both ends (FIFO + LIFO)
- Deques are not synchronized
- ArrayDeques are faster than liked lists and stacks

50
Core Java

Chapter 10: Collections (Map Interface)

51
Core Java
10.1 The Java Collections Framework

- The map interface of the Java Collections Framework


- However, note that the Map Interface is NOT a subset of the Collection Interface
- Therefore, ßMap behaves differently than other Collection types

52
Core Java
10.2 Map Interface

- A map contains values on the basis of a key value pair known as an entry in the map
- Map contains only unique keys

10.3 SortedMap Interface

- SortedMap interface extends the Map Interface


- SortedMap interface provides an ordering of it’s elements
- Elements can be traversed in sorted order of keys

10.4 NavigatableMap Interface

- NavigatableMap interface extends the SortedMap Interface


- NavigatableMap provides convenient navigation methods like lowerKey, floorKey, ceilingKey and higherKey
- It also provides ways to create a sub map of an existing map from a fromKey and toKey
- headMap whose keys are less than the specified key
- tailMap whose keys are greater than the specified key

10.5 Hashtable

- Hashtable contains values based on a key, i.e key/value pairs


- Hashtable implements the Map interface
- Hashtable contains unique elements, no duplicates
- Hashtable does not allow null keys or values
- Hashtable is syncronized
- Hashtable has been deprecated in the recent Java versions (HashMaps are used instead)

53
Core Java
10.6 HashMap

- HashMap implements the map interface


- A Hashmap contains values based on a key, i.e. key/value pairs
- Hashmap contain only unique elements, no duplicate keys or values
- It may have a null key and multiple null values
- It maintains NO order, it is not ordered

10.7 TreeMap

- TreeMap implements the map interface


- A TreeMap contains values based on a key, i.e. key/value pairs
- It provides an efficient means of storing key/value pairs in sorted order
- A TreeMap only unique elements, no duplicates
- It cannot have a null key, but can have multiple null values
- It is the same as a HashMap, only difference is that it maintains keys in ascending order

54
Core Java

Chapter 11: Multithreading

55
Core Java

11.1 Multithreading Vs Multiprocessing

- Multithreading in Java is the process of executing multiple threads in Java


- Thread is a lightweight sub-process, a smallest unit of processing
- Sub-process means each process has multiple threads
- Multithreading and Multiprocessing are both used for multitasking to save time and execute tasks in parallel
- With Multiprocessing separate memory is allocated for each process
- Where as, with Multithreading, a common memory is shared between threads, and therefore thread context switching is fast
- In Java, we mostly use Multithreading, because for multiprocessing you will need to run multiple JVM’s

11.2 Lifecycle of a Thread

- In Java, a thread has five states


- New: When a new thread is created, it is in a new state
- Runnable:A thread that is ready to run is in a runnable state
- Blocked / Waiting: A thread is in a blocked or waiting state if it is waiting for another thread to complete a task
- Timed Waiting: A thread is in a timed waiting state if a thread is explicitly set to wait for a certain period of time
- Terminated: A thread is in a terminated state, when it has completed etiher successfully or due to an exception
- Methods in the thread class are used to control thread states, sleep(), wait(), notify(), notifyAll() etc …

11.3 Thread Vs Runnable

- Since Java does not allow multiple inheritance, Runnable is an interface that can be implemented for thread functionality

11.4 Synchronization

- Synchronization in Java is a process by which multiple threads can access shared resources
- The synchronized keyword / access modifier can be applied to static variables, methods or blocks of code within a method
- Synchronization is used to prevent thread interference and prevent inconsistency when accessing shared resources

56
Core Java
Extending the Thread Class

public class MultiThreadingDemo extends Thread {

public void run() {


// Do Task
}
}

Implementing the Runnable Interface

public class MultiThreadingDemo implements Runnable {

public void run() {


// Do Task
}
}

Creating & Starting a new Thread

MultiThreadingDemo mtdThread = new MultiThreadingDemo();


For a subtype of thread: mtdThread.start();
For implementation of Runnable: mtdThread.run();

Putting a thread in a timed waiting state in millseconds

mtdThread.sleep(200);

57
Core Java
11.5 Executor Service

- Java thread pool represents a group of worker threads that are waiting to do a job, and can be re-used multiple times
- In the case of thread pool, a fixed group of threads are created
- A thread from the thread pool, is pulled out and assigned a job by the service provider
- After completing a job, the thread is contained in the thread pool again and waits the next request
- The Executor interface provides for thread pool management in Java, like max limit of threads, re-use of threads etc …
- Creation of new threads is an expensive process, and therefore re-use improves the performance of the application
- A good example of thread pool usage is a servlet waiting for incoming requests

ExecutorService executor = Executors.newFixedThreadPool(5);

for(I nt i=0; i<20; i++) {


Runnable worker = new WorkerThread();
Executor.execute( worker );
}

executor.shutdown();

while( !executor.isTerminated() ) { };

58
Core Java

Chapter 12: Other Concepts

59
Core Java

12.1 Other Core Java Concepts to be Learnt by Implenting Projects (Self Learning)

- Java Date Object


- Regex and Pattern Machers
- Java IO, InputStreams, OutputStreams and File Handling
- Java Reflection
- Java JDBC
- Java Generics
- Enum
- Lambda Expressions
- Java Networking
- Java Mail API
- RMI
- Internationalization

60

S-ar putea să vă placă și