Java Tutorial - Learn Java Basics

Comprehensive Java tutorial covering basics like Hello World, data types, operators, loops, OOPs concepts, and advanced data structures. Learn Java programming easily.

Java Tutorial

Hello World

//Text file name HelloWorld.java
public class HelloWorld {
  // main() is the method
  public static void main (String[] args) {
    //Prints "Hello World" in the terminal window.
    System.out.println("Hello World");
  }
}

Compilation & Executing Java Code

  • Go to your program directory in the terminal (Assumed JAVA Path is set)
  • To compile your code:

javac HelloWorld.java (your program file name)

  • To run the program:

java HelloWorld (main class name)

Data Types

Type Set of values Values Operators
short integers between -2^15 and + (2^15)-1 + - * / %
int integers between -2^31 and + (2^31)-1 + - * / %
long integers between -2^63 and + (2^63)-1 + - * / %
float floating-point numbers real numbers 32 bit + - * /
double floating-point numbers real numbers 64 bit + - * /
boolean boolean values true or false && || !
char characters 16 bit
String sequences of characters it's not a primitive data type

Declaration and Assignment Statements

//Declaration statement
int a,b;

//Assignment statement
a = 13212; //a is the variable name; 13212 is the literal which is assigned to the variable a

//Initialization statement
int c = a + b;

//Compound assignment expressions
a += b; //a = a + b
a -= b; //a = a - b
a *= b; //a = a * b
a /= b; //a = a / b
a %= b; //a = a % b
a ^= b; //a = a ^ b
a &= b; //a = a & b
a |= b; //a = a | b

Comparison Operators

Operation Meaning
== equal
!= not equal
< less than
> greater than
<= less than or equal
>= greater than or equal

Printing

String s = "Happy Coding Folks!!";
System.out.print(s); //print s
System.out.println(s); //print s, followed by a newline
System.out.println(); //print a newline

Parsing Command-Line Arguments

String s = "123";
int i = Integer.parseInt(s); //convert s to an int value
double d = Double.parseDouble(s); //convert s to a double value
long l = Long.parseLong(s); // convert s to a long value

Math Library

public class Math {
    public static double abs(double a)    // absolute value of a
    public static double max(double a, double b)  //maximum of a and b
    public static double min(double a, double b)  //minimum of a and b
    public static double sin(double theta) //sine of theta
    public static double cos(double theta) //cosine of theta
    public static double tan(double theta) //tangent of theta
    public static double toRadians(double degrees) // convert angle from degrees to radians
    public static double toDegrees(double radians)  // convert angle from radians to degrees
    public static double exp(double a)  // exponential (e^a)
    public static double pow(double a, double b) //raise a to the bth power (a^b)
    public static double random() //random in [0,1)
    public static double sqrt(double a)  //square root of a
}

Examples of Type Conversion

Expression Expression type Expression value
(1 + 2 + 3 + 4) / 4.0 double 2.5
Math.sqrt(4) double 2.0
"123343" + 99 String "12334399"
11 * 0.25 double 2.75
(int) 11 * 0.25 double 2.75
11 * (int) 0.25 int 0
(int) (11 * 0.25) int 2

Conditional & Loop Statements

Anatomy of Conditional Statements

If Statement
if (x > y) { // x > y is the boolean expression
  //Sequence of statements
  x = y;
}
If-Else Statement
if (BOOLEAN EXPRESSION) {
  //Sequence of statements
} else {
  //Sequence of statements
}
Nested If Statement
if (BOOLEAN EXPRESSION) {
  //Sequence of statements
} else if {
  //Sequence of statements
}
...
...
...
else {
  //Sequence of statements
}
Switch Statement
switch (VARIABLE TO EVALUATE ITS VALUE) {
  case value: Statement; break;
  ...
  ...
  ...
  default: Statement; break;
}

Example:

int month = 8;
String monthString;
switch (month) {
    case 1:  monthString = "January"; break;
    case 2:  monthString = "February"; break;
    case 3:  monthString = "March"; break;
    case 4:  monthString = "April"; break;
    case 5:  monthString = "May"; break;
    case 6:  monthString = "June"; break;
    case 7:  monthString = "July"; break;
    case 8:  monthString = "August"; break;
    case 9:  monthString = "September"; break;
    case 10: monthString = "October"; break;
    case 11: monthString = "November"; break;
    case 12: monthString = "December"; break;
    default: monthString = "Invalid month"; break;
}

Anatomy of a Loop Statement

For Loop Statement
for (declare and initialize a loop control variable; loop-continuation condition/s; increment or decrement of the variable of control) {
  //Statement
}

Example:

for (int i = 0; i <= n; i++) {
  System.out.println(i);
}
Enhanced For Loop/For-Each
for (dataType item : array) {
  ...
}

Example:

// array of numbers
int[] numbers = {100, 200, 300, 400};

// for each loop
for (int number : numbers) {
  System.out.println(number);
}
While Loop Statement
while (condition) {  //till condition will be true.
  //code to be executed
}

Example:

//Initialization is a separate statement
int power = 1;

while (power <= 10 / 2) // power <= n/2 is an example of the loop-continuation condition
{
  System.out.println(power);
}
Do-While Loop Statement
do { //always run one time even if condition would be false
  //Statement
} while (loop-continuation condition);

Example:

int i = 1;
do {
  System.out.println(i);
  i++;
} while (i <= 10);

Arrays

Array Declaration
int[] ai;        // array of int
short[][] as;        // array of array of short
short s;         // scalar short
short aas[][];   // array of array of short
Object[] ao;        // array of Object
Collection<?>[] ca;  // array of Collection of unknown type
Declaration of Array Variable
Exception ae[] = new Exception[3];
Object aao[][] = new Exception[2][3];
int[] factorial = {1, 1, 2, 6, 24, 120, 720, 5040};
char ac[] = {'n', 'o', 't', ' ', 'a', ' ',
            'S', 't', 'r', 'i', 'n', 'g'};
String[] aas = {"array", "of", "String",};

Access Modifiers

  1. default (No keyword required)
  2. private
  3. public
  4. protected

Non-Access Modifiers

  1. static
  2. final
  3. transient
  4. abstract
  5. synchronized
  6. volatile

Object Oriented Programming (OOPs) Concepts

Objects

//Declare a variable, object name
String s;

//Invoke a constructor to create an object
s = new String("Hello World");

//Invoke an instance method that operates on the object's value
char c = s.charAt(4);
Instance Variables
public class Charge {
  //Instance variable declarations
  private final double rx, ry;
  private final double q;
}

Methods

public static double sum(int a, int b) { //double is the return type, sum is the method's name, a and b are two arguments of type int;
  int result; //local variable
  result = a + b;
  return result;//return statement;
}

Class Declaration

class MyClass {
  // field, constructor, and
  // method declarations
}

Example:

public class Bicycle {
  // the Bicycle class has
  // three fields
  public int cadence;
  public int gear;
  public int speed;
  // the Bicycle class has
  // one constructor
  public Bicycle(int startCadence, int startSpeed, int startGear) {
    gear = startGear;
    cadence = startCadence;
    speed = startSpeed;
  }
  // the Bicycle class has
  // four methods
  public void setCadence(int newValue) {
    cadence = newValue;
  }
  public void setGear(int newValue) {
    gear = newValue;
  }
  public void applyBrake(int decrement) {
    speed -= decrement;
  }
  public void speedUp(int increment) {
    speed += increment;
  }
}
Declaring Classes Implementing an Interface and Extending Parent Class
class MyClass extends MySuperClass implements YourInterface {
  // field, constructor, and
  // method declarations
}
  • MyClass is a subclass of MySuperClass and it implements the YourInterface interface.
Constructors
public class Bicycle {
  private int gear;
  private int cadence;
  private int speed;

  public Bicycle(int startCadence, int startSpeed, int startGear) { //args-constructor
    gear = startGear;
    cadence = startCadence;
    speed = startSpeed;
  }

  public Bicycle() { //No-args constructor
    super();
  }
}

Polymorphism

  • Polymorphism is the concept where an object behaves differently in different situations.
  • There are two types of polymorphism:
    1. Compile-time polymorphism
    2. Runtime polymorphism

Compile-Time Polymorphism

  • Compile-time polymorphism is achieved by method overloading.
  • Method overloading is creating multiple methods with the same name but different arguments.
public class Circle {
  public void draw() {
    System.out.println("Drawing circle with default color Black and diameter 1 cm.");
  }

  public void draw(int diameter) { //method draw() overloaded.
    System.out.println("Drawing circle with default color Black and diameter " + diameter + " cm.");
  }

  public void draw(int diameter, String color) { //method draw() overloaded.
    System.out.println("Drawing circle with color " + color + " and diameter " + diameter + " cm.");
  }
}

Runtime Polymorphism

  • Runtime polymorphism is achieved by method overriding.
  • Runtime polymorphism is implemented when we have an β€œIS-A” relationship between objects.
  • Method overriding is when the subclass overrides the superclass method.
public interface Shape {
  public void draw();
}
public class Circle implements Shape {
  @Override
  public void draw() {
    System.out.println("Drawing circle");
  }
}
public class Square implements Shape {
  @Override
  public void draw() {
    System.out.println("Drawing Square");
  }
}
  • Shape is the superclass and there are two subclasses Circle and Square
  • Below is an example of runtime polymorphism.
Shape sh = new Circle();
sh.draw();

Shape sh1 = getShape(); //some third party logic to determine shape
sh1.draw();

Inheritance

  • Inheritance is the mechanism of code reuse.
  • The object that is getting inherited is called the superclass and the object that inherits the superclass is called a subclass.
  • We use the extends keyword in Java to implement inheritance from a class.
  • We use the implements keyword in Java to implement inheritance from an interface.
public class Superclass {
  // methods and fields
}
public interface Superinterface {
  // methods and fields
}
public class Subclass extends Superclass implements Superinterface {
  // methods and fields
}

Abstraction

  • Abstraction is the concept of hiding the internal details and describing things in simple terms.
  • Abstraction can be achieved in two ways:
  • Abstract Class
  • Interface

Abstract Class

  • An abstract class must be declared with an abstract keyword.
  • It can have abstract and non-abstract methods.
  • It cannot be instantiated.
  • It can have constructors and static methods also.
  • It can have final methods which will force the subclass not to change the body of the method.
abstract class Flower {
  abstract String Smell(); //abstract method.
  String Oil() {  // non-abstract method.
    System.out.println("Flower Oil is good.");
  }
}

public class Lily extends Flower {
  private String Smell() { // implementation of abstract method.
    System.out.println("Lily smell's lovender.");
    return "lovender";
  }
}

Interface

  • Interface is a blueprint of a class.
  • It can have only abstract methods. [Except Java 8 and next versions.]
  • Since Java 8, we can have default and static methods in an interface.
interface print {
  void printPaper();
}
public class A4 implements print {
  public void printPaper() {
    System.out.println("A4 Page Printed. ");
  }
}

Encapsulation

  • Encapsulation is used for access restriction to class members and methods.
  • Encapsulation is the technique used to implement abstraction in OOP.
  • As in encapsulation, the data in a class is hidden from other classes, so it is also known as data-hiding.
  • Encapsulation can be achieved by declaring all the variables in the class as private and writing public methods in the class to set and get the values of variables.
  • Best example of Encapsulation is POJO (Plain-Java-Object-Class).
public class User {
  private String username;
  private String password;

  public String getUsername() {
    return username;
  }

  public void setUsername(String username) {
    this.username = username;
  }

  public String getPassword() {
    return password;
  }

  public void setPassword(String password) {
    this.password = password;
  }
}

Advanced Data Types

Stack Data Type

public class Stack<Item> implements Iterable<Item> {
  Stack()   //create an empty stack
  boolean isEmpty() //return if the stack empty
  void push(Item item) // push an item onto the stack
  Item pop() //return and remove the item that was inserted most recently
  int size() //number of item on stack
}

Queue Data Type

public class Queue<Item> implements Iterable<Item> {
  Queue()  //create an empty queue
  boolean isEmpty()  //return if the queue empty
  void enqueue(Item item) // insert an item onto queue
  Item dequeue()  //return and remove the item that was inserted least recently
  int size() //number of item on queue
}

Iterable

//import Iterator
import java.util.Iterator;

public class Queue<Item> implements Iterable<Item> {
  //FIFO queue
  private Node first;
  private Node last;
  private class Node {
    Item item;
    Node next;
  }

  public void enqueue(Item item) {
    ...
  }

  public Item dequeue() {
    ...
  }

  public Iterator<Item> iterator() {
    ...
  }
}

Symbol Table Data Type

public class ST<Key extends Comparable<Key>, Value> {
  ST()  //create and empty symbol table
  void put(Key key, Value val)  //associate val with key
  Value get(Key key)  //value associated with key
  void remove(Key key) //remove key (and its associated value)
  boolean contains(Key key)  //return if there is a value associated with key
  int size()  //number of key-value pairs
  Iterable<Key> keys()  // all keys in the symbol table
}

Set Data Type

public class Set<Key extends Comparable<Key>> implements Iterable<Key> {
  Set() //create an empty set
  boolean isEmpty()  //return if the set is empty
  void add(Key key)  //add key to the set
  void remove(Key key)  //remove key from set
  boolean contains(Key key) //return if the key is in the set
  int size() //number of elements in set
}