Intro
Java is used to develop mobile apps, web apps, desktop apps, games and more.
Why Java?
PATH and CLASSPATH variables need to be set to run Java programs
To check if Java is installed, in cmd/terminal type> java --version
Why Java?
- Can be used on different platforms
- Open-source and free
- OOP which gives a clear structure to programs and allows code to be reused, lowering development costs
PATH and CLASSPATH variables need to be set to run Java programs
To check if Java is installed, in cmd/terminal type> java --version
Basics
Basics
|
public class Main {
public static void main(String[] args) { System.out.println("Hello World"); } } |
// To run this file, navigate to its path in terminal/cmd
> javac Main.java > java Main Hello World |
/* All lines of code must be in a class. A class should always start with an upper-case first letter. The main() method is required for every Java program and any code inside it will be executed. System and out are built-in java classes. Always use double quotes to print strings
*/
*/
|
Java Variables
|
int myNum = 15; myNum = 20; // myNum is now 20 final int myNum = 15; myNum = 20; // error: cannot re-assign value to final variable // Assigning same value to multiple variables int x, y, z; x = y = z = 50; |
|
Primitive Data Types
* 1 byte = 8 bits
-
|
* Wrapper classes provide a way to use primitive data types as objects - Just capitalize the first letter (except int) int => Integer byte => Byte ... |
|
Non-primitive data types are called reference types because they refer to objects. With the exception of String, non-primitive types must be defined by the programmer. All primitive types are predefined in Java.
Non-primitive data type ex: Arrays, Classes, Interface, etc. |
Non-Primitive Data type
|
-
Java Type Casting
- assigning a value of one primitive data type to another type
- 2 types of casting:
- assigning a value of one primitive data type to another type
- 2 types of casting:
- Widening Casting (automatically) - converting a smaller type to a larger type size
- byte -> short -> char -> int -> long -> float -> double
- // Ex:
- int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
System.out.println(myInt); // Outputs 9
System.out.println(myDouble); // Outputs 9.0 - -
- Narrowing Casting (manually) - converting a larger type to a smaller size type
- double -> float -> long -> int -> char -> short -> byte
- // Ex:
- double myDouble = 9.78d;
int myInt = (int) myDouble; // Manual casting: double to int
System.out.println(myDouble); // Outputs 9.78
System.out.println(myInt); // Outputs 9 - -
|
Coding in Java with Strings
String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; System.out.println("The length of the txt string is: " + txt.length()); String txt = "Hello World"; System.out.println(txt.toUpperCase()); // Outputs "HELLO WORLD" System.out.println(txt.toLowerCase()); // Outputs "hello world" String txt = "Please locate where 'locate' occurs!"; System.out.println(txt.indexOf("locate")); // Outputs 7 because 0 is the first position String firstName = "Kannika"; String lastName = "Kabilar"; System.out.println(firstName + " " + lastName); String firstName = "Kannika "; String lastName = "Kabilar"; System.out.println(firstName.concat(lastName)); String x = "10"; String y = "20"; String z = x + y; // z will be 1020 (a String) String x = "10"; int y = 20; String z = x + y; // z will be 1020 (a String) // To use special characters in a String use escape character \ // \' => ' ; \" => " ; \\ => \ ; \n => newline ; \r => Carriage Return ; \t => tab ; \b => backspace String txt = "He\'s called \"The Chopper\" because he cuts fruits\\vegetables."; // For-Each loop String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; for (String i : cars) { System.out.println(i); } |
Math in Java
Math.max(5, 10); // Math.min(5, 10); Math.sqrt(64); Math.abs(-4.7); int randomNum = (int)(Math.random() * 101); // 0 to 100 // Shortcut of if.. else.. // variable = (condition) ? expressionTrue : expressionFalse; int time = 20; String result = (time < 18) ? "Good day." : "Good evening."; System.out.println(result); // Switch int day = 4; switch (day) { case 6: System.out.println("Today is Saturday"); break; // optional - allows to break out of switch block and // not continue executing other cases case 7: System.out.println("Today is Sunday"); break; default: System.out.println("Looking forward to the Weekend"); // optional - if no case block were matched, default block gets executed } // Outputs "Looking forward to the Weekend" // do/while loop gets executed at least once while may never get executed even once int i = 0; do { System.out.println(i); i++; } while (i < 5); |
Exercises
// Count words in a JavaString
String words = "One Two Three Four";
int countWords = words.split("\\s").length;
System.out.println(countWords);
// Reverse a String in Java
String originalStr = "Hello";
String reversedStr = "";
for (int i = 0; i < originalStr.length(); i++) {
reversedStr = originalStr.charAt(i) + reversedStr;
}
System.out.println("Reversed string: "+ reversedStr);
// Count words in a JavaString
String words = "One Two Three Four";
int countWords = words.split("\\s").length;
System.out.println(countWords);
// Reverse a String in Java
String originalStr = "Hello";
String reversedStr = "";
for (int i = 0; i < originalStr.length(); i++) {
reversedStr = originalStr.charAt(i) + reversedStr;
}
System.out.println("Reversed string: "+ reversedStr);
Arrays in Java
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
System.out.println(cars[0]);
// Now outputs Opel instead of Volvo
System.out.println(cars.length);
// Outputs 4
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
myNumbers[1][2] = 9;
System.out.println(myNumbers[1][2]); // Outputs 9 instead of 7
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
System.out.println(cars[0]);
// Now outputs Opel instead of Volvo
System.out.println(cars.length);
// Outputs 4
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
myNumbers[1][2] = 9;
System.out.println(myNumbers[1][2]); // Outputs 9 instead of 7
Methods
Java methods can only return primitive data types
Method overloading & Block scope
Method Overloading
Multiple methods can have the same name with different (type/amount of) parameters
static int plusMethod(int x, int y) {
return x + y;
}
static double plusMethod(double x, double y) {
return x + y;
}
public static void main(String[] args) {
int myNum1 = plusMethod(8, 5);
double myNum2 = plusMethod(4.3, 6.26);
}
Java Block Scope
A block of code may exist on its own or it can belong to an if, while or for statement. In the case of for statements, variables declared in the statement itself are also available inside the block's scope.
public class Main {
public static void main(String[] args) {
// Code here CANNOT use x
{ // This is a block
// Code here CANNOT use x
int x = 100;
// Code here CAN use x
System.out.println(x);
} // The block ends here
// Code here CANNOT use x
}
}
Multiple methods can have the same name with different (type/amount of) parameters
static int plusMethod(int x, int y) {
return x + y;
}
static double plusMethod(double x, double y) {
return x + y;
}
public static void main(String[] args) {
int myNum1 = plusMethod(8, 5);
double myNum2 = plusMethod(4.3, 6.26);
}
Java Block Scope
A block of code may exist on its own or it can belong to an if, while or for statement. In the case of for statements, variables declared in the statement itself are also available inside the block's scope.
public class Main {
public static void main(String[] args) {
// Code here CANNOT use x
{ // This is a block
// Code here CANNOT use x
int x = 100;
// Code here CAN use x
System.out.println(x);
} // The block ends here
// Code here CANNOT use x
}
}
File Handling
File Handling example in Java
import java.io.File; // Import the File class
import java.io.FileWriter; // Import the FileWriter class
import java.io.FileNotFoundException; // Import this class to handle errors
import java.util.Scanner; // Import the Scanner class to read text files
import java.io.IOException; // Import the IOException class to handle errors
public class JavaFile {
public static void main(String[] args) {
// Create new file
try {
File myObj = new File("C:\\Users\\MyName\\filename.txt"); // double backslash only for windows
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
// Write to a File
try {
FileWriter myWriter = new FileWriter("filename.txt");
myWriter.write("Files in Java might be tricky, but it is fun enough!");
myWriter.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
// Read a File
try {
File myObj = new File("filename.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
System.out.println(data);
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
// Get File Info
File myObj = new File("filename.txt");
if (myObj.exists()) {
System.out.println("File name: " + myObj.getName());
System.out.println("Absolute path: " + myObj.getAbsolutePath());
// Output: Absolute path: C:\Users\MyName\filename.txt
System.out.println("Writeable: " + myObj.canWrite());
System.out.println("Readable " + myObj.canRead());
System.out.println("File size in bytes " + myObj.length());
} else {
System.out.println("The file does not exist.");
}
// Delete File or Folder
File myObj = new File("filename.txt");
if (myObj.delete()) {
System.out.println("Deleted the file: " + myObj.getName());
} else {
System.out.println("Failed to delete the file.");
}
}
}
import java.io.FileWriter; // Import the FileWriter class
import java.io.FileNotFoundException; // Import this class to handle errors
import java.util.Scanner; // Import the Scanner class to read text files
import java.io.IOException; // Import the IOException class to handle errors
public class JavaFile {
public static void main(String[] args) {
// Create new file
try {
File myObj = new File("C:\\Users\\MyName\\filename.txt"); // double backslash only for windows
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
// Write to a File
try {
FileWriter myWriter = new FileWriter("filename.txt");
myWriter.write("Files in Java might be tricky, but it is fun enough!");
myWriter.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
// Read a File
try {
File myObj = new File("filename.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
System.out.println(data);
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
// Get File Info
File myObj = new File("filename.txt");
if (myObj.exists()) {
System.out.println("File name: " + myObj.getName());
System.out.println("Absolute path: " + myObj.getAbsolutePath());
// Output: Absolute path: C:\Users\MyName\filename.txt
System.out.println("Writeable: " + myObj.canWrite());
System.out.println("Readable " + myObj.canRead());
System.out.println("File size in bytes " + myObj.length());
} else {
System.out.println("The file does not exist.");
}
// Delete File or Folder
File myObj = new File("filename.txt");
if (myObj.delete()) {
System.out.println("Deleted the file: " + myObj.getName());
} else {
System.out.println("Failed to delete the file.");
}
}
}
Java Classes
Procedural Programming - writing procedures/methods that perform operations on the data
vs.
Object Oriented Programming - writing objects that contain methods and data
- OOP is easier to maintain because it prevents code from being repeated
Ex: Class - Fruits | Objects - Apple, Orange, Banana (Object is an instance of Class)
- There can only be 1 class per file
vs.
Object Oriented Programming - writing objects that contain methods and data
- OOP is easier to maintain because it prevents code from being repeated
Ex: Class - Fruits | Objects - Apple, Orange, Banana (Object is an instance of Class)
- There can only be 1 class per file
Simple example
// Main.java (Simple Class and Object example)
public class Main {
int x = 5;
final int y = 10;
public static void main(String[] args) {
Main myObj = new Main();
myObj.x = 25; // x is now 25
myObj.y = 25; // will generate an error: cannot assign a value to a final variable
System.out.println(myObj.x);
}
}
public class Main {
int x = 5;
final int y = 10;
public static void main(String[] args) {
Main myObj = new Main();
myObj.x = 25; // x is now 25
myObj.y = 25; // will generate an error: cannot assign a value to a final variable
System.out.println(myObj.x);
}
}
Static vs Public (or other modifiers) Methods
- Static methods can be accessed without creating an object of the class
- Public methods can only be accessed by an object of the class
Static vs public method example
public class Main {
static void myStaticMethod() {
System.out.println("Static methods can be called without creating objects");
}
public void myPublicMethod() {
System.out.println("Public methods must be called by creating objects");
}
// Main method
public static void main(String[] args) {
myStaticMethod(); // Call the static method
// myPublicMethod(); This would compile an error
Main myObj = new Main(); // Create an object of Main
myObj.myPublicMethod(); // Call the public method on the object
}
}
static void myStaticMethod() {
System.out.println("Static methods can be called without creating objects");
}
public void myPublicMethod() {
System.out.println("Public methods must be called by creating objects");
}
// Main method
public static void main(String[] args) {
myStaticMethod(); // Call the static method
// myPublicMethod(); This would compile an error
Main myObj = new Main(); // Create an object of Main
myObj.myPublicMethod(); // Call the public method on the object
}
}
Java Constructors
- special method used to initialize attribute values for newly created object
- constructor name must match class name and cannot mention/have return type
- all classes have constructors - either you create it or Java creates it
- constructors are automatically called when an object is created
- constructors can have 1 or more parameters
Constructor Example
public class Main {
int modelYear;
String modelName;
public Main(int year, String name) {
modelYear = year;
modelName = name;
}
public static void main(String[] args) {
Main myCar = new Main(1999, "Nissan Skyline");
System.out.println(myCar.modelYear + " " + myCar.modelName);
}
}
// Outputs 1999 Nissan Skyline
int modelYear;
String modelName;
public Main(int year, String name) {
modelYear = year;
modelName = name;
}
public static void main(String[] args) {
Main myCar = new Main(1999, "Nissan Skyline");
System.out.println(myCar.modelYear + " " + myCar.modelName);
}
}
// Outputs 1999 Nissan Skyline
Modifiers
- Access Modifiers - sets access levels for classes, attributes, methods and constructors.
- Code within following modifier indicate that they are available to be accessed by
- Public - all classes
- Protected* - same package and subclasses
- Default - same package only
- Private* - declared class
- Non-Access Modifiers - focuses on other functionalities
- Code within following modifier indicate that they are available to be accessed by
- Final - attributes/methods cannot be modified/overridden
- Static - attributes/methods can be used without creating an object
- Abstract - can only be used for methods in abstract classes. Abs. methods cannot contain implementation, only its subclasses can write body
- Transient* - during serialization, does not save value of variable when saving it to a byte stream file
- Synchronized* - methods can only be accessed by 1 thread at a time
- Volatile* - value of volatile variable is always accessed from main memory not thread cache
Encapsulation
Why? - increased security: read-only/write-only, controlled modification
How?
public class Person {
private String name; // private = restricted access
public String getName() {
return name;
}
public void setName(String newName) {
this.name = newName;
}
}
How?
- declare class variables as private
- provide public get/set methods to access/update the value of a private variable
public class Person {
private String name; // private = restricted access
public String getName() {
return name;
}
public void setName(String newName) {
this.name = newName;
}
}
Packages
Groups related classes together
// import package.name.Class; // Import a single class
// import package.name.*; // Import the whole package
// Below ex, java.util is a package, while Scanner is a class of the java.util package.
import java.util.Scanner;
import java.util.*;
// MyPackageClass.java
package mypack; // package name should be written in lower case
class MyPackageClass {
public static void main(String[] args) {
System.out.println("This is my package!");
}
}
>javac -d . MyPackageClass.java
// The -d keyword specifies the destination for where to save the class file/create the package ( '.' is current dir)
- Built-in Packages
// import package.name.Class; // Import a single class
// import package.name.*; // Import the whole package
// Below ex, java.util is a package, while Scanner is a class of the java.util package.
import java.util.Scanner;
import java.util.*;
- User-defined Packages
// MyPackageClass.java
package mypack; // package name should be written in lower case
class MyPackageClass {
public static void main(String[] args) {
System.out.println("This is my package!");
}
}
>javac -d . MyPackageClass.java
// The -d keyword specifies the destination for where to save the class file/create the package ( '.' is current dir)
Java Inheritance
Java Inheritance
class Vehicle {
protected String brand = "Ford"; // Vehicle attribute
protected String color = "Black"; // Default vehicle color
public void honk() { // Vehicle method
System.out.println("Tuut, tuut!");
}
}
class Car extends Vehicle {
private String modelName = "Mustang"; // Car attribute
private String color = "Blue"; // New Car Color
public static void main(String[] args) {
// Create a myCar object
Car myCar = new Car();
// Call the honk() method (from the Vehicle class) on the myCar object
myCar.honk();
// Display values from parent and child class
System.out.println(myCar.brand + " " + myCar.modelName);
// Differentiating between parent and child attributes using 'super'
System.out.println("Car paint color: " + myCar.color); // Outputs Blue
System.out.println("Default Car color: " + super.color); // Outputs Black
// parent methods can called using super.methodName()
// parent constructors can be called using super()
// only use super when method/attribute names are identical in parent & child
System.out.println(myCar instanceof Vehicle); // Outputs true
}
}
- Superclass (parent) | subclass (child)
class Vehicle {
protected String brand = "Ford"; // Vehicle attribute
protected String color = "Black"; // Default vehicle color
public void honk() { // Vehicle method
System.out.println("Tuut, tuut!");
}
}
class Car extends Vehicle {
private String modelName = "Mustang"; // Car attribute
private String color = "Blue"; // New Car Color
public static void main(String[] args) {
// Create a myCar object
Car myCar = new Car();
// Call the honk() method (from the Vehicle class) on the myCar object
myCar.honk();
// Display values from parent and child class
System.out.println(myCar.brand + " " + myCar.modelName);
// Differentiating between parent and child attributes using 'super'
System.out.println("Car paint color: " + myCar.color); // Outputs Blue
System.out.println("Default Car color: " + super.color); // Outputs Black
// parent methods can called using super.methodName()
// parent constructors can be called using super()
// only use super when method/attribute names are identical in parent & child
System.out.println(myCar instanceof Vehicle); // Outputs true
}
}
Polymorphism
Any Java object that can pass more than one IS-A (instanceof) test is considered to be polymorphic. In Java, all Java objects are polymorphic since any object will pass the IS-A test for their own type and for the class Object.
Any Java object that can pass more than one IS-A (instanceof) test is considered to be polymorphic. In Java, all Java objects are polymorphic since any object will pass the IS-A test for their own type and for the class Object.
- A Deer IS-A Deer => Deer d = new Deer();
- A Deer IS-A Vegetarian => Vegetarian v = d;
- A Deer IS-A Animal => Animal a = d;
- A Deer IS-A Object => Object o = d;
Java Inner Classes
- groups classes that belong together
- groups classes that belong together
Nested Classes example
class OuterClass {
int x = 10;
class InnerClass {
int y = 5;
// InnerClass can access any attribute/methods from outer class
public void getParentAttribute(){
System.out.println("Getting parent attribute: " + x);
}
}
}
public class Main {
public static void main(String[] args) {
OuterClass myOuter = new OuterClass();
OuterClass.InnerClass myInner = myOuter.new InnerClass();
System.out.println(myInner.y + myOuter.x); // Outputs 15 (5 + 10)
myInner.getParentAttribute(); // Outputs: Getting parent attribute: 10
}
}
int x = 10;
class InnerClass {
int y = 5;
// InnerClass can access any attribute/methods from outer class
public void getParentAttribute(){
System.out.println("Getting parent attribute: " + x);
}
}
}
public class Main {
public static void main(String[] args) {
OuterClass myOuter = new OuterClass();
OuterClass.InnerClass myInner = myOuter.new InnerClass();
System.out.println(myInner.y + myOuter.x); // Outputs 15 (5 + 10)
myInner.getParentAttribute(); // Outputs: Getting parent attribute: 10
}
}
Abstract Class
- helps hide certain details and allows child class it's own way to implement a requirement
Abstract example
abstract class Animal {
// Abstract method (does not have a body) and can only exist in abstract classes
public abstract void animalSound();
// Regular method
public void sleep() {
System.out.println("Zzz");
}
}
// Subclass (inherit from Animal)
class Pig extends Animal {
public void animalSound() {
// The body of animalSound() is provided here
System.out.println("The pig says: oink oink!");
}
}
class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object because abstract classes cannot be used to create objects
myPig.animalSound();
myPig.sleep();
}
}
// Abstract method (does not have a body) and can only exist in abstract classes
public abstract void animalSound();
// Regular method
public void sleep() {
System.out.println("Zzz");
}
}
// Subclass (inherit from Animal)
class Pig extends Animal {
public void animalSound() {
// The body of animalSound() is provided here
System.out.println("The pig says: oink oink!");
}
}
class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object because abstract classes cannot be used to create objects
myPig.animalSound();
myPig.sleep();
}
}
Java Interface
Interfaces must be implemented by another class with the implements keyword. The implementation of the interface methods must be in the subclass.
- A class can implement multiple interface
- All methods of an interface must be overridden by its child class
- Interface methods can be: public, abstract
- Interface attributes can be: public, static, final
- Does not contain a constructor (since it cannot create objects)
Interface Example
interface Animal {
// interface methods cannot contain a body
public void animalSound();
public void sleep();
}
class Pig implements Animal {
public void animalSound() {
// The body of animalSound() and sleep() is provided here
System.out.println("The pig says: wee wee");
}
public void sleep() {
// The body of sleep() is provided here
System.out.println("Pig is asleep: Zzz...");
}
}
class Main {
public static void main(String[] args) {
// Create a Pig object because interface cannot be used to create objects
Pig myPig = new Pig();
myPig.animalSound();
myPig.sleep();
}
}
// interface methods cannot contain a body
public void animalSound();
public void sleep();
}
class Pig implements Animal {
public void animalSound() {
// The body of animalSound() and sleep() is provided here
System.out.println("The pig says: wee wee");
}
public void sleep() {
// The body of sleep() is provided here
System.out.println("Pig is asleep: Zzz...");
}
}
class Main {
public static void main(String[] args) {
// Create a Pig object because interface cannot be used to create objects
Pig myPig = new Pig();
myPig.animalSound();
myPig.sleep();
}
}
Java User Input
import java.util.Scanner; // Import the Scanner class
class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter username");
String userName = myObj.nextLine(); // Read user input
System.out.println("Username is: " + userName); // Output user input
}
}
/*
nextLine() reads a string from user
nextInt() reads an int from user
Similarly: nextBoolean(), nextByte(), nextDouble(), nextFloat(), nextLong(), nextShort()
*/
class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter username");
String userName = myObj.nextLine(); // Read user input
System.out.println("Username is: " + userName); // Output user input
}
}
/*
nextLine() reads a string from user
nextInt() reads an int from user
Similarly: nextBoolean(), nextByte(), nextDouble(), nextFloat(), nextLong(), nextShort()
*/
Enums
Enums
public class Main {
enum Level {
LOW,
MEDIUM,
HIGH
}
public static void main(String[] args) {
Level myVar = Level.MEDIUM;
System.out.println(myVar);
// Traverses through all values in enum Level
for (Level myVar : Level.values()) {
System.out.println(myVar);
}
}
}
- Use when you have a set of values that are not going to change
- Enums can have attributes/methods but they must be: public, static, final (unchangeable)
public class Main {
enum Level {
LOW,
MEDIUM,
HIGH
}
public static void main(String[] args) {
Level myVar = Level.MEDIUM;
System.out.println(myVar);
// Traverses through all values in enum Level
for (Level myVar : Level.values()) {
System.out.println(myVar);
}
}
}
Date & time
import java.time.LocalDate; // import the LocalDate class
public class Main {
public static void main(String[] args) {
LocalDate myObj = LocalDate.now(); // 2022-12-11
LocalTime myObj2 = LocalTime.now(); // 19:21:14.300118
LocalDateTime myObj3 = LocalDateTime.now(); // 2022-12-11T19:21:14.300568
DateTimeFormatter myFormatObj = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
String formattedDate = myObj3.format(myFormatObj); // 11-12-2022 19:21:14
System.out.println(myObj); // Display the current date
}
}
public class Main {
public static void main(String[] args) {
LocalDate myObj = LocalDate.now(); // 2022-12-11
LocalTime myObj2 = LocalTime.now(); // 19:21:14.300118
LocalDateTime myObj3 = LocalDateTime.now(); // 2022-12-11T19:21:14.300568
DateTimeFormatter myFormatObj = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
String formattedDate = myObj3.format(myFormatObj); // 11-12-2022 19:21:14
System.out.println(myObj); // Display the current date
}
}
Java ArrayList
Unlike arrays, you can add or remove elements in ArrayList whenever you want.
ARRayList example
import java.util.ArrayList;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
System.out.println(cars);
cars.get(0); // returns "Volvo"
cars.set(0, "Opel");
cars.remove(0);
cars.size();
Collections.sort(cars); // Sort cars alphabetically
cars.clear();
}
}
import java.util.Collections;
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
System.out.println(cars);
cars.get(0); // returns "Volvo"
cars.set(0, "Opel");
cars.remove(0);
cars.size();
Collections.sort(cars); // Sort cars alphabetically
cars.clear();
}
}
Java LinkedList
- The ArrayList class has a regular array inside it
- The LinkedList stores its items in "containers."
Some methods of Linked list: addFirst/Last(), removeFirst/Last(), getFirst/Last()
Linkedlist example
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
LinkedList<String> cars = new LinkedList<String>();
cars.add("Ferrari");
cars.add("BMW");
cars.add("McLaren");
cars.add("Ford");
System.out.println(cars);
}
}
public class Main {
public static void main(String[] args) {
LinkedList<String> cars = new LinkedList<String>();
cars.add("Ferrari");
cars.add("BMW");
cars.add("McLaren");
cars.add("Ford");
System.out.println(cars);
}
}
Java HashMap
HashMaps store items in (key, value) pairs.
* keys and values are objects so use Integer instead of int
* keys and values are objects so use Integer instead of int
Hashmap example
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
// Create a HashMap object called capitalCities
HashMap<String, String> capitalCities = new HashMap<String, String>();
// Add keys and values (Country, City)
capitalCities.put("England", "London");
capitalCities.put("Germany", "Berlin");
capitalCities.put("Norway", "Oslo");
capitalCities.put("USA", "Washington DC");
System.out.println(capitalCities);
// Print keys and values
for (String i : capitalCities.keySet()) { // use capitalCities.values() to loop through values
System.out.println("key: " + i + " value: " + capitalCities.get(i));
}
// Access an item
capitalCities.get("England");
capitalCities.remove("England");
capitalCities.size();
capitalCities.clear();
}
}
public class Main {
public static void main(String[] args) {
// Create a HashMap object called capitalCities
HashMap<String, String> capitalCities = new HashMap<String, String>();
// Add keys and values (Country, City)
capitalCities.put("England", "London");
capitalCities.put("Germany", "Berlin");
capitalCities.put("Norway", "Oslo");
capitalCities.put("USA", "Washington DC");
System.out.println(capitalCities);
// Print keys and values
for (String i : capitalCities.keySet()) { // use capitalCities.values() to loop through values
System.out.println("key: " + i + " value: " + capitalCities.get(i));
}
// Access an item
capitalCities.get("England");
capitalCities.remove("England");
capitalCities.size();
capitalCities.clear();
}
}
Java HashSet
Collection of items where every item is unique
Hashset example
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
HashSet<String> cars = new HashSet<String>();
cars.add("Lambo");
cars.add("BMW");
cars.add("Ford");
// BMW is added twice but it'll only appears once in the set
cars.add("BMW");
cars.add("McLaren");
System.out.println(cars);
// Loop through set
for (String i : cars) {
System.out.println(i);
}
// HashSet methods
cars.contains("McLaren");
cars.remove("Ford");
cars.size();
cars.clear();
}
}
public class Main {
public static void main(String[] args) {
HashSet<String> cars = new HashSet<String>();
cars.add("Lambo");
cars.add("BMW");
cars.add("Ford");
// BMW is added twice but it'll only appears once in the set
cars.add("BMW");
cars.add("McLaren");
System.out.println(cars);
// Loop through set
for (String i : cars) {
System.out.println(i);
}
// HashSet methods
cars.contains("McLaren");
cars.remove("Ford");
cars.size();
cars.clear();
}
}
Try ... Catch
public class Main {
public static void main(String[] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
int age = 17;
if (age < 18) {
// use throw to create a custom error
throw new ArithmeticException("Access denied - You must be at least 18 years old.");
}
} catch (Exception e) {
System.out.println("Something went wrong.");
} finally {
System.out.println("The 'try catch' is finished."); // finally block always executes
}
}
}
public static void main(String[] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
int age = 17;
if (age < 18) {
// use throw to create a custom error
throw new ArithmeticException("Access denied - You must be at least 18 years old.");
}
} catch (Exception e) {
System.out.println("Something went wrong.");
} finally {
System.out.println("The 'try catch' is finished."); // finally block always executes
}
}
}
Lambda
like a short function: (parameter1, parameter2) -> { code block }
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(5);
numbers.add(9);
numbers.add(8);
numbers.add(1);
numbers.forEach( (n) -> { System.out.println(n); } );
like a short function: (parameter1, parameter2) -> { code block }
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(5);
numbers.add(9);
numbers.add(8);
numbers.add(1);
numbers.forEach( (n) -> { System.out.println(n); } );
Java Regex
Used to perform all types of text search and text replace operations
regex example
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
// word that we are looking for (the second parameter is optional - for more search up 'flags in compile method')
Pattern pattern = Pattern.compile("w3schools", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher("Visit W3Schools!"); // text where the word will be searched
boolean matchFound = matcher.find(); // stores result as boolean
if(matchFound) {
System.out.println("Match found");
} else {
System.out.println("Match not found");
}
}
}
// Outputs Match found
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
// word that we are looking for (the second parameter is optional - for more search up 'flags in compile method')
Pattern pattern = Pattern.compile("w3schools", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher("Visit W3Schools!"); // text where the word will be searched
boolean matchFound = matcher.find(); // stores result as boolean
if(matchFound) {
System.out.println("Match found");
} else {
System.out.println("Match not found");
}
}
}
// Outputs Match found
Patterns
|
Expression
[abc] [^abc] [0-9] |
Description
Find one character from the options between the brackets Find one character NOT between the brackets Find one character from the range 0 to 9 |
Metacharacters
|
Metacharacter
| . ^ $ \d \s \b \uxxxx |
Description
Find a match for any one of the patterns separated by | as in: cat|dog|fish Find just one instance of any character Finds a match as the beginning of a string as in: ^Hello Finds a match at the end of the string as in: World$ Find a digit Find a whitespace character match at the beginning of a word like this: \bWORD, or at the end of a word: WORD\b Find the Unicode character specified by the hexadecimal number xxxx |
Quantifiers
|
Quantifier
n+ n* n? n{x} n{x,y} n{x,} |
Description
Matches any string that contains at least one n Matches any string that contains zero or more occurrences of n Matches any string that contains zero or one occurrences of n Matches any string that contains a sequence of X n's Matches any string that contains a sequence of X to Y n's Matches any string that contains a sequence of at least X n's |
Java Threads
2 ways to create a thread
- 1. Extend Thread class and override its run method.
- - create an instance of its class and call its start method
- - cannot extend other classes
Thread class example
public class Main extends Thread {
public static void main(String[] args) {
Main thread = new Main();
thread.start();
System.out.println("This code is outside of the thread");
}
public void run() {
System.out.println("This code is running in a thread");
}
}
public static void main(String[] args) {
Main thread = new Main();
thread.start();
System.out.println("This code is outside of the thread");
}
public void run() {
System.out.println("This code is running in a thread");
}
}
- 2. Implement Runnable Interface
- - pass an instance of the class to a Thread object's constructor and then call the thread's start() method
- - can extend other class
Implement Runnable example
public class Main implements Runnable {
public static void main(String[] args) {
Main obj = new Main();
Thread thread = new Thread(obj);
thread.start();
System.out.println("This code is outside of the thread");
}
public void run() {
System.out.println("This code is running in a thread");
}
}
public static void main(String[] args) {
Main obj = new Main();
Thread thread = new Thread(obj);
thread.start();
System.out.println("This code is outside of the thread");
}
public void run() {
System.out.println("This code is running in a thread");
}
}
Serialization
Converts an object and its state to a byte stream (stored in a file) so that the byte stream can be reverted back into a copy of the object in a different platform (kind of like transportation of a java object)
The entire process is JVM independent, meaning an object can be serialized on one platform and deserialized on an entirely different platform.
Used when data needs to be transmitted over the network
For a class to be serialized successfully, 2 conditions must be met
* Note: When serializing an object to a file, the standard convention in Java is to give the file a .ser extension
The entire process is JVM independent, meaning an object can be serialized on one platform and deserialized on an entirely different platform.
Used when data needs to be transmitted over the network
For a class to be serialized successfully, 2 conditions must be met
- The class must implement the java.io.Serializable interface
- All of the fields in the class must be serializable, unless marked transient
* Note: When serializing an object to a file, the standard convention in Java is to give the file a .ser extension
Serializing an object example
/* When the program is done executing, a file named employee.ser is created */
import java.io.*;
public class Employee implements java.io.Serializable {
public String name;
public String address;
public transient int SSN;
public int number;
public void mailCheck() {
System.out.println("Mailing a check to " + name + " " + address);
}
}
public class SerializeDemo {
public static void main(String [] args) {
Employee e = new Employee();
e.name = "Josie Rizal";
e.address = "Phokka Kuan, Ambehta Peer";
e.SSN = 11122333;
e.number = 101;
try {
FileOutputStream fileOut =
new FileOutputStream("/tmp/employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in /tmp/employee.ser");
} catch (IOException i) {
i.printStackTrace();
}
}
}
import java.io.*;
public class Employee implements java.io.Serializable {
public String name;
public String address;
public transient int SSN;
public int number;
public void mailCheck() {
System.out.println("Mailing a check to " + name + " " + address);
}
}
public class SerializeDemo {
public static void main(String [] args) {
Employee e = new Employee();
e.name = "Josie Rizal";
e.address = "Phokka Kuan, Ambehta Peer";
e.SSN = 11122333;
e.number = 101;
try {
FileOutputStream fileOut =
new FileOutputStream("/tmp/employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in /tmp/employee.ser");
} catch (IOException i) {
i.printStackTrace();
}
}
}
Deserializing an object example
import java.io.*;
public class DeserializeDemo {
public static void main(String [] args) {
Employee e = null;
try {
FileInputStream fileIn = new FileInputStream("/tmp/employee.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
e = (Employee) in.readObject(); // must be type casted back to its proper class type
in.close();
fileIn.close();
} catch (IOException i) {
i.printStackTrace();
return;
} catch (ClassNotFoundException c) { // included because if JVM cannot find a class when deserializing, it will throw this error
System.out.println("Employee class not found");
c.printStackTrace();
return;
}
System.out.println("Deserialized Employee...");
System.out.println("Name: " + e.name);
System.out.println("Address: " + e.address);
System.out.println("SSN: " + e.SSN);
System.out.println("Number: " + e.number);
}
}
/* Output:
Deserialized Employee...
Name: Josie Rizal
Address:Phokka Kuan, Ambehta Peer
SSN: 0 // - initially before serializing, value of SSN was 11122333 but since it was marked transient, the value was not saved/serialized so it sets to default int value, 0
Number:101
*/
public class DeserializeDemo {
public static void main(String [] args) {
Employee e = null;
try {
FileInputStream fileIn = new FileInputStream("/tmp/employee.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
e = (Employee) in.readObject(); // must be type casted back to its proper class type
in.close();
fileIn.close();
} catch (IOException i) {
i.printStackTrace();
return;
} catch (ClassNotFoundException c) { // included because if JVM cannot find a class when deserializing, it will throw this error
System.out.println("Employee class not found");
c.printStackTrace();
return;
}
System.out.println("Deserialized Employee...");
System.out.println("Name: " + e.name);
System.out.println("Address: " + e.address);
System.out.println("SSN: " + e.SSN);
System.out.println("Number: " + e.number);
}
}
/* Output:
Deserialized Employee...
Name: Josie Rizal
Address:Phokka Kuan, Ambehta Peer
SSN: 0 // - initially before serializing, value of SSN was 11122333 but since it was marked transient, the value was not saved/serialized so it sets to default int value, 0
Number:101
*/
Java Interview Notes
Singleton Class - can have only one instance
- make the constructor private
- create the object and return via a method
Base class in Java which all other classes is derived from - java.lang.object
garbage collection - when an object is not referenced anymore, java destroys that object
Abstract classes perform faster than Interfaces
Importing a package doesn't include its subpackages. for ex: import university.* != import university.department.*
Strings in Java are immutable and if changed it creates a new object
Constructors are automatically called when object is created but they are only called once.
Defualt java constructors cannot be used when there's an explicit constructor
Clone() method from cloneable interface can be used to make copies of an object
No pointers in Java
Classes cannot extend a final class
A class without a main method can be compiled can be compiled but cannot be run.
JDK is required for development and JRE is required to Java programs
When an object is created, memory is allocated for it in the heap.
Frameworks in Java - a pre-made architecture that contains a set of classes and interfaces
J2EE = Java 2 Enterprise Edition - provides a set of APIs that developers can use to build applications for businesses
- make the constructor private
- create the object and return via a method
Base class in Java which all other classes is derived from - java.lang.object
garbage collection - when an object is not referenced anymore, java destroys that object
Abstract classes perform faster than Interfaces
Importing a package doesn't include its subpackages. for ex: import university.* != import university.department.*
Strings in Java are immutable and if changed it creates a new object
Constructors are automatically called when object is created but they are only called once.
Defualt java constructors cannot be used when there's an explicit constructor
Clone() method from cloneable interface can be used to make copies of an object
No pointers in Java
Classes cannot extend a final class
A class without a main method can be compiled can be compiled but cannot be run.
JDK is required for development and JRE is required to Java programs
When an object is created, memory is allocated for it in the heap.
Frameworks in Java - a pre-made architecture that contains a set of classes and interfaces
J2EE = Java 2 Enterprise Edition - provides a set of APIs that developers can use to build applications for businesses