본문 바로가기

Java/Story

Java - 기본 문법

 

 

Java 기본 문법 정리입니다.

 

1. Tutorial

1.0 public class

/**
 * App
 */
public class App {
    public static void main(String[] args) {
        // code space
    }
}

 

1.1 print

System.out.println("Hello World");
System.out.print("this is on ");
System.out.println("same line.");
System.out.println("He said \"I\'m not ok. using Backslash (\\) \"");

// Operators
String x1 = "10";
int x2 = 20;
System.out.println(x1 + x2); // String concat operator

 

1.2 Data Type

// type (primitive, wrapper classes)
Byte bNull = null;
// byte b_null = null; primitive can't null

byte b1 = -128, b2 = 127; // 2^8
Byte B1 = -128, B2 = 127; // 2^8

short s1 = -32768, s2 = 32767; // 2^16
Short S1 = -32768, S2 = 32767; // 2^16

int i1 = -2147483648, i2 = 2147483647; // 2^32
Integer I1 = -2147483648, I2 = 2147483647; // 2^32

long l1 = -9223372036854775808L, l2 = 9223372036854775807L; // 2^64
Long L1 = -9223372036854775808L, L2 = 9223372036854775807L; // 2^64

float f1 = 1.23456789f; // 2^32
Float F1 = 1.23456789f; // 2^32

double d1 = 1.2345678901234567890d; // 2^64
Double D1 = 1.2345678901234567890d; // 2^64

boolean bool1 = true, bool2 = false; // 1bit
Boolean Bool1 = true, Bool2 = false; // 1bit

char c1 = 'a', c2 = 97;
Character C1 = 'b', C2 = 98;

String h1 = "hello";

String[] fruits = { "banana", "apple", "berry" };

Object[] myArray = { 1, "2" };

System.out.println(l1 - 1); // underflow
System.out.println(l2 + 1); // overflow
System.out.println(f1); // floating point error
System.out.println(d1); // floating point error
System.out.println(c1); // a
System.out.println(c2); // a
System.out.println(h1); // hello
System.out.println(fruits[2]);

 

1.3 Math

System.out.println(Math.E); // 2.718281828459045
System.out.println(Math.PI); // 3.141592653589793
System.out.println(Math.sin(Math.PI)); // ~ 0
System.out.println(Math.cos(Math.PI)); // -1
System.out.println(Math.tan(Math.PI / 2)); // ~ inf
System.out.println(Math.asin(0.5) / Math.PI); // 1/6
System.out.println(Math.acos(0.5) / Math.PI); // 1/3
System.out.println(Math.atan(1) / Math.PI); // 1/4
System.out.println(Math.log(Math.exp(1))); // log e = 1
System.out.println(Math.log10(Math.pow(10, 25)));// log10 10^25 = 25
System.out.println(Math.random()); // 0 ~ 1
// Exception has occurred. overflow protect
// System.out.println(Math.addExact(Integer.MAX_VALUE, 1));
System.out.println(Math.max(10, 100)); // 100
System.out.println(Math.min(10, 100)); // 10
System.out.println(Math.ceil(1234.5678)); // 1235.0 double -> double
System.out.println(Math.floor(1234.5678)); // 1234.0 double -> double
System.out.println(Math.round(1234.5678)); // 1235 float -> int, double -> long
System.out.println(Math.abs(-10)); // 10

 

1.4 if else, switch

boolean cond = false, cond2 = false, cond3 = false;

if (cond)
    System.out.println("cond : " + cond);
else if (!cond2)
    System.out.println("cond2 : not " + cond2);
else
    System.out.println("cond2 : " + cond2);
    
System.out.println("cond3 is : " + (cond3 ? "true" : "false"));

int num = 10;
switch(num){
    case 1:
        System.out.println("number is 1. Specially.");
        break;
    default:
        System.out.println("number is " + num);
        break;
}

 

1.5 for, while

int whileNum = 5, doWhileNum = 4, forNum = 3;
int[] forArray = { 4, 2, 3, 4, 100 };
while (whileNum > 0) {
    System.out.println(whileNum);
    whileNum--;
}

do {
    System.out.println(doWhileNum);
    doWhileNum--;
} while (doWhileNum > 0);

for (int i = 0; i < forNum; i++)
    System.out.println(i);

for (int forElement : forArray)
    System.out.println(forElement);

 

 


2. Class

2.1 Class Attribute, Method ( + static, final)

/**
 * InnerApp
 */
class InnerApp {
    private Integer priAppNum = 1;
    public Integer pubAppNum = 2;
    public static final Integer constNum = 3;

    public static void pubsMethod() {
        System.out.println("this is InnerApp public static method");
    }

    public void pub_method() {
        System.out.println("this is InnerApp public method");
    }

    private static void pris_method() {
        System.out.println("this is InnerApp private static method");
    }

    private void pri_method() {
        System.out.println("this is InnerApp private method");
    }

    // getter
    public Integer getPublicAppNum() {
        return pubAppNum;
    }

    // setter
    public void setPuiblicAppNum(Integer newNum) {
        if (newNum > 0)
            this.pubAppNum = newNum;
        else
            this.pubAppNum = 0;
    }
}

/**
 * App
 */
public class App {
    public static void main(String[] args) {
        // class
        InnerApp innerApp1 = new InnerApp();

        // System.out.println(innerApp1.priAppNum); // private won't work

        System.out.println(++innerApp1.pubAppNum);
        // System.out.println(++InnerApp.constNum); // final attribute can't modified

        innerApp1.pubsMethod(); // warning, but it will works
        InnerApp.pubsMethod();
        innerApp1.pub_method();
        // InnerApp.pub_method(); // static method won't works class direct
        // InnerApp.pris_method(); // private won't work
        // innerApp1.pri_method(); // private won't work
        innerApp1.setPuiblicAppNum(I2);
        System.out.println(innerApp1.getPublicAppNum());
    }
}

 

 

2.2 Constructor

/**
 * ConstructorExample
 */
class ConstructorExample {
    public int num1, num2;

    public ConstructorExample(int _num1, int _num2) {
        num1 = _num1;
        this.num2 = _num2;
    }

    public int sumNumber() {
        return (this.num1 + num2);
    }
}

public class App {
    public static void main(String[] args) {
        ConstructorExample cExample = new ConstructorExample(2, 3);
        int resultNumber = cExample.sumNumber();
        System.out.println(resultNumber);
    }
}

 

 

2.3 Encapsulation

public class App {
    public static void main(String[] args) {
        Person p1 = new Person("jjj", "qwer1234");
        p1.login("jjj", "qwerqwer"); // fail
        p1.login("jjj", "qwer1234"); // success
    }
}

class Person {
    // encapsulation
    private String ID = "__unknown__";
    private int PasswordHashValue = -1; // there is no password
    private int secretNumArray[] = { 2, 3, 5, 7, 11 };

    Person(String id, String pasword) {
        this.ID = id;
        this.PasswordHashValue = this.genHash(pasword);
    }

    // encapsulation. secret algorithm
    private int genHash(String password) {
        int num = 0;
        char[] passwordCharArray = password.toCharArray();
        for (int i = 0; i < password.length(); i++) {
            num += passwordCharArray[i] * secretNumArray[i % 4];
        }
        return num;
    }

    // encapsulation
    private boolean authentication(String id, String password) {
        if (this.ID != id)
            return false;
        if (this.PasswordHashValue != this.genHash(password))
            return false;
        return true;
    };

    // public method
    public void login(String id, String password) {
        if (authentication(id, password)) {
            System.out.println("welcome");
        } else {
            System.out.println("wrong information");
        }
    }
}

 

 

2.4 Inheritance

public class App {
    public static void main(String[] args) {
        Bird bird = new Bird("pp");
        System.out.println(bird.name);
        bird.age = 10;
        System.out.println(bird.age);
        bird.name = "birdy"; // protected but super(name)
        System.out.println(bird.name);
        bird.nickname = "new_nickname";
        System.out.println(bird.nickname);
        bird.eat();
        bird.sleep();
        bird.fly();
    }
}

class Animal {
    protected String name;
    protected String nickname = "nickname";
    public int age;

    public Animal(String name) {
        this.name = name;
    }

    public void eat() {
        System.out.println(name + " is eating.");
    }

    public void sleep() {
        System.out.println(name + " is sleeping");
    }

    final public void breath() {
        System.out.println(name + " is breathing. all of Animal does.");
    }
}

class Bird extends Animal {
    public Bird(String name) {
        super(name); // public Animal(String name);
    }

    @Override
    public void eat() {
        System.out.println(name + " is eating with beak");
    }

    // final method can't override
    // @Override
    // public void breath() {
    //     System.out.println(name + " is another breathing");
    // }

    public void fly() {
        System.out.println(name + " flying");
    }
}

 

2.5 Polymorphism

// Compile-time Polymorphism (overloading)
public class Calculator {
    public int add(int a, int b) {
        return a + b;
    }

    public double add(double a, double b) {
        return a + b;
    }
}

 

 

//Runtime Polymorphism (overriding)
public class App {
    public static void main(String[] args) {
        Animal myDog = new Dog();
        Animal myCat = new Cat();

        myDog.makeSound(); // Dog barks.
        myCat.makeSound(); // Cat meows.
    }
}

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

class Dog extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Dog barks.");
    }
}

class Cat extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Cat meows.");
    }
}

 

 

2.6 Abstractor

abstract class Shape {
    abstract double area();	// 상속할 때 반드시 구현하라는 의미. method body가 없어도 된다.

    void printArea() {
        System.out.println("Area : " + area());
    }
}

class Circle extends Shape {
    private double radius;

    Circle(double radius) {
        this.radius = radius;
    }
    
    @override	// 없어도 error 안나지만 있으면 보기 좋다
    double area() {	// 없으면 에러 난다
        return Math.PI * radius * radius;
    }
}

 

 

2.7 Interface

public class App {
    public static void main(String[] args) {
        Circle circle = new Circle(5.0);
        circle.printArea();
    }
}

interface Shape {
    double area(); // method를 만들라고 지시
}

class Circle implements Shape {
    private double radius;

    Circle(double radius) {
        this.radius = radius;
    }
    
    @Override
    public double area() {
        return Math.PI * radius * radius;
    }

    void printArea() {
        System.out.println("Area: " + area());
    }
}

 

 


 

* reference

https://www.w3schools.com/java/java_output.asp