SNCA:Java/Tutorial

From Soyjak Wiki, the free ensoyclopedia
Jump to navigationJump to search

In Java, the file name must match the name of the public class. For example, if your class is public class NusoiProgram, save the file as NusoiProgram.java. This is required for the program to compile.

Boilerplate[edit | edit source]

Every simple Java program needs this structure. The program always starts with a public class and a main() method. The main() method is where the program begins execution.

public class NusoiProgram {
    public static void main(String[] args) {
        // Your code goes here
    }
}

Hello World[edit | edit source]

Here's a simple hello world app. The println() method prints text and moves to the next line automatically.

public class NusoiProgram {
    public static void main(String[] args) {
        System.out.println("Hello Saar!");
    }
}

Variables[edit | edit source]

Java uses variables to store data. Each variable has a type, like <def title="Integer">int</def> for numbers, double for decimals, and String for text. You WILL say what type of variable it is before setting it doe.

public class NusoiProgram {
    public static void main(String[] args) {
        int age = 25;
        double price = 2000.31;
        String name = "Bajeet";
        System.out.println(name + " is " + age + " years old and the price of his laptop was " + price + " rupees.");
    }
}

Adding Numbers[edit | edit source]

You can read numbers from the user and add them together. import java.util.Scanner; adds the Scanner class from the package java.util into the code. The Scanner class allows you to get input from the console.

import java.util.Scanner;

public class NusoiProgram {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter first number: ");
        int firstNumber = scanner.nextInt();

        System.out.print("Enter second number: ");
        int secondNumber = scanner.nextInt();

        System.out.println(firstNumber + " + " + secondNumber + " = " + (firstNumber + secondNumber));
    } 
}

Convert time[edit | edit source]

This is almost exactly like the previous example, but using multiplication instead. Notice how we are using print() instead of println() to get user input- this is to make the cursor be on the same line as the question.

import java.util.Scanner;

public class NusoiProgram {

    public static void main(String[] args) {
        Scanner nusoi = new Scanner(System.in);
        System.out.print("Enter time in minutes: ");
        
        int minutes = nusoi.nextInt();
        int seconds = minutes * 60;
        
        System.out.println(minutes + " minutes is " + seconds + " seconds.");
    }
}

Printf[edit | edit source]

We will introduce printf(), which is a version of print() that accepts C-style format specifiers. %d formats numeric types and %s formats strings. %n is a newline specifier.

public class NusoiProgram {
    public static void main(String[] args) {
        int age = 25;
        double price = 2000.31;
        String name = "Pajet";
        System.out.printf("%s is %d years old and the price of his laptop was %d rupees.%n", name, age, price);
    }
}

|slide8title=Star pyramid |slide8content=A star pyramid is a pyramid of stars. WAAAOOOOW! This script below generates it.

import java.util.Scanner;

public class NusoiProgram {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the number of rows: ");
        int numOfRows = input.nextInt();
        for (int i = numOfRows; i > 0; i -= 2){
            for (int j = 1; j <= i / 2; ++j) {
                System.out.print(" ");
            }
            for (int k = i; k <= numOfRows; ++k) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}

Packages and modules[edit | edit source]

A package is essentially a grouping of classes. Each file may have at most one package declaration, and it must be before any other statements in the file. A package name typically consists of of the structure TLD, then organisation name, then subdirectories (e.g. package com.mysoft.tools for the tools package of a company whose website is mysoft.com, or package party.soyjak.soy; for soyjak.party/soy). Each package is named after its location in the app's file system structure, so for example the package party.soyjak.soy would reside in (from the project root): ./src/main/java/party/soyjak/soy. (Note that the names of packages begin after ./src/main/java.)

Packages in Java do not have "sub-packages", thus java.util.concurrent is not a "sub-package" of java.util. Such names are only used to indicate that the package is associated.

package party.soyjak.examples;

public class NusoiProgram {
    public static void main(String[] args) {
        System.out.printf("%s is %d years old and the price of his laptop was %d rupees.%n", "Pajeet", 25, 2000.31);
    }
}

After this, one can import classes from defined packages, like so:

import party.soyjak.booru.BooruNamefag;
import party.soyjak.util.captcha.McChallenge;

Or, to import all classes from the package, use a wildcard import:

import party.soyjak.util.*;

As mentioned earlier, this will only import packages directly in party.soyjak.util, but not in "sub-packages" like party.soyjak.util.captcha.

In Java 9 and later, packages can be even further grouped together using modules, which can declare the dependencies (using requires) and exported packages (using exports) of each module. However, these are only particularly useful in large applications and libraries where encapsulation must be clearly defined. However, entire modules can be imported, such as import module java.base; which imports a large subsection of the Java standard library.

module party.soyjak.tools {
    requires java.sql;

    exports party.soyjak.tools;
    exports party.soyjak.tools.utils;
}

Classes, interfaces, inheritance[edit | edit source]

A class should have a constructor (which has no return type and bears the same name as the class), which is used with the keyword new to instantiate a new instance. Each Java source file can have at most one public declaration. You can make a class inherit another class's features by using a extends clause. In Java, it is only possible to extend a single class. All classes implicitly extend Object. However, you can inherit as many interfaces as you would like; an interface is essentially a set of methods. When overriding a function, indicate it is overriden with the @Override annotation.

package party.soyjak.examples;

// Base class of vehicles, which implicitly extends Object
class Vehicle {
    private String brand;
    private int year;

    public Vehicle(String brand, int year) {
        this.brand = brand;
        this.year = year;
    }

    public void displayInfo() {
        System.out.printf("Brand: %s, Year: %d%n", brand, year);
    }
}

// Interface for flying vehicles
interface Flyable {
    void fly();
}

// Interface for drivable vehicles
interface Drivable {
    void drive();
}

// Car class extends Vehicle and implements Drivable
class Car extends Vehicle implements Drivable {
    private int doors;

    public Car(String brand, int year, int doors) {
        super(brand, year); // calling Vehicle constructor
        this.doors = doors;
    }

    @Override
    public void drive() {
        System.out.printf("Driving the car with %d doors.%n", doors);
    }

    public void displayCarInfo() {
        displayInfo();
        System.out.printf("Doors: %s%n", doors);
    }
}

// Airplane class extends Vehicle and implements Flyable
class Airplane extends Vehicle implements Flyable {
    private int maxAltitude;

    public Airplane(String brand, int year, int maxAltitude) {
        super(brand, year); // calling Vehicle constructor
        this.maxAltitude = maxAltitude;
    }

    @Override
    public void fly() {
        System.out.printf("Flying the airplane at max altitude of %d metres.%n", maxAltitude);
    }

    public void displayAirplaneInfo() {
        displayInfo();
        System.out.printf("Max Altitude: %d metres.%n", maxAltitude);
    }
}

public class NusoiProgram {
    public static void main(String[] args) {
        Car car = new Car("Toyota", 2022, 4);
        Airplane airplane = new Airplane("Boeing", 2020, 35000);

        car.displayCarInfo(); // Display car details
        car.drive(); // Driving the car

        System.out.println();

        airplane.displayAirplaneInfo(); // Display airplane details
        airplane.fly(); // Flying the airplane
    }
}

GUI[edit | edit source]

This uses Swing. The code snippet below is used in this applet, but can also be used in normal desktop apps. Remember, NetBeans makes Java GUIs drag and drop, just like Visual Basic.

package party.soyjak.examples;

import java.awt.event.ActionEvent;

public class NusoiProgram {
    private void jButton1ActionPerformed(ActionEvent evt) {
         int num1 = (int) jSpinner1.getValue();
         int num2 = (int) jSpinner2.getValue();
         int calculation = num1 + num2;
         jTextField1.setText(Integer.toString(calculation));
    }
}

This uses AWT. Remember, NetBeans makes Java GUIs drag and drop.

package party.soyjak.examples;

import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;

public class NusoiProgram extends JFrame {
    public HelloWorldApp() {
        setTitle("Helo saar");
        setSize(300, 200);
        setVisible(true);
    }

    @Override
    public void paint(Graphics g) {
        g.drawString("Hello saar", 100, 100);
    }

    public static void main(String[] args) {
        HelloWorldApp instance = new HelloWorldApp();
        instance.paint(new Graphics2D());
    }
}

Next Steps[edit | edit source]

Here are some resources to continue learning Java:

Extra notes for beginners:

  • public static void main(String[] args) is the entry point of your program. Only one method with this signature is allowed. The JVM looks for a method with this exact signature to execute the program.
  • Print methods:
    • print() – prints text without moving to a new line.
    • println() – prints text and moves to a new line.
    • printf() – prints text with format specifiers (like in C), no newline automatically.
  • The java.lang package is always available; you don't need to import it. This package contains important globally relevant classes like String, Math, and System.
  • A public class can be used by other programs outside its package.

Final Step to Mastery[edit | edit source]

}}