Documente Academic
Documente Profesional
Documente Cultură
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
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
3
Core Java
1.4 Features of Java
1.4.1 Simple
1.4.2 Object-Oriented
4
Core Java
- use of OOP concepts like Class, Object, Inheritance, Polymorphism, Abstraction and Encapsulation
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
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 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
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 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
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
11
Core Java
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
14
Core Java
float hourlyBillingRate = 60.75;
double noOfHours = 160.50;
char grade = ‘A’;
boolean promote = true;
15
Core Java
Additive +-
Equality == !=
bitwise exclusive OR ^
bitwise inclusive OR |
logical OR ||
Ternary Ternary ?:
16
Core Java
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)
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;
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;
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
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 “\”
Instantiation
- String exampleString = new String();
Initialization
- String exampleString = new String(“Hello World”);
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
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
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
References
Java documentation for java.util.Arrays.java
https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html
25
Core Java
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
27
Core Java
6.2: Decision Making Statements
If Else Statement
Ternary Statement
28
Core Java
Switch Statement
- 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 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 );
- 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
}
32
Core Java
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
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
- 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
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
7.10 Final
public ExampleClass() {
}
ExampleClass(String name) {
36
Core Java
// Body (Scope) of Constructor
this.name = name;
}
String getAge() {
return age;
}
37
Core Java
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
- 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
- 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)
- 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
- 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
- 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
- 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
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
- 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
- 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
42
Core Java
public Student(int id) {
this.id = id;
}
@Overriden
public boolean getVisaType() {
// Implement body of the abstract method here
}
}
}
43
Core Java
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
- 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
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
- 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
- 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"
- The SortedSet Interface is a sub-interface of Set that supports elements of a Set in sorted order
48
Core Java
9.11 ArrayList
9.12 LinkedList
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
9.15 PriorityQueue
9.16 ArrayDeque
50
Core Java
51
Core Java
10.1 The Java Collections Framework
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.5 Hashtable
53
Core Java
10.6 HashMap
10.7 TreeMap
54
Core Java
55
Core Java
- 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
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
executor.shutdown();
while( !executor.isTerminated() ) { };
58
Core Java
59
Core Java
12.1 Other Core Java Concepts to be Learnt by Implenting Projects (Self Learning)
60