Java Basics

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 23

Java

Java development Kit


1) Programming Language
2) Runtime Environment
3) Standard Library
Example of Java Code (Hello.java):
public class Hello{ // class declaration
public static void main(String[] args) { // main method
System.out.println(“Hello PluralSight!”);
}
}
Compiling and Running Java Code
Hello.java
(javac)
Hello.class (bytecode for application)
(Run)
java (Name of Class in java program)
 bytecode sits on top of Standard Library (Java Standard Edition (SE)
APIs)
 Java Virtual Machine (JVM) use to run java code. It is runtime
environment of Java.
Software Needed:
1) Download JDK (oracle.com/technetwork/java/javase)
2) Eclipse IDE
Java Developers do develop-
a) Web-applications
b) Backend services
c) Data-intensive applications
Classes > Packages > Modules
Java Usage
a) Desktop Java
b) Enterprise Java
c) Java in Cloud
Popular Java Libraries
 Spring Framework
Commonly Used Libraries in Java
- Utility (Google Guava , Apache Commons, Apache Log4J)
- Distributed system (Netty, Akka, RxJava- Reactive programming,
Apache Camel)
- Data-access (JDBC java database connectivity Drivers – MySQL,
Postgres, Oracle, H2)
Object Relational Mappers ORMs- Hibernate, EclipseLink – pure Java
Objects used.
SQl DSLs(domain specific) – jOOQ, QueryDSL
Java-based Data Processing
- Big Data Processing (Apache Hadoop, Apache Spark, DL4J- Deep
Learning for Java( for face or object detection)
- Cassandra – NoSQL data base in Java
- Neo4J – Graph Database written in Java
- ElasticSearch
- Hadoop Distributed File System (HDFS)
IDEs (Integrated Development Environment) – Eclipse, IntelliJ
Unit Testing – JUnits
Build Tools – Maven, Gradle
Jenkins in Java based CI (Continuous Integration) Server
Static Code Analysis
- Checkstyle
- Spotbugs
- PMD
SonarCube (Continuous Inspection)
Alternative JVM Languages – Scala results in same bytecode as JVM, Kotlin
Reasons- productivity, familiarity, different paradigms
1) Groovy – Dynamic scripting language (opt-in type system, concise but
still close to Java)
2) Scala – Combines OO(Object Oriented) programming with Functional
Programming ( compiled language , Akka, Spark written in Scala)
3) Kotlin – A ‘better Java’ (null safety, data classes), used for Android
development, also runs in browser.
Java Development Environment
Java applications are packaged into JAR files where JAR stands for Java
Archive. It contains applications classes.
Build Tools
1) Build
2) Test
3) Analyse
4) Package
It is JRE (Java Runtime Environment) that helps Java App to run in host
environment.
/** … */ Javadoc comment (can be used to generate documentation)
Package Naming Conventions – use reverse domain name notation to assure
global uniqueness. , add further qualifiers to assure uniqueness within a
company or group.
Variables
final int maxStudents =25;
maxStudents = 100 ; // error as final declared variables can’t be modified.
Primitive Types (they represent data only)
- Integer Types (byte, short , int , long)
- Floating point types (float, double)
- Character type
- Boolean type
Operators
Prefix applies operation before returning value.
Postfix applies operation after returning value.
Compound – Apply right side to left.
Precedence: x++, x--, ++x, --x, *, /, %, +, - (left – right evaluation for equal
precedence)
Conversion -:
Implicit type conversion- Conversion automatically performed by compiler.
int intValueOne=50;
long longValueOne = intValueOne;
Explicit type conversion- Conversion performed explicitly in code with cast
operator.
long longValueTwo =50;
int intValueTwo = (int) longValueTwo;
Order of datatypes: float -> double -> byte -> short -> long
Conditional Logic Operators: &&, true && true = TRUE
||, false || true = TRUE, true || --- = TRUE
Primitive data types – supported for switch statement.
Arrays in Java
float[] theVals =new float[3]; //Array declaration
int[] vals = {1,2};
Index range from 0 to number-of-elements minus 1.
// For Each Loop Example
int[] val={1,2};
for(int num : val)
{
int sum+=num;
}
String Class
intern() method used to for checking equality of two strings.
// for input
Import java.util.Scanner;
Scanner scanner = new Scanner(System.in);
Scanner.nextline();
StringBuilder – Provides mutable string Buffer (append/insert) , uses
toString to extract string content.
String.format // works on different string formats
Format Flags:
# : include radix
0 : zero-padding
- : Left justify
, : include grouping separator
space: leading space when positive number
+ : always show sign
( : enclose negative values in parenthesis

Revise (7, 8, 9 module of Getting started with


programming in Java)
Argument Index
Not specified: Corresponds sequentially to argument
index$ : Index of argument to use (1-based)
< : corresponds to same argument as previous format specifier
Data and Time in Java
Instance Class:
- optimized for time- stamping events
- can be converted into more complex date/time types.
DateTimeFormatter : can be used when converting to string , can be used
when parsing from string.
Primitive wrapper classes: they can hold primitive data values and provide
methods, and each primitive types has its own wrapper classes. They used
convert to from other types and finding min max values
Classes and Interfaces
Classes – contains state, contains code to manipulate that state, allow us to
create custom data types.
Interfaces – model data type behaviour, create contracts between data types.
Date and Time API in Java
java.time Meaning Example
Instant Instant of time timestamp
ZonedDateTime date-time with time start of a conference
zone information call
LocalDate date without time zone birthday
information
Duration time between two length of a conference
instants call
Period amount of time in Length of a prison
years, months, and sentence
days

DateTimeFormatter : java.time .format(..)

.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<>();

We can use any type of list (LinkedList , MyList…) inplace of it.


List can hold any type of objects
For Example:
List of Integers
List<Integer> numbers = new ArrayList<>();
List<MyProduct> products =new LinkedList<>();

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

languages.add(“CSS”); // ignored as Set store only unique values

System.out.println(languages.size()); // 3

for(String language : languages)

System.out.println(language);

} // HTML CSS JS

