Java Basics
Java Basics
Java Basics
.parse(..) String
java.time interopearation
java.util classes
- Date.from(Instant)
- Date.toInstant()
- Calender.toInsatnt()
- timeZOne.toZoneId()
- TimeZone.getTimeZone(ZoneId)
java.sql classes
- Date LocalDate
- Timestamp LocalDateTime
- Timestamp Instant
JPA (Java Persistent API) – Attribute Converter.
Dealing with Errors
Exception handling relies on try/catch blocks.
Try block: contains “normal” code to execute, runs to completion when no
exceptions, Exits block if exception thrown.
Catch block: contains error handling code, runs only if matching exception is
thrown, receive exception information.
Handling Cleanup
- Tasks often require cleanup, close file, database, etc. May be needed even
if exception even if exception occurs.
- Finally block: can be added at end of try/catch, runs in all cases following
try or catch.
Classes and Interfaces in Java 11
Declaring and using classes
Constructors and initializers
Class inheritance
Declaring and implementing interfaces
Nested types and anonymous classes
A class is a template for creating objects.
class Flight {
//class members
int passengers;
int seats;
Flight() {
seats=150;
passengers =0;
}
void add1Passenger() {
if(passengers<seats)
passengers+=1;
}
}// Java source file name normally has same name as class (Flight.java)
It contains
Fields: Store object state
Methods: Executable code that manipulates state and performs operations.
Constructors: Executable code used during object creation to set initial state.
Using Classes:
Use the new keyword to create a class instance (a.k.a. an object)
- Allocates the memory described by the class, and runs the constructor
- Returns a reference to the allocated memory
Encapsulation and Access Modifiers
The implementation details of a class are generally hidden, this concept is
encapsulation.
Java uses access modifiers to achieve encapsulation. Control member visibility.
Modifiers Visibility Usable on Classes Usable on
Members
No access Only within its Y Y
modifier own package
(a.k.a. package
private)
public Everywhere Y Y
private Only within the N* Y
declaring class
*As private applies to top-level classes;
- private is available to nested-classes
Special References
this - implicit reference to current object , useful for reducing ambiguity, allows
an object to pass itself as a parameter.
null – Represents an uncreated object, can be assigned to any reference variable
public class Flight {
private int passengers;
private int seats;
// other members elided for clarity
public Boolean hasRoom(Flight f2) {
int total = this.passengers + f2.passengers;
return total <= seats;
}
}
Accessor- retrieves field value, also called getter. Method name: getFieldName
Mutator- modifies field value, also called setter. Method name: setFieldName
Constructors
Code that runs during object creation.
- Named same as the class
- No return type
Initialization Blocks
1) Share code across all constructors
- Cannot receive parameters
- Place code within brackets outside of any method or constructor
2) A class can have multiple
- All always execute
- Execute in order starting at the top of the source file
Static Members: They are shared class-wide. Not associated with individual
instance. It is declared using static keyword. It is accessible using class name.
Static Initialisation blocks: Perform one-time type initialisation. Execute
before type’s first use.
Passing Objects as Parameters
Passed “by reference” – Parameter receives a copy of the reference.
Changes to the reference – Visible within method, not visible outside method.
Changes to members – Visible within method, visible outside method.
Overloading: Multiple versions of a method or constructor within a class.
Every constructor and method must have a unique signature.
Class Inheritance: Use extends keyword , Derived has characteristics of base,
Derived can add specialization.
class CargoFlight extends Flight{
float maxCargoSpace = 1000.0f;
float usedCargoSpace;
}
Object Class: Root of the Java class hierarchy
- Every class has characteristics of Object
- Object references can reference any array or class instance
Inheriting from Object
Every class inherits directly or indirectly from the Object class
Object Class Methods:
clone: Create a new object instance that duplicates the current instance
hashCode: Get a hash code for current instance
getClass: Return type information for the current instance
finalize: Handle special resource cleanup scenarios
toString: Return a string value representing the current instance
equals: Compare another object to the current instance for equality
Override equals
public class Flight{
private int flightNumber;
private char flightClass;
@Override
public Boolean equals(Object o){
Flight flight = (Flight) o;
return flightNumber == flight.flightNumber && flightClass ==
flight.flightClass;
}
}
// Example 2 //
Flight f1 = new Flight(175);
Flight f2 = new Flight (175);
if(f1==f2) //false
//do something
if (f1.equals(f2)) //true
//do something
Passenger p = new Passenger();
if(f1.equals(p)) //false
// do something
________________________________________________________________
Special Reference: super
- Refers to current object (Similar to the special reference this)
Has a key difference from this
- Treats as an instance of the base class
- Provides access to overridden base class members
Default inheritance behaviour
- Each class can be extended
- Derived class can override any method
Can change default behaviour with final
- Can prevent class extending
- Can prevent method overriding
Can explicitly call a base constructor using super keyword.
Constructors
Constructors are not inherited
- Each class has its own constructors
Constructing a derived class instance
- A base class constructor always called
- By default calls no-argument version
- Can explicitly call specific constructor
Enumeration Types
Useful for defining a type with a finite list of valid values
- Declare using the enum keyword
- Provide comma-separated value list
- By convention value names are all upper case
public enum FlightCrewJob{
FLIGHT_ATTENDANT,
COPILOT,
PILOT
}
Enums supports equality tests
- Can use == and != operators
Enums supports switch statements
Use compareTo for relative comparison
- Returns negative, zero, or positive value
- Indicates current instance’s ordering relative to another value
Common Enum Methods
values - Returns an array contain all values
valueOf – returns the value that corresponds to a string (case sensitive)
Enum Types are Classes
- Implicitly inherit from Java’s Enum Class
- Similar to other class in some ways
Interfaces- provides a list of operations. Does not focus on implementation
details
Classes implement interfaces, express conformance to contract. Provide
necessary methods
- compareTo
- Receives a reference to another object
- Indicates ordering between current object and received object
- Return negative value- current is ordered first.
- Returns Positive value- received is ordered first
- Returns zero value- current and received are equal.
Implementing a Generic Interface
Some interfaces support additional type information
- Use a concept known as generics
- Allows strong typing
public interface Comparable<T> {
int compareTo(T o);
}
An interface can extend another (uses extends keyword)
Implementing a derived interface (Implies implementation of the base)
An interface provides a list of operations.
Not focused on implementation details
Classes implement interfaces
- Express conformance to contract
- Provide necessary methods
Generic interfaces
- Allows stronger typing and specialising interface on a type
Nested Type Classes
- A type declared within another type
- Are members of the enclosing type ( Nested type can access private
members of enclosing class)
- Nested types support all access modifiers
- 1) No modifier (a.k.a package private)
- 2) public
- 3) private
- 4) protected
Two broad categories
- One provides only naming scope
- The other links type instance
Inner Classes
- Type name scoped within enclosing type
- Creates instances relationship
- Each instance of nested class associated with an instance of enclosing
class
Applies to the following nested type
- Non-static classes nested within classes
Anonymous Classes
- Declared as part of their creation
- Use as simple interface implementation
- Use new keyword with base class or interface name
- Place parenthesis after name
OOPs in Java
Generics
Collections can contain any object – We can add both strings and integers.
A List containing only Strings. Generics stop runtime errors at compile time.
Java Lists
A java List inherits from a Collection, which is a very general container for any
Java Objects
A Collection is an Interface, like a Blueprint, that says you MUST implement
these methods to be a Collection.
LIST – An ordered group of values that are indexed numerically.
SET – A group of unique values without an index.
List is abstract cannot be instantiated. So we use non-abstract lists (already
present in Java like ArrayList, LinkedList, Vector,Stack) to initialise LIST.
List <String> languages = new ArrayList<>();
Object of List
Example:
List<String> languages = new ArrayList();
languages.add(“Java”); // add is method of inserting List
langiuages.add(“Python”);
System.out.println(languages.size()); // prints 2 in console
// Alternate method to print
for(String language : languages)
System.out.println(language);
indexOf – method to index of value
remove – method to delete particular index
Object[] langsArray = languages.toArray();
String[] langsArray = languages.to Array(new String[0]);
List<String> someLangs = languages.subList(0,3);
inclusive exclusive
someLangs.set(2,”Groovy”); // this also changed in original list
Sets in Java
A java Set inherits from a Collection, which is a general container for any Java
Objects. Set inherits its methods from the Collection interface, but has
additional rules on some methods. For example add() must add only unique
values.
Set<String> languages = new Set<String>(); // Set is abstract cannot be
instantiated
We need HashSet, TreeSet, EnumSet
Set<String> languages= new HashSet<>()
General what is in set Specific leave string out here, it’s inferred
set interface type of set
--Example –
Set<String> languages = new HashSet<>(Arrays.asList(“HTML”,”CSS”,”JS”));
languages.add(“HTML”); // ignored as Set store only unique values
System.out.println(languages.size()); // 3
System.out.println(language);
} // HTML CSS JS
if(!combined.contains(language))
combined.add(language);
combined.sort(String::compareTo);
combinedSet.addAll(Arrays.asList(moreLanguages));
Maps in Java
courseByLanguage.put(“HTML”,5);
containskey(); --method
Lambda in Java
items.add(1);
items.add(2);
items.add(3);
items.forEach(System.out::println);
System.out.println(Arrays.toString(array));
System.out.println(Arrays.toString(words));
---Exceptions and Errors, Events and States, Debug info, HTTP requests,
Thread usage, Frontend errors.
Why Logging:
Logging levels
-Severe
-Warning
-Info
-Config
-Fine
-Finer
-Finest
Log Handlers
Types of Handler
1) Consolehandler
2) FileHandler
3) StreamHandler
4) SocketHandler
5) MemoryHandler
Collections in Java
Map
List Set Queue
HashMap
(ArrayList, (HashSet) (Priority Queue)
LinkedList)
------------------------------------------------------------------------------------------------
size()- get the number of elements in the collection
addAll()- add all the elements of the argument collection to this collection
Http is a request- and response- based protocol where some client performs an
http request to an http server and in turn server returns an http response.
HttpResponse<T>
BodyHandlers
ofString() – String
ofByteArray() – byte[]
ofFile(Path) – Path
ofLines() – Stream<String>
discarding() – Void
CompletableFuture<HttpResponse<T>>
SQL
A primary key is the single constraint that ensures both UNIQUE and
NOT NULL property.
A foreign key is a column in one table that references the primary key
column of another table.
Relationships:
1) One-to-One
2) One-to-Many
3) Many-to-Many
Primary Key- Uniquely identifies each record in a table. Cannot contain NULL
values, must be UNIQUE. Only one primary key per table, using single or
multiple fields.
Foreign Key – Not just to a primary key constraint in another table, can
reference columns of a UNIQUE constraint in another table.
- Can only reference tables within the same database on the same server.
- Self-reference is allowed to reference another column in the same table
- Column level constraint must list only one reference column and be the
same data type.
- Table-level constraint needs same number of reference columns and data
types.
Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.
Alternative Proxies: