Java

Syntax of Java

Pratik Kabade, 10 June 2022

Java is a high-level, class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible.

Hello World

package src;
public class HelloWorld {
  public static void main(String[] args) {
    System.out.println("HelloWorld");
  }
}

Content

  1. Variables
  2. String
  3. Numbers
  4. Loop
  5. Array
  6. Method
  7. Class
  8. OOP

    Constructors
    Modifiers
    Encapsulation
    Inheritance
    Polymorphism
    Abstraction
    Interface
    Enum


1 Variables

int myNum = 5;               // Integer
float myFloatNum = 5.99f;    // Floating no.
char myLetter = 'D';         // Character
boolean myBool = true;       // Boolean
char myVar1 = 65;            // Character
String myText = "Java";      // String

int x, y, z;
x = y = z = 50;

int myInt = 9;
double myDouble = myInt;     // int to double

2 String

String myText = "Java";     // String
  System.out.println(myText);
// case
  System.out.println(myText.toUpperCase());

// concat
  System.out.println(myText + "&" + myText);

String x = "10";
String y = "20";
String z = x + y;
  System.out.println(z);

3 Numbers

max

System.out.println(Math.max(5, 10));

min

System.out.println(Math.min(5, 10));

sqrt

System.out.println(Math.sqrt(25));

abs

System.out.println(Math.abs(-4.7));

random

System.out.println(Math.random());

4 Loop

if-else

int time = 22;
if(time < 12){
    System.out.println("Morning!");
}
else if(time > 12){
    System.out.println("Evening!");
}
else{
    System.out.println("error!");
}

// other method
String greet = (time < 12) ? "Morning!" : "Evening!";
System.out.println(greet);

switch

int day = 4;
switch (day) {
  case 1:
    System.out.println("Monday");
    break;
  case 2:
    System.out.println("Tuesday");
    break;
  case 3:
    System.out.println("Wednesday");
    break;
  case 4:
    System.out.println("Thursday");
    break;
  case 5:
    System.out.println("Friday");
    break;
  case 6:
    System.out.println("Saturday");
    break;
  case 7:
    System.out.println("Sunday");
    break;
}

do-while

int i = 0 , j = 5;
while(i < 2){
    System.out.println(i);
    i++;
};

do{
    System.out.println(j);
    j++;
}
while(j < 8);

for

for (int i = 0; i < 3; i = i +1){
    System.out.println(i);
}

for (int i = 0; i < 5; i++) {
    System.out.println(i);
}

foreach

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

for (String i : cars) {
    System.out.println(i);
}

5 Array

Declaration

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

System.out.println(cars[0]);

for-array

String [] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for(int i = 0; i < cars.length; i++){
    System.out.println(cars[i]);
}

multidiamensional array

int a [] [] = { {1,2,3,4},{5,6,7} };

for(int i = 0; i < a.length; i++){
    for(int j = 0; j < a[i].length; j++){
        System.out.println(a[i][j]);
    }
}

6 Method

Method

static void myMethod(String fname, int age) {
    System.out.println(fname + " is " + age);
}

static int myMethod(int x) {
    return 5 + x;
}

public static void main(String[] args) {
    myMethod("Liam", 5);
    myMethod("Jenny", 8);
    myMethod("Anja", 31);
    System.out.println(myMethod(3));
}

if Method

static void checkAge(int age) {
  if (age < 18) {
    System.out.println("Access denied - You are not old enough!");
  } else {
    System.out.println("Access granted - You are old enough!");
  }
}

public static void main(String[] args) {
  checkAge(20);
}

Method

public static void main(String[] args) {
    int result = sum(5, 10);
    System.out.println(result);
}
public static int sum(int start, int end) {
    if (end > start) {
    return end + sum(start, end - 1);
    } else {
    return end;
    }
}

7 Class

Class

public class oClass {
  int x = 5;

  public static void main(String[] args) {
      oClass myObj1 = new oClass();  // Object 1
      oClass myObj2 = new oClass();  // Object 2
      System.out.println(myObj1.x);
      System.out.println(myObj2.x);
  }
}
public class pClassLink {
    public static void main(String[] args) {
        oClass myObj = new oClass();
        myObj.x = 40;
        System.out.println(myObj.x);
      }
}

8. OOP

Constructors

public class qConstructors {
    int x;
    String a;

    public qConstructors(int y, String b) {
      x = y;
      a = b;
    }

    public static void main(String[] args) {
      qConstructors myObj = new qConstructors(1, "day");
      System.out.println(myObj.a);
      System.out.println(myObj.x);
    }
}

Modifiers

public class rModifiers {
    // final(cant be changed)
    // static
    // public
    // private(can be accessed in declrd class)
    // protected

      // Static method
  static void myStaticMethod() {
    System.out.println("Static methods can be called without creating objects");
  }

  // Public method
  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 output an error
    rModifiers myObj = new rModifiers();
        // Create an object of Main
    myObj.myPublicMethod();
        // Call the public method
  }
}

Encapsulation

public class sEncapsulation {
    private String name; // restricted access

    // Setter
    public void setName(String newName) {
      this.name = newName;
    }

    // Getter
    public String getName() {
      return name;
    }
}

Encapsulation

public class tEncapsulation {
    public static void main(String[] args) {
        //sEncapsulation myObj1 = new sEncapsulation();
        //myObj1.name = "John";  // error
        //System.out.println(myObj1.name); // error

        sEncapsulation myObj2 = new sEncapsulation();
        myObj2.setName("John");
        System.out.println(myObj2.getName()); // John
    }
}

Inheritance

public class uInheritance {
    protected String brand = "Ford";        // Vehicle attribute
    public void honk() {                    // Vehicle method
      System.out.println("Tuut, tuut!");
    }
}

class Car extends uInheritance {
    private String modelName = "Mustang";    // Car attribute
    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 the value of the brand attribute (from the Vehicle class) and the value of the modelName from the Car class
      System.out.println(myCar.brand + " " + myCar.modelName);
    }
}

Polymorphism

class Animal {
    public void animalSound() {
      System.out.println("The animal makes a sound");
    }
}

  class Pig extends Animal {
    public void animalSound() {
      System.out.println("The pig says: wee wee");
    }
}

class Dog extends Animal {
    public void animalSound() {
      System.out.println("The dog says: bow wow");
    }
}

class Main {
    public static void main(String[] args) {
      Animal myAnimal = new Animal();  // Create a Animal object
      Animal myPig = new Pig();  // Create a Pig object
      Animal myDog = new Dog();  // Create a Dog object
      myAnimal.animalSound();
      myPig.animalSound();
      myDog.animalSound();
    }
}

Abstraction

// Abstract class
abstract class Animal {
    // Abstract method (does not have a body)
    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: wee wee");
    }
}

class Main {
    public static void main(String[] args) {
      Pig myPig = new Pig(); // Create a Pig object
      myPig.animalSound();
      myPig.sleep();
    }
}

interface

interface FirstInterface {
    public void myMethod(); // interface method
}

interface SecondInterface {
    public void myOtherMethod(); // interface method
}

class DemoClass implements FirstInterface, SecondInterface {
    public void myMethod() {
      System.out.println("Some text..");
    }
    public void myOtherMethod() {
      System.out.println("Some other text...");
    }
}

class Main {
    public static void main(String[] args) {
      DemoClass myObj = new DemoClass();
      myObj.myMethod();
      myObj.myOtherMethod();
    }
}

Enum

enum Level {
    LOW,
    MEDIUM,
    HIGH
}

public class yEnum {
    public static void main(String[] args) {
      Level myVar = Level.MEDIUM;

      switch(myVar) {
        case LOW:
          System.out.println("Low level");
          break;
        case MEDIUM:
           System.out.println("Medium level");
          break;
        case HIGH:
          System.out.println("High level");
          break;
        }
    }
}