Concepts for Java
Java is a versatile, object-oriented programming language developed by Sun Microsystems (now owned by Oracle) in the mid-1990s. It's designed to be platform-independent, allowing developers to write code once and run it on any device or operating system that supports Java. Java's key features include its robustness, as it provides automatic memory management through garbage collection, strong type safety, and exception handling. It also offers platform independence through its "write once, run anywhere" philosophy, achieved by compiling Java code into bytecode that can run on any Java Virtual Machine (JVM). Additionally, Java boasts a rich standard library, extensive tooling support, and a large ecosystem of frameworks and libraries, making it popular for developing enterprise-level applications, mobile apps (with Android), web servers, and more.
Print Text
class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } }
Comments
// one line comment /* multi line comment */
Variables
int carCount = 2; String name = "Joe"; boolean isPurple = true;
Data Types
int carCount = 2; int age = 15; short seaLevel = -10000; long usBudget = 11000000000L; long lightSpeed = 11799312874L; float myGPA = 3.45f; double piValue = 3.14159265; char lastLetter = 'Z'; boolean isMale = true; String myName = "Joe";
Math Op
int carCount = 6; int truckCount = 3; int total = carCount + truckCount; System.out.println(total); int subtract = carCount - truckCount; System.out.println(subtract); int multiple = carCount * truckCount; System.out.println(multiple); int divisble = carCount / truckCount; System.out.println(divisble); // performs division and gets remainder which is 0 int modulo = carCount % truckCount; System.out.println(modulo);
Math Functions
import java.lang.Math; double power = Math.pow(3.0, 6.0); System.out.println(power); double root = Math.sqrt(16.0); System.out.println(root); double floorVal = Math.floor(3.14); System.out.println(floorVal); double ceilVal = Math.ceil(4.3); System.out.println(ceilVal); double roundVal = Math.round(3.4); System.out.println(roundVal); // random number from 0 to 100 int ranNum = (int)(Math.random() * 101); System.out.println(ranNum);
If/Else
int carCount = 6; if (carCount > 3) { System.out.println("More than three cars"); } else if (carCount == 3) { System.out.println("Equal to three cars"); } else { System.out.println("Less than three cars"); }
Ternary
int carCount = 3; String result = (carCount > 2) ? "Yes" : "No"; System.out.println(result);
Switch
int carCount = 3; switch (carCount) { case 1: System.out.println("One car"); break; case 2: System.out.println("Two cars"); break; case 3: System.out.println("Three cars"); break; default: System.out.println("More than three"); }
Functions
static int handleCars(int cars, int wheels) { int total = cars * wheels; return total; } int result = handleCars(3, 4); System.out.println(result);
Interpolation
String name = "Joe"; String car = "Mazda"; String result = String.format( "%s drivers a %s", name, car ); System.out.println(result);
Type Casting
import java.lang.Math; public static String squareA(int length) { double result = (double)(Math.pow(length, 2)); String strResult = String.valueOf(result); return strResult; } String squareL = "4"; int convertedVal = Integer.valueOf(squareL); String area = squareA(convertedVal); System.out.println(area);
Date and Time
import java.util.Date; import java.util.Calendar; import java.text.SimpleDateFormat; // epoch time long milliTime = System.currentTimeMillis(); System.out.println(milliTime ); Calendar cal=Calendar.getInstance(); // current year int year = cal.get(Calendar.YEAR); System.out.println(year ); // current month int month = cal.get(Calendar.MONTH) + 1; System.out.println(month ); // formatted date String pattern = "MM/dd/yyyy"; SimpleDateFormat fullDate = new SimpleDateFormat(pattern); String formattedDate = fullDate.format(new Date()); System.out.println(formattedDate );
Classes
import java.util.ArrayList; class Cars { protected ArrayList<String> carList = new ArrayList<>(); public void addCar(String car) { carList.add(car); } public void removeFirst() { carList.remove(0); } public String getFirstVal() { if(carList.size() > 0) { return carList.get(0); } return ""; } public static void main(String[] args) { Cars newList = new Cars(); newList.addCar("Honda"); newList.addCar("Mazda"); newList.addCar("Toyota"); newList.removeFirst(); String firstCar = newList.getFirstVal(); System.out.println(firstCar); } }
Inheritance
class User { protected String username; protected String password; public User( String username, String password ) { this.username = username; this.password = password; } } class Admin extends User { protected String Id; public Admin( String username, String password, String id ) { super(username, password); this.Id = id; } public String getUsername() { return this.username; } public String getAdminID() { return this.Id; } } class Test { public static void main(String[] args) { Admin newAdmin = new Admin( "alpha0", "pw1", "1FE" ); System.out.println( newAdmin.getUsername() ); System.out.println( newAdmin.getAdminID() ); } }
Method Overload
class UserForm { public String formA = "alpha"; public String formB = "beta"; public String formC = "gamma"; public String formD = "epsilon"; public String getForm(int age) { if (age > 65) { return formA; } return formB; } public String getForm(String id) { if (id == "1FE") { return formA; } return formC; } public String getForm( boolean isMilitary, boolean isNasa ) { if (isMilitary || isNasa) { return formD; } return formA; } } UserForm form = new UserForm(); int myAge = 67; String myId = "1FE"; boolean veteran = false; boolean nasa = true; String form1 = form.getForm(myAge); String form2 = form.getForm(myId); String form3 = form.getForm(veteran, nasa); System.out.println(form1 ); System.out.println(form2 ); System.out.println(form3 );
Abstract Class
abstract class Animation { public abstract void walk(); public abstract void run(); public abstract void idle(); } class Human extends Animation { public void walk() { System.out.println("Human walks" ); } public void run() { System.out.println("Human runs" ); } public void idle() { System.out.println("Human idles" ); } } class Zombie extends Animation { public void walk() { System.out.println("Zombie walks" ); } public void run() { System.out.println("Zombie runs" ); } public void idle() { System.out.println("Zombie idles" ); } } Human player = new Human(); player.walk(); Zombie boss1 = new Zombie(); boss1.run();
Static Class
import java.lang.Math; public static class Helper { public static double CircleA(int radius) { double power = Math.pow(radius, 2); return (double)(3.14 * power); } public static double SquareA(int length) { return (double)(Math.pow(length, 2)); } } double circle = Helper.CircleA(3); System.out.println(circle ); double square = Helper.SquareA(4); System.out.println(square );
Arrays/Lists
String[] names = {"Joe", "Alex", "Bob"}; names[1] = "Tom"; String name = names[1]; int numItems = names.length; System.out.println(name); System.out.println(numItems);
Array Methods
import java.util.ArrayList; // adds a new element ArrayList<String> cars = new ArrayList<>(); cars.add("Honda"); cars.add("Mazda"); cars.add("Toyota"); // total number of element int initLength = cars.size(); System.out.println(initLength ); // get element at index one String secondCar = cars.get(1); System.out.println(secondCar ); // removes element one cars.remove(1); System.out.println(cars.get(1) ); // becomes empty cars.clear(); System.out.println(cars.size());
Concatenation
import java.util.Arrays; String[] carListKr = {"Kia", "Hyundai", "Daewoo"}; String[] carListJp = {"Honda", "Mazda", "Toyota"}; String[] combined = Arrays.copyOf( carListKr, carListKr.length + carListJp.length ); System.arraycopy( carListJp, 0, combined, carListKr.length, carListJp.length); System.out.println(combined[1]); System.out.println(combined[4]);
Sort Method
import java.util.ArrayList; import java.util.Collections; ArrayList<Integer> ages = new ArrayList<>(); ages.add(5); ages.add(3); ages.add(1); ages.add(6); ages.add(7); ages.add(4); ages.add(19); Collections.sort(ages); for (int i : ages) { System.out.println(i); }
Objects
class User { public String first; public String last; public int age; public boolean retired; public String[] carBrands; public User ( String first, String last, int age, boolean retired, String[] carBrands ) { this.first = first; this.last = last; this.retired = retired; this.carBrands = carBrands; } public String fullName() { return String.format("%s %s", first, last); } } String[] brands = {"Mazda", "Toyota"}; User user = new User ( "Joe", "Doe", 23, false, brands ); System.out.println(user.first); System.out.println(user.carBrands[1]); System.out.println(user.fullName());
Maps (Key/Value)
import java.util.*; Map<String, String> carMap = new HashMap<>(); carMap.put("Joe", "Toyota"); carMap.put("Bob", "Mazda"); carMap.put("Tom", "Ford"); System.out.println(carMap.get("Tom") + "\n"); carMap.remove("Tom"); System.out.println(carMap.containsKey("Tom"));
Sets
import java.util.*; Set<String> cars = new HashSet<String>(); cars.add("Mazda"); cars.add("Toyota"); cars.add("Honda"); System.out.println(cars.contains("Honda") ); cars.remove("Honda"); System.out.println(cars.contains("Honda"));
Stack
import java.util.*; ArrayList<String> cars = new ArrayList<>(); cars.add("Mazda"); cars.add("Toyota"); cars.add("Honda"); System.out.println(cars.get(cars.size() - 1)); cars.remove(cars.size() - 1); System.out.println(cars.get(cars.size() - 1));
Queues
import java.util.*; ArrayList<String> cars = new ArrayList<>(); cars.add("Mazda"); cars.add("Toyota"); cars.add("Honda"); System.out.println(cars.get(0)); cars.remove(0); System.out.println(cars.get(0));
Linked List
import java.util.*; class Node { public String value; public Node next; public Node(String value) { this.value = value; } } class LinkedList { public Node head = null; public void addValue(String val) { Node newNode = new Node(val); if (this.head == null) { this.head = newNode; } else { Node current = this.head; while(current.next != null) { current = current.next; } current.next = newNode; } } public String returnHead() { return this.head.value; } public void traverse() { Node current = this.head; while(current != null) { System.out.println(current.value ); current = current.next; } } public static void main(String[] args) { LinkedList carList = new LinkedList(); carList.addValue("Mazda"); carList.addValue("Toyota"); carList.addValue("Honda"); System.out.println(carList.returnHead() ); carList.traverse(); } }
Graphs
import java.util.*; class Graph { public Map<String, ArrayList<String>> graphMap = new HashMap<>(); public void addNode(String val) { ArrayList<String> tempArr = new ArrayList<>(); graphMap.put(val, tempArr); } public void addVertices( String node1, String node2 ) { ArrayList<String> tempArr = new ArrayList<String>(); if(graphMap.containsKey(node1) == false) { graphMap.put(node1, tempArr); } if(graphMap.containsKey(node2) == false) { graphMap.put(node2, tempArr); } graphMap.get(node1).add(node2); graphMap.get(node2).add(node1); } public void breadthTraverse(String start) { ArrayList<String> queue = new ArrayList<String>(); queue.add(start); Map<String, Boolean> visited = new HashMap<>(); visited.put(start, true); while(queue.size() > 0) { String val = queue.get(0); System.out.println(val ); queue.remove(0); ArrayList<String> tempArr = graphMap.get(val); for (int i = 0; i < tempArr.size(); i++) { String tempKey = tempArr.get(i); if( visited.containsKey(tempKey ) == false) { queue.add(tempKey); visited.put(tempKey, true); } } } } public void depthTraverse(String start) { ArrayList<String> stack = new ArrayList<>(); stack.add(start); Map<String, Boolean> visited = new HashMap<>(); visited.put(start, true); while(stack.size() > 0) { String val = stack.get(stack.size() - 1); System.out.println(val ); stack.remove(stack.size() - 1); ArrayList<String> tempArr = graphMap.get(val); for (int i = 0; i < tempArr.size(); i++) { String tempKey = tempArr.get(i); if( visited.containsKey(tempKey) == false ) { stack.add(tempKey); visited.put(tempKey, true); } } } } public static void main(String[] args) { Graph newGraph = new Graph(); newGraph.addNode("a"); newGraph.addVertices("a", "b"); newGraph.addVertices("a", "c"); newGraph.addVertices("b", "d"); newGraph.addVertices("b", "e"); newGraph.addVertices("d", "f"); newGraph.addVertices("d", "g"); newGraph.addVertices("d", "h"); newGraph.addVertices("e", "i"); newGraph.addVertices("e", "j"); newGraph.breadthTraverse("a"); newGraph.depthTraverse("a"); } }
For Loops
import java.util.ArrayList; ArrayList<String> names = new ArrayList<>(); names.add("Joe"); names.add("Alex"); names.add("Bob"); for (int i = 0; i < names.size(); i++) { System.out.println(names.get(i) ); }
While Loops
import java.util.ArrayList; ArrayList<String> carList = new ArrayList<>(); carList.add("Mazda"); carList.add("Toyota"); carList.add("Honda"); while(carList.size() > 0) { System.out.println(carList.get(0) ); carList.remove(0); } System.out.println(carList.size());
Loop Breaks
import java.util.ArrayList; ArrayList<String> cars = new ArrayList<>(); cars.add("Toyota"); cars.add("Honda"); cars.add("Mazda"); for (int i = 0; i < cars.size(); i++) { if (cars.get(i) == "Honda") { String result = String.format("Found at index %d", i); System.out.println(result); break; } String result = String.format("Visited index %d", i); System.out.println(result); }
Recursion
import java.util.ArrayList; public static int getSum(ArrayList<Integer> arr) { if (arr.size() == 0) return 0; int firstVal = arr.get(0); arr.remove(0); System.out.println(firstVal ); return firstVal + getSum(arr); } ArrayList<Integer> testArr = new ArrayList<>(); testArr.add(1); testArr.add(2); testArr.add(4); testArr.add(5); int sum = getSum(testArr); System.out.println(sum );
Regex Words
import java.util.regex.Matcher; import java.util.regex.Pattern; Pattern pattern = Pattern.compile( "(\\w+)", Pattern.CASE_INSENSITIVE ); String phrase = "I am legend"; Matcher match = pattern.matcher(phrase); String result = match.find() ? match.group(1) : ""; System.out.println(result);
Regex Numbers
import java.util.regex.Matcher; import java.util.regex.Pattern; Pattern pattern = Pattern.compile( "(\\d+)", Pattern.CASE_INSENSITIVE ); String phrase = "I am 23"; Matcher match = pattern.matcher(phrase); String result = match.find() ? match.group(1) : ""; System.out.println(result);
Regex Test
import java.util.regex.Matcher; import java.util.regex.Pattern; Pattern pattern = Pattern.compile( "Lee", Pattern.CASE_INSENSITIVE ); String phrase = "Bob Lee"; Matcher match = pattern.matcher(phrase); boolean result = match.find(); System.out.println(result);
Regex Characters
import java.util.regex.Matcher; import java.util.regex.Pattern; Pattern pattern = Pattern.compile( "(#+\\w?)", Pattern.CASE_INSENSITIVE ); String phrase = "##I am legend##"; Matcher match = pattern.matcher(phrase); String result = match.find() ? match.group(1) : ""; System.out.println(result);