Niweera
5/25/2019 - 7:43 PM

Java Documentation

The following snippets are helpful to create JAVA code.

// Create Java Classes
// One project should have only one Main class.
// Main class declaration

package com.niweera.Project;
public class Main{
  public static void main(String[] args){
    System.out.println("Hello World!")
  }
}

// Create another class {Car is the class we are creating}

package com.niweera.Project;
public class Car{
  
  public Car (){
    System.out.println("The Car object has instantiated with the default constructor");
  }
  public Car (int a, int b){
    System.out.println("The Car object has instantiated" + " " + a + b);
  }
  
  private int maxSpeed = 180;
  private int numOfSeats = 4;
  private int numOfDoors = 4;
  
  // Getters
  
  public int getSpeed(){
    return maxSpeed;
  }
  
  public int getNumOfSeats(){
    return numOfSeats;
  }
  
  public int getNumOfDoors(){
    return numOfDoors;
  }
  
  // Setters
  
  public void setSpeed(int maxSpeed){
    this.maxSpeed = maxSpeed;
  }
  
  public void setNumOfSeats(int numOfSeats){
    this.numOfSeats = numOfSeats;
  }
  
  public void setNumOfDoors(int numOfDoors){
    this.numOfDoors = numOfDoors;
  }
  
  // Methods in the Car class
  
  public void revEngine(){
    System.out.println("REV...");
  }
  
  public String getOwner(String ownerName){
    return ("The owner is " + ownerName);
  }
  
}

// Create a class variables and class methods

public class Bus(){
  public static int speed = 40;
  
  public static void getRoute(){
    System.out.println("430 Colombo - Mathugama");
  }
}

// String class

String myString = "This is a string";
String myString = new String("This is a string");
String myStringTwo = myString.concat(" This a another string");


// casting 

double r4 = (double)4/3;

// here the output of 4/3 is casted as a double and set it to r4 double variable


// ternary operator

int n = 2;
int m;
m = (n>1)?1:2;
System.out.println(m);


//switch

int number = 100;
		int a = 1;
		
		switch(number) {
		case (1):
			a = 1;
			break;
		case (2):
			a = 2;
			break;
		case (3):
			a = 3;
			break;
		case (4):
			a = 4;
			break;
		case (5):
			a = 5;
			break;
		default:
			a = 0;
		}