In Java , a Set’s retainAll() method returns the intersection of two Sets

In Java , a Set’s addAll() method returns the Union of two Sets

Set is alphabetically remains in sorted order.

List<String> combined = new ArrayList<>(Arrays.asList(languages));

for(String language : moreLanguages)

if(!combined.contains(language))

combined.add(language);

combined.sort(String::compareTo);

Set<String> combinedSet = new HashSet<>(Arrays.asList(languages));

combinedSet.addAll(Arrays.asList(moreLanguages));
Maps in Java

An unordered group key value pairs that are indexed by a key.

Key must be unique and value can be repeated.

Map<String, Integer> courseByLanguage = new HashMap<>();

courseByLanguage.put(“HTML”,5);

System.out.println(courseByLanguage.size()); // returns size


System.out.println(“Number of HTML courses”courseByLanguage.get(“HTML”));

containskey(); --method

Iterating through the Map Entries

for(Map.Entry<String, Integer> entry: languagesCount.entrySet()){

System.out.format(“ %d %s courses%n” , entry.getValue() ,entry.getKey());

// keyset() returns a Set and Sets have unique values.

System.out.println(“The languages we teach are: ” + languagesCount.keySet());

 Hashmap- no order is guaranteed


 LinkedHashMap- insertion order is preserved
 TreeMap – elements are in sorted order by key

Lambda in Java

List<Integer> items = new ArrayList<>();

items.add(1);

items.add(2);

items.add(3);

items.forEach(System.out::println);

items.forEach(item->System.out.println(item*item)); // here this lambda


expression will print square of each item in the list
A Lambda Expression allows you to pass code as an argument in a concise,
readable way.

Arrays.sort(words, …); //default string comparator for sorting

Interface Comparator <T> {

int compare( T o1, T o2);// it takes two strings inp

Arrays.sort(words, (s1,s2) -> Integer.compare(s1.length(), s2.length()));

System.out.println(Arrays.toString(array));

The Cleaner Lambda Expression version

Arrays.sort(words,(s1,s2)-> Integer.compare(s1.length() , s2.length()));

System.out.println(Arrays.toString(words));

Java 11 Core Libraries: Java Log System

When to use Logging:

---Exceptions and Errors, Events and States, Debug info, HTTP requests,
Thread usage, Frontend errors.

Why Logging:

---Trouble shooting, performance analytics, Auditing

Logging is the act of writing information about events in the application to a


file, also called the log file.

Logging levels

-Severe

-Warning

-Info

-Config
-Fine

-Finer

-Finest

Log Handlers

Sends the message to the log place.

Handlers format the message using a formatter

Types of Handler

1) Consolehandler
2) FileHandler
3) StreamHandler
4) SocketHandler
5) MemoryHandler

Log Formatters change the structure of the log message.

1) SimpleFormatter – human readable way of depicting the log message.


2) XMLFormatter – Write log message to standard XML format

Collections in Java

Map
List Set Queue
HashMap
(ArrayList, (HashSet) (Priority Queue)

LinkedList)

Sorted Set Deque SortedMap


TreeMap
(TreeSet) (LinkedList, ArrayDeque)

Set – Order is not important, elements must be unique

SortedSet- Order is important , elements must be unique

Map – Elements are keyed, order is not important

SortedMap – Elements are keyed , order is important


List- Insertion orders does not matters

Deque- Insertion order matters.

------------------------------------------------------------------------------------------------
size()- get the number of elements in the collection

isEmpty()- true if size() == 0, false otherwise

add() – Ensure that an element is in the collection

addAll()- add all the elements of the argument collection to this collection

contains(element)- True if the element is in this collection, false otherwise

containsAll(collection) – True if all the elements of the argument collection are


in this collection

clear()- Remove all elements from this collection.

Java Fundamentals- Http Client API

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.

HttpClient types live in java.net.http package.

HttpClient: send , sendAsync… newBuilder (HttpClient.Builder)

HttpRequest: uri, headers, method …… newBuilder (HttpRequest.Builder)

HttpResponse : uri, headers, statusCode , body …

Synchronous HTTP Requests

- send(HttpRequest, request, HttpResponse.BodyHandler<T>


responseBodyHandler) throws IOException, InterruptedException

HttpResponse<T>
BodyHandlers

ofString() – String
ofByteArray() – byte[]
ofFile(Path) – Path
ofLines() – Stream<String>
discarding() – Void

Asynchronous HTTP Requests


sendAsync(HttpRequest request, HttpResponse.BodyHandler<T>
responseBodyHandler)

CompletableFuture<HttpResponse<T>>

Stream API in Java


The key point of the stream API is an implementation of the
map/filter/reduce algorithm that does not duplicate any data and that does
not create any load on the CPU or on the memory.
These are two kinds of methods on stream.
1) Methods that crate another stream
2) Method that produce a result.
Stream <T> and IntStream

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.

// Do read Foreign Key on your own once

First Normal Form Rule (1NF):

Table must not contain repeating groups of data in 1 column.

Eliminates repeating groups. No duplicate records exist in table and no multi-


valued attributes. All entries in column are of same data type.

Second Normal Form Rule (2NF):

Tables must not contain redundancy (unnecessary repeating information). Table


is already in 1NF, all the partial dependencies are removed to another table(s).

Third Normal Form (3NF)


Table is already in 2NF, eliminate non-dependent columns and transient
dependencies.

Fourth Normal Form (4NF)

Already in 3NF, no independent multiple relationships

Fifth Normal Form (5NF)

Already in 4NF, isolate semantically-related relationships.

Relationships:

1) One-to-One
2) One-to-Many
3) Many-to-Many

Data Types in SQL

char, varchar, text, nchar, nvarchar, ntext

nchar – Fixed-length string data , nchar[(n)] n defines the string length in


byte-pairs and n=1 to 4,000 (n* 2 bytes)

nvarchar- variable-length string data, nvarchar[(n)] defines the string length


in byte-pairs and n=1 to 4,000 (n*2 bytes)

ntext- Variable-length Unicode data with n=0 to 2^30-1(n * 2 bytes)

char – fixed-length string data

varchar – Variable-length string data, varchar[(n)] has a length of n= 1 to


8,000, varchar [(max)] has a length of n=1 to 2^31-1 (2GB), Storage is the
actual length of the data in bytes.

Normalisation: Resolving issues of data redundancy and improving storage


efficiency, data integrity, scalability. It helps to reduce insert, update, and delete
anomalies.

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.

Database Permissions (Data Control language)

GRANT – Positive privilege

DENY – Negative privilege that overrides GRANT

REVOKE – Negate a GRANT or DENY

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

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:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy