[Studying Java Core] #1

Inwook Baek ·2021년 9월 27일
0

Java Study

목록 보기
1/6
post-thumbnail

Units of Information

Bit (b): the smallest unit of information
Byte (B): a sequence of eight bits
Larger units of information:

Kibibyte (KiB) 2^10 B (or 1024B)
Mebibyte (MiB) 2^20 B (or 1024 KiB) 
Gibibyte (Gib) 2^30 B (or 1024 MiB)
Tebibyte (TiB) 2^40 B (or 1024 GiB)
Pebibyte (PiB) 2^50 B (or 1024 TiB)

What is Java?

Java is a general-purpose modern programming language initially developed by Sun Microsystems, and currently owned by Oracle Corporation. The key feature of the language is platform independence: it means that the same Java program can be run on multiple platforms without any changes! This principle is also known as "write once, run anywhere" (or WORA).

The most important feature of Java is platform independence and its garbage collector that automatically cleans memory from unsused objects during runtime.

Literals

Regardless of its complexity, a program always performs operations on numbers, strings, and other values. These values are called literals.

Integer Numbers

Here are several examples of valid integer number literals separated by commas: 0, 1, 2, 10, 11, 100.

If an integer value contains a lot of digits, we can add underscores to divide the digit into blocks for increased readability: 1_000_000. It's more readable than the same value written as 1000000.

Characters

A single character can represent a digit, a letter or another symbol. To write a character we use single quotes as follows: 'A', 'B', 'C', 'x', 'y', 'z', '0', '1', '2', '9'. Character literals can represent symbols of an alphabet, digits from '0' to '9', whitespaces (' '), or other characters or symbols ('$').

Strings

To write a string we use double quotes instead of single ones. Here are some valid examples: "text", "I want to know Java", "123456", "e-mail@gmail.com". A string consisting of a single character like "A" is also a valid string, but do not confuse it with the 'A' character.

Overview of the Basic Program

Basic syntax

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

The Basic Terminology

Program – a sequence of instructions (called statements), which are executed one after another in a predictable manner. Sequential flow is the most common and straightforward sequence of statements, in which statements are executed in the order that they are written – from top to bottom in a sequential manner;
Statement – a single action (like print a text) terminated by semi-colon (;);
Block – a group of zero, one or more statements enclosed by a pair of braces {...}; There are two such blocks in the program above.
Method – a sequence of statements that represents a high-level operation (also known as subprogram or procedure).
Syntax – a set of rules that define how a program needs to be written in order to be valid; Java has its own specific syntax that we will learn;
Keyword – a word that has a special meaning in the programming language (public, class, and many others). These words cannot be used as variable names for your own program;
Identifier or name – a word that refers to something in a program (such as a variable or a function name);
Comment – a textual explanation of what the code does. Java comments start with //.
Whitespace – all characters that are not visible (space, tab, newline, etc.).

The public class

It is the basic unit of a program. Every Java program must have at least one class. The definition of a class consists of the class keyword followed by the class name. A class can have any name, such as App, Main, or Program, but it must not start with a digit. A set of braces {...} encloses the body of a class.

public class Main {
    // ...
}

The main method

To make the program runnable, we put a method named main inside a class. It is the entry point for a Java program. Again, the braces {...} enclose the body of the method, which contains programming statements.

public static void main(String[] args) {
    // statements go here
}

Printing Data

println() vs print()

The println method displays the passed string followed by a new line on the screen (print-line). For example, the following code snippet prints four lines.

System.out.println("I ");
System.out.println("know ");
System.out.println("Java ");
System.out.println("well.");

Output:
I
know
Java
well.

The print method displays the value that was passed in and places the cursor (the position where we display a value) after it. For example, the code below outputs all strings in a single line.

System.out.print("I ");
System.out.print("know ");
System.out.print("Java ");
System.out.print("well.");

Output:
I know Java well.

Types and Variables

Declaring and initializng

A variable is a placeholder for storing a value of a particular type: a string, a number, or something else. Every variable has a name (also known as an identifier) to distinguish it from others. Before you start using a variable, you must declare it.

The general form of declaration is the following:

DataType variableName = initialization;
String language = "java";
int numberOfApples = 5;

The type (or data type) of a variable determines what possible operations can be performed on the variable and which values can be stored in it. Here we use a non-existing data type (DataType) to demonstrate the general form of declaration.
The name (or identifier) distinguishes the variable from others. The name of a variable cannot start with a digit; it usually starts with a letter. Always try to choose meaningful and readable names for variables to make your code easy to understand.
The assignment operator denoted as = is used to assign a single value or a result of an expression to a variable.
The initialization is a value or a result of an expression that is assigned to the variable.

Accessing the value of a variable

String dayOfWeek = "Monday";
System.out.println(dayOfWeek); // Monday

int one = 1;
int num = one;
System.out.println(num); // 1

String dayOfWeek = "Monday";
System.out.println(dayOfWeek); // Monday

dayOfWeek = "Tuesday";
System.out.println(dayOfWeek); // Tuesday

int number = 10;
number = 11; // ok
number = "twelve"; // it does not work!

String language = "java", version = "8 or newer";
int age; // declaration
age = 35; // initialization 

There is one restriction for variables: you can only assign a value of the same type as the type of the initial variable.

Type inference

Since Java 10, you can write var instead of a specific type to force automatic type inference based on the type of assigned value:

var variableName = initialization;

var language = "Java"; // String
var version = 10; // int

This feature can be a bit controversial: on the one hand, it allows your code to be more concise. On the other hand, since it doesn't indicate the type explicitly, it may affect the code readability in a bad way.

Sizes and Ranges

Integer numbers (0, 1, 2, ...) are represented by the following four types: long,int,short,byte(from the largest to the smallest). These types have different sizes and may represent different ranges of values. The range of an integer type is calculated as −(2n−1) to (2n−1)−1, where n is the number of bits. The range includes 0, which is the reason for subtracting 1 from the upper bound.

byte: size 8 bits (1 byte), range from -128 to 127
short: size 16 bits (2 bytes), range from -32768 to 32767
int: size 32 bits (4 bytes), range from −(231) to (231)−1
long: size 64 bits (8 bytes), range from −(263) to (263)−1

The most commonly used integer types are int and long. Try to use int if it is enough for your purposes. Otherwise, use long.

int one = 1;
long million = 1_000_000L;

Floating-point types represent numbers with fractional parts. Java has two such types: double (64 bits) and float (32 bits). These types can store only a limited number of significant decimal digits (~6-7 for float and ~14-16 for double). Usually, you will use the double type in practice.

double pi = 3.1415;
float e = 2.71828f;

Java has a type named char to represent letters (uppercase and lowercase), digits, and other symbols. Each character is just a single letter enclosed in single quotes. This type has the same size as the short type (2 bytes = 16 bits).

char lowerCaseLetter = 'a';
char upperCaseLetter = 'Q';
char dollar = '$';

Java provides a type called boolean, which can store only two values: true and false. It represents only one bit of information, but its size is not precisely defined.

boolean enabled = true;
boolean bugFound = false;

Type Casting

Implicit casting

The compiler automatically performs implicit casting when the target type is wider than the source type. Normally, there is no loss of information when the target type is wider than the source type, for example when we cast int to long. But it is not possible to automatically cast in the backward order (e.g. from long to int or from double to float).

from int to long:
  int num = 100;
  long bigNum = num; // 100L

from long to double:
  long bigNum = 100_000_000L;
  double bigFraction = bigNum; // 100000000.0

from short to int:
  short shortNum = 100;
  int num = shortNum; // 100

from char to int:
  char ch = '?';
  int code = ch; // 63

In some cases, implicit type casting may be a bit lossy. When we convert an int to float, or a long to float or to double, we may lose some less significant bits of the value, which will result in a loss of precision. However, the result of this conversion will be a correctly rounded version of the integer value, which will be in the overall range of the target type. To understand that, check out the example:

long bigLong =  1_200_000_002L;
float bigFloat = bigLong; // 1.2E9 (= 1_200_000_000)

When we convert a char to an int in Java we actually get the ASCII value for a given character. ASCII value is an integer representation of English alphabet letters (both uppercase and lowercase), digits, and other symbols.

char character = 'a';
char upperCase = 'A';

int ascii1 = character; // this is 97
int ascii2 = upperCase; // this is 65

Explicit casting

The considered implicit casting does not work when the target type is narrower than the source type. But programmers can apply explicit casting to a source type to get another type they want. It may lose information about the overall magnitude of a numeric value and may also lose precision.

To perform explicit casting, a programmer must write the target type in parentheses before the source.

(targetType) source

double d = 2.00003;

// it loses the fractional part
long l =  (long) d; // 2

// requires explicit casting because long is wider than int
int i = (int) l; // 2 

// requires explicit casting because the result is long (indicated by L)
int val = (int) (3 + 2L); // 5

// casting from a long literal to char
char ch = (char) 55L; // '7'

However, the explicit casting may truncate the value, because long and double can store a much larger number than int.

long bigNum = 100_000_000_000_000L;
int n = (int) bigNum; // 276447232

Order of Conversion:
Be Careful! Bears shouldn't Ingest Large Furry Dogs
Boolean -> Char -> Byte -> Short -> Int -> Long -> Float -> Double

Coding Style Conventions

Java Conventions

Oracle Code Conventions
Google Style Guide

Scanning the Input

The standard input is a stream of data going into a program. It is supported by the operating system. By default, the standard input obtains data from the keyboard input but it's possible to redirect it from a file.

Reading data with a scanner

The simplest way to obtain data from the standard input is to use the standard class Scanner. It allows a program to read values of different types (string, numbers, etc) from the standard input.

import java.util.Scanner;

Scanner scanner = new Scanner(System.in);

There are two ways to read strings with a Scanner class. If your input is an integer number or a single word, you can read the data using next() method. As an example, the following code fragment reads the user’s name and prints hello message:

String name = scanner.next();

System.out.println("Hello, " + name + "!");

We can read data from the standard input with a special Scanner class. The next() and the nextLine() methods will help you to read strings. Both of them are used for getting input, but they act differently. The next() method can read the input only till the whitespace while the nextLine() method reads the input till the end of the whole line.

Example 1:

Sample Input:
Java
Programming
Language

Sample Output:
Language
Programming
Java

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        String word1 = scanner.nextLine();
        String word2 = scanner.nextLine();
        String word3 = scanner.nextLine();
        
        System.out.println(word3);
        System.out.println(word2);
        System.out.println(word1);
    }
}

Example 2:

Sample Input:
Hello
Java
Future programmer

Sample Output:
Hello
Java
Future
programmer

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        String word1 = scanner.nextLine();
        String word2 = scanner.nextLine();
        String word3 = scanner.next();
        String word4 = scanner.next();
        
        System.out.println(word1);
        System.out.println(word2);
        System.out.println(word3);
        System.out.println(word4);
    }
}

Example 3:

Sample Input:
This Java platform
is adaptive

Sample Output:
This
Java
platform
is
adaptive

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        String word1line1 = scanner.next();
        String word2line1 = scanner.next();
        String word3line1 = scanner.next();
        String word1line2 = scanner.next();
        String word2line2 = scanner.next();
        
        System.out.println(word1line1);
        System.out.println(word2line1);
        System.out.println(word3line1);
        System.out.println(word1line2);
        System.out.println(word2line2);
    }
}

Example 4:

Sample Input:
Eugene
33
secondary
8
fusion

Sample Output:
The form for Eugene is completed. We will contact you if we need a chef that cooks fusion dishes.

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        String firstName = scanner.next();
        scanner.next();
        scanner.next();
        scanner.next();
        String cuisine = scanner.next();
        
        System.out.print("The form for " + firstName + " is completed." +  
            " We will contact you if we need a chef that cooks " + cuisine + " dishes.");
    }
}

Integer types and operations

Basic information about integer types

Java provides several types which represent integer numbers including positive, negative and zero. In practice, the most used types are int and long. The first type can store numbers from a smaller range than the second one, but it is often enough (especially, in this topic). You can perform all arithmetic operations (+, -, *, /, %) with variables of integer types.

int two = 2;
int ten = 10;

int twelve = two + ten; // 12
int eight = ten - two;  // 8
int twenty = two * ten; // 20
int five = ten / two;   // 5
int zero = ten % two;   // 0, no remainder

int minusTwo = -two; // -2

Example 1:

Find how many seconds passed between the two moments of time on the same day.

You are given the integer values representing these moments: hours, minutes and seconds for each of them. It is guaranteed that the earlier moment goes first in the input.

Input data format

The program gets the input of six integers: three defining the first moment of time in hours, minutes, seconds, and the other three defining the second one.

For example, six numbers 1, 2, 30, 15, 21, 1 will represent two moments of time: 1:02:30 am and 3:21:01 pm (or just 15:21:01).

Sample Input:
1
2
30
1
3
20

Sample Output:
50

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        int hourFirst = scanner.nextInt();
        int minutesFirst = scanner.nextInt();
        int secondsFirst = scanner.nextInt();
        int hourSecond = scanner.nextInt();
        int minutesSecond = scanner.nextInt();
        int secondsSecond = scanner.nextInt();
        
        System.out.print(hourSecond * 3600 + minutesSecond * 60 + secondsSecond 
            - hourFirst * 3600 - minutesFirst * 60 - secondsFirst);
    }
}

Example 2:

Given a two-digit number. Print its first digit (i.e. the number of tens).

Sample Input:
42

Sample Output:
4

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        int input = scanner.nextInt();
        
        System.out.print(input / 10);
    }
}

Example 3:

A university has decided to open math courses and equip classrooms for 3 groups with new special desks. The faculty agreed that for the sake of productivity, only two students may share one desk. The enrolment has ended, and now the task is to count the number of desks to order the correct number from the shop. Of course, the university is short of money, so you need to calculate the minimum number of desks. But don't forget that each group will sit in its own classroom!

Input data format

The program receives the input of the three non-negative integers: the number of students in each of the three groups (the numbers are not bigger than 1000).

Sample Input:
20
21
22

Sample Output:
32

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        int numStudent1 = scanner.nextInt();
        int numStudent2 = scanner.nextInt();
        int numStudent3 = scanner.nextInt();
        
        System.out.println(numStudent1 / 2 + numStudent1 % 2 
            + numStudent2 / 2 + numStudent2 % 2
            + numStudent3 / 2 + numStudent3 % 2);
    }
}

Increment and Decrement

int n = 10;
n++; // 11
n--; // 10

int n = 10;
n += 1; // 11
n -= 1; // 10

prefix (++n or --n) increases/decreases the value of a variable before it is used;
postfix (n++ or n--) increases/decreases the value of a variable after it is used.

Prefix increment:

int a = 4;
int b = ++a;

System.out.println(a); // 5
System.out.println(b); // 5

In this case, the value of a has been incremented and then assigned to b. So, b is 5.

Postfix increment:

int a = 4;
int b = a++;

System.out.println(a); // 5
System.out.println(b); // 4

In Java, the postfix operator has higher precedence than the assignment operator. However, it returns the original value of a, not the incremented one. That's why when we assign a++ to b, we actually assign 4, while a itself has already been incremented. So, b is 4 and a is 5.

Characters

A character can be also created using its hexadecimal code in the Unicode table. The code starts with \u.

char ch = '\u0040'; // it represents '@'
System.out.println(ch); // @

It is also possible to initialize a char with a positive integer number.

char ch = 64;
System.out.println(ch); // @

Escape sequences

'\n' is the newline character;
'\t' is the tab character;
'\r' is the carriage return character;
'\' is the backslash character itself;
'\'' is the single quote mark;
'\"' is the double quote mark.

System.out.print('\t'); // makes a tab
System.out.print('a');  // prints 'a'
System.out.print('\n'); // goes to the new line
System.out.print('c');  // prints 'c'

Output:
  a
c

1개의 댓글

comment-user-thumbnail
2024년 6월 17일

The Chennai Escorts Service is known for making customers happy. Their rosy cheeks, dark hair, and shiny lips easily catch your attention. These beautiful women have their own special likes, and their simple accessories can attract anyone

답글 달기