The Basics
Data
Primitive types store strings or whole numbers
type | bytes | range |
---|---|---|
byte | 1 | [-128, 127] |
short | 2 | [-32K, 32K] |
int | 4 | [-2B, 2B] |
long | 8 | |
float | 4 | |
double | 8 | |
char | 2 | A, B, C... |
boolean | 1 | true / false |
package com.tutorialdoctor;
public class Main{
public static void main(String[] args){
int viewsCount 3_123_456_789;
float price = 10.99
System.out.println(viewsCount)
}
}
Note
Integer number too large (change to long).
Error default numbers seen as integers. Java compiler ses as integer. Add L
as a suffix. Seen as double add suffix for float F
int viewsCount 3_123_456_789L;
float price = 10.99F;
Reference types (non-primitive types)
Used for storing complex objects.
package com.tutorialdoctor;
import java.util.Date;
public class Main{
public static void main(String[] args){
byte age = 30;
Date now = new Date();
now.getTime()
System.out.println(now);
}
}
Note
Primitive types don't have members like .getTime()
Variables
package com.tutorialdoctor;
public class Main{
public static void main(String[] args){
String name = "Tutorial Doctor";
int myAge = 30;
double avogadro = 6.022;
boolean wifi = true;
}
}
Constants
Use final
to treat a variable as a constant. Use all all caps for constant names.
package com.tutorialdoctor;
public class Main{
public static void main(String[] args){
final float PI = 3.14f;
}
}
Statements
package com.tutorialdoctor;
import java.util.Scanner;
public class Main{
public static void main(String[] args){
String name = "Tutorial Doctor";
System.out.print("Hello " + name);
}
}
package com.tutorialdoctor;
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.print("Age:");
byte age = scanner.nextByte();
System.out.println("You are " + age)
}
}
Strings
package com.tutorialdoctor;
public class Main{
public static void main(String[] args){
String message = new String("Hello World") //redundant
String message = "Hello World" //shorthand
System.out.println(message)
}
}
String Methods
package com.tutorialdoctor;
public class Main{
public static void main(String[] args){
String message = "Hello World" + "!!"
System.out.println(message);
message.endsWith("!!");
message.endsWith("!!");
message.length();
message.indexOf("H");
message.replace(target:"!", replacement:"*");
message.toLowerCase();
message.toUpperCase();
message.trim() //gets rid of white space;
}
}
Note
replace()
and toLowerCase()
don't modify original string (returns a new string). Strings are immutable (you cannot change them).
Escape
Arrays
package com.tutorialdoctor;
public class Main{
public static void main(String[] args){
int[] = numbers = new int[5];
numbers[0] = 1
numbers[1] = 2
numbers[10] = 3 //exception/errror
System.out.println(numbers); // weird string
}
}
Print the array
package com.tutorialdoctor;
import java.utils.Arrays;
public class Main{
public static void main(String[] args){
int[] = numbers = new int[5];
numbers[0] = 1
numbers[1] = 2
System.out.println(Arrays.toString(numbers));
}
}
Note
Other values are set to 0
by default. if it were a boolean array, all values would default to false
. String array, all items initialized to an empty string ''
Another way length and sort.
package com.tutorialdoctor;
import java.utils.Arrays;
public class Main{
public static void main(String[] args){
int[] = numbers = { 2, 3, 5, 1, 4 };
System.out.println(numbers.length());
System.out.println(Arrays.sort(numbers));
}
}
Note
arrays have fixed size/length
Loops
package com.tutorialdoctor;
public class Main{
public static void main(String[] args){
for (int i = 0; i < 5; i++){
System.out.println("Hello World " + i);
}
for (int i = 5; i > 5; i--){
System.out.println("Hello World " + i);
}
}
}
package com.tutorialdoctor;
public class Main{
public static void main(String[] args){
int i = 5;
while (i > 0){
System.out.println("Hello World " + i);
i--;
}
}
}
Note
If you know how many times you want to repeat, use a for loop, if you don't, use while loop.
For Loop
package com.tutorialdoctor;
public class Main{
public static void main(String[] args){
for (int i = 0; i < 5; i++){
System.out.println("Hello World " + i);
}
for (int i = 5; i > 5; i--){
System.out.println("Hello World " + i);
}
}
}
While Loop
package com.tutorialdoctor;
public class Main{
public static void main(String[] args){
int i = 5;
while (i > 0){
System.out.println("Hello World " + i);
i--;
}
}
}
::info Note If you know how many times you want to repeat, use a for loop, if you don't, use while loop. :::
package com.tutorialdoctor;
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String input = "";
while(!input.equals("quit")) {
System.out.println("Input: ");
input = scanner.next().toLowerCase();
System.out.println(input)
}
}
}
Do While Loops
package com.tutorialdoctor;
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String input = "";
while(!input.equals("quit")) {
System.out.println("Input: ");
input = scanner.next().toLowerCase();
System.out.println(input)
}
do{
System.out.println("Input: ");
input = scanner.next().toLowerCase();
System.out.println(input)
}while(!input.equals("quit"));
}
}
Note
Do-while loops get executed at least once, even if the condition is false. These loops are rarely used.
Break and Continue
Break terminates a loop. Continue moves control to the beginning of the loop.
package com.tutorialdoctor;
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String input = "";
while(!input.equals("quit")) {
System.out.println("Input: ");
input = scanner.next().toLowerCase();
if(!input.equals("quit"))
System.out.println(input)
}
}
}
package com.tutorialdoctor;
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String input = "";
while(!input.equals("quit")) {
System.out.println("Input: ");
input = scanner.next().toLowerCase();
if(input.equals("pass"))
continue;
if(input.equals("quit"))
break;
System.out.println(input)
}
}
}
Better
package com.tutorialdoctor;
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String input = "";
while(true) {
System.out.println("Input: ");
input = scanner.next().toLowerCase();
if(input.equals("pass"))
continue;
if(input.equals("quit"))
break;
System.out.println(input)
}
}
}
Note
Without break, you will get an infinite loop.
For-Each Loop
To iterate over arrays or collections
package com.tutorialdoctor;
public class Main{
public static void main(String[] args){
String[] fruits = {"Apple","Mango","orange"};
for (int i = 0; i < fruits.length; i++)
System.out.println(fruits[i]);
for (String fruit : fruits){
System.out.println(fruit);
}
for (int i = fruits.length ; i > 0; i--)
System.out.println(fruits[i]); //not working
}
}
Note
Can only loop forward and not backward.
Mortgage Calculator
Multiple objects
public class Main {
int x = 5;
public static void main(String[] args) {
Main myObj1 = new Main(); // Object 1
Main myObj2 = new Main(); // Object 2
System.out.println(myObj1.x);
System.out.println(myObj2.x);
}
}
Multiple classes
public class Main {
int x = 5;
}
class Second {
public static void main(String[] args) {
Main myObj = new Main();
System.out.println(myObj.x);
}
}
public class Person {
private String name; // private = restricted access
// Getter
public String getName() {
return name;
}
// Setter
public void setName(String newName) {
this.name = newName;
}
}
Functions
class Car {
public static void main(String[] args) {
public static void sayHello(String name){
System.out.println("Hello " + name);
}
sayHello("John");
sayHello("Sandy");
}
}
Classes
public class Main {
int x = 5;
}
public class Main {
int x = 5;
public static void main(String[] args) {
Main myObj = new Main();
System.out.println(myObj.x);
}
}
class Vehicle {
protected String brand = "Ford";
public void honk() {
System.out.println("Tuut, tuut!");
}
}
class Car extends Vehicle {
private String modelName = "Mustang";
public static void main(String[] args) {
Car myCar = new Car();
myCar.honk();
System.out.println(myCar.brand + " " + myCar.modelName);
}
}
Math Class
package com.tutorialdoctor;
public class Main{
public static void main(String[] args){
//overloaded, implemented twice
int result = Math.round(1.1F);
System.out.println(result);
int result = (int)Math.ceil(1.1F);
System.out.println(result);
int result = (int)Math.floor(1.1F);
System.out.println(result);
int result = (int)Math.max(1,2);
System.out.println(result);
int result = (int)Math.min(1,2);
System.out.println(result);
double result = Math.random();
System.out.println(result);
double result = Math.random() * 100;
System.out.println(result);
int result = (int) Math.round(Math.random() * 100);
System.out.println(result);
int result = (int) Math.random() * 100;
System.out.println(result); //error
int result = (int) (Math.random() * 100);
System.out.println(result);
}
}
Packages
import package.name.Class; // Import a single class
import package.name.*; // Import the whole package
package.com.upskil;
import com.upskil.Something;
class Main {
public static void main(String[] args) {
Something something = new Something;
something.create();
}
}
package.com.upskil;
class Something {
public void create(){
System.out.println("Something was created!")
}
}
Dependencies
<depenencies>
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.46.0.0</version>
</dependency>
</depenencies>
Memory Management
Primitive type memory management
package com.tutorialdoctor;
public class Main{
public static void main(String[] args){
byte x = 1;
byte y = x;
}
}
Note
x
and y
are at two different memory locations. If you change x
, y
not affected.
Reference type memory management
package com.tutorialdoctor;
import java.awt.*;
public class Main{
public static void main(String[] args){
Point point1 = new Point(x:1,y:1); //address/reference stored
Point point2 = point1;
point1.x = 2;
System.out.println(point2)
}
}
Note
point1
and point2
point to the same memory location. If you change x
, y
is affected.
Arithmetic
package com.tutorialdoctor;
public class Main{
public static void main(String[] args){
int result = 10 + 3
int result = 10 - 3
int result = 10 * 3
double result = (double)10 / (double)3 // casting 10 to double
System.out.println(result);
// Increment operator
int x = 1;
x++;
++x;
int y = x++ // copied to y then x incremented
System.out.println(x);
System.out.println(y);
int x = 1;
int y = ++x // x and y == 2
System.out.println(x);
System.out.println(y);
int x = 1;
x = x + 2;
x += 2;
System.out.println(x);
int x = 10 + 3 * 2;
System.out.println(x);
}
}
Order of Operations
PEMDAS - Please Excuse My Dear Aunt Sally. Parenthesis, exponents, multiplication, division, addition, subtraction.
package com.tutorialdoctor;
public class Main{
public static void main(String[] args){
int x = 10 + 3 * 2;
System.out.println(x);
}
}
Casting
package com.tutorialdoctor;
public class Main{
public static void main(String[] args){
// Implicit casting (automatically)
short x = 1; // 2 bytes
int y = x + 2; // 4 bytes
System.out.println(y); // 3
double x = 1.1;
double y = x + 2; // 1.1 + 2.0
System.out.println(y); // 3.1
// Explicit Casting
double x = 1.1;
int y = (int)x + 2; // 1 + 2
System.out.println(y); // 3
}
}
Note
can't cast string to integer
package com.tutorialdoctor;
public class Main{
public static void main(String[] args){
String x = "1";
y = Integer.parseInt(x) + 2;
System.out.println(y); // 3
String x = "1.1";
double y = Double.parseDouble(x) + 2;
System.out.println(y); // 3.1
}
}
Typically Recieve input as a string from users, convert to numeric representation
Formatting Numbers
package com.tutorialdoctor;
import java.text.NumberFormat;
public class Main{
public static void main(String[] args){
// $1,234,537
// Abstract class
NumberFormat currency = new NumberFormat();//error
NumberFormat currency = NumberFormat.getCurrencyInstance(); //factory method
String result = currency.format(12345678.891)
System.out.println(result);/// $1,234,567,89
NumberFormat percent = NumberFormat.getPercentInstance(); //factory method
String result = percent.format(0.1)
System.out.println(result); // 10%
String result = NumberFormat.getPercentInstance().format(0.1); //method chaining
System.out.println(result); // 10%
}
}
Reading Input
package com.tutorialdoctor;
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner scanner = new Scanner(System.in); //field
System.out.print("Age:");
byte age = scanner.nextByte();
System.out.println("You are " + age)
Scanner scanner = new Scanner(System.in); //field
System.out.print("Age:");
double age = scanner.nextDouble();
System.out.println("You are " + age)
Scanner scanner = new Scanner(System.in); //field
System.out.print("Name:");
String name = scanner.next(); // next reads one token Full name with space won't work
System.out.println("You are " + name)
Scanner scanner = new Scanner(System.in); //field
System.out.print("Name:");
String name = scanner.nextLine();
System.out.println("You are " + name)
Scanner scanner = new Scanner(System.in); //field
System.out.print("Name:");
String name = scanner.nextLine().trim(); //get rid of leading spaces.
System.out.println("You are " + name)
}
}
Switch Statements
package com.tutorialdoctor;
public class Main{
public static void main(String[] args){
String role = "admin";
if(role=="admin")
System.out.println("You are an admin");
else if(role = "moderator")
System.out.println("You are a moderator");
else
System.out.println("You are a guest");
}
}
package com.tutorialdoctor;
public class Main{
public static void main(String[] args){
String role = "admin";
switch(role){
case "admin":
System.out.println("You are an admin");
break;
case "moderator":
System.out.println("You are a moderator");
break;
default:
System.out.println("You are a guest");
}
}
}
Exercise
Solution
package com.tutorialdoctor;
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.print("Number: ");
int number = scanner.nextInt();
if (number % 5 == 0 && number % 3 == 0)
System.out.println("FizzBuzz");
else if (number % 5 == 0)
System.out.println("Fizz");
else if (number % 3 == 0)
System.out.println("Buzz");
else
System.out.println(number);
}
}