Язык программирования Java SE 8. Подробное описание.
Эта книга написана разработчиками языка Java и является полным техническим справочником по этому языку программирования. В ней полностью описаны новые возможности, добавленные в Java SE 8, включая лямбда-выражения, ссылки на методы, методы по умолчанию, аннотации типов и повторяющиеся аннотации. В книгу также включено множество поясняющих примечаний. В ней четко обозначены отличия формальных правил языка от практического поведения компиляторов.
Java является языком программирования общего назначения, ориентированным на параллельное выполнение и основанным на классах объектно-ориентированным языком. Он специально разрабатывался так, чтобы быть достаточно простым, так что многие программисты могут легко достичь высокой скорости работы.
Язык программирования Java является строго и статически типизированным. В дан ной спецификации четко различаются ошибки времени компиляции, которые могут и должны быть обнаружены во время компиляции, и ошибки, которые происходят во время выполнения.
Язык программирования Java — язык относительно высокого уровня, что проявляется, в частности, в том, что детали представления машинного кода в языке недоступны.
Сюда входят автоматическое управление памятью, обычно с использованием сборщика мусора (чтобы избежать проблем, связанных с явным освобождением памяти. Высокопроизводительные реализации сборки мусора могут ограничиваться работой в паузах выполнения программы, чтобы обеспечить возможность создания системных программ и приложений реального времени.
Язык не включает ни одной небезопасной конструкции, такой как доступ к массиву без проверки диапазонов индексирования, поскольку такие небезопасные конструкции могут приводить к неопределенному поведению программы.
Программа на языке Java обычно компилируется в набор команд байт-кода и бинарный формат, определенный в спецификации виртуальной машины Java The Java Virtual Machine Specification, Java SE 8 Edition.
Java Syntax
In the previous chapter, we created a Java file called Main.java , and we used the following code to print «Hello World» to the screen:
Example explained
Every line of code that runs in Java must be inside a class . In our example, we named the class Main. A class should always start with an uppercase first letter.
Note: Java is case-sensitive: «MyClass» and «myclass» has different meaning.
The name of the java file must match the class name. When saving the file, save it using the class name and add «.java» to the end of the filename. To run the example above on your computer, make sure that Java is properly installed: Go to the Get Started Chapter for how to install Java. The output should be:
The main Method
The main() method is required and you will see it in every Java program:
public static void main(String[] args)
Any code inside the main() method will be executed. Don’t worry about the keywords before and after main. You will get to know them bit by bit while reading this tutorial.
For now, just remember that every Java program has a class name which must match the filename, and that every program must contain the main() method.
System.out.println()
Inside the main() method, we can use the println() method to print a line of text to the screen:
public static void main(String[] args) < System.out.println("Hello World"); >
Note: The curly braces <> marks the beginning and the end of a block of code.
System is a built-in Java class that contains useful members, such as out , which is short for «output». The println() method, short for «print line», is used to print a value to the screen (or a file).
Don’t worry too much about System , out and println() . Just know that you need them together to print stuff to the screen.
You should also note that each code statement must end with a semicolon ( ; ).
Java Basic Syntax
Java program is an object-oriented programming language, that means java is the collection of objects, and these objects communicate through method calls to each other to work together. Here is a brief discussion on the Classes and Objects, Method, Instance variables, syntax, and semantics of Java.
Basic terminologies in Java
1. Class: The class is a blueprint (plan) of the instance of a class (object). It can be defined as a logical template that share common properties and methods.
- Example1: Blueprint of the house is class.
- Example2: In real world, Alice is an object of the “Human” class.
2. Object: The object is an instance of a class. It is an entity that has behavior and state.
- Example: Dog, Cat, Monkey etc. are the object of “Animal” class.
- Behavior: Running on the road.
3. Method: The behavior of an object is the method.
4. Instance variables: Every object has its own unique set of instance variables. The state of an object is generally created by the values that are assigned to these instance variables.
Example: Steps to compile and run a java program in a console
Java
Note: When the class is public, the name of the file has to be the class name.
Syntax:
1. Comments in Java
There are three types of comments in Java.
i. Single line Comment
// System.out.println("This is an comment.");
ii. Multi-line Comment
/* System.out.println("This is the first line comment."); System.out.println("This is the second line comment."); */
iii. Documentation Comment. Also called a doc comment.
2. Source File Name
The name of a source file should exactly match the public class name with the extension of .java. The name of the file can be a different name if it does not have any public class. Assume you have a public class GFG.
GFG.java // valid syntax gfg.java // invalid syntax
3. Case Sensitivity
Java is a case-sensitive language, which means that the identifiers AB, Ab, aB, and ab are different in Java.
System.out.println("GeeksforGeeks"); // valid syntax system.out.println("GeeksforGeeks"); // invalid syntax because of the first letter of System keyword is always uppercase.
4. Class Names
i. The first letter of the class should be in Uppercase (lowercase is allowed but discouraged).
ii. If several words are used to form the name of the class, each inner word’s first letter should be in Uppercase. Underscores are allowed, but not recommended. Also allowed are numbers and currency symbols, although the latter are also discouraged because they are used for a special purpose (for inner and anonymous classes).
class MyJavaProgram // valid syntax class 1Program // invalid syntax class My1Program // valid syntax class $Program // valid syntax, but discouraged class My$Program // valid syntax, but discouraged (inner class Program inside the class My) class myJavaProgram // valid syntax, but discouraged
5. public static void main(String [] args)
The method main() is the main entry point into a Java program; this is where the processing starts. Also allowed is the signature public static void main(String… args).
6. Method Names
i. All the method names should start with a lowercase letter (uppercase is also allowed but lowercase is recommended).
ii. If several words are used to form the name of the method, then each first letter of the inner word should be in Uppercase. Underscores are allowed, but not recommended. Also allowed are digits and currency symbols.
public void employeeRecords() // valid syntax public void EmployeeRecords() // valid syntax, but discouraged
7. Identifiers in java
Identifiers are the names of local variables, instance and class variables, and labels, but also the names for classes, packages, modules and methods. All Unicode characters are valid, not just the ASCII subset.
i. All identifiers can begin with a letter, a currency symbol or an underscore (_). According to the convention, a letter should be lower case for variables.
ii. The first character of identifiers can be followed by any combination of letters, digits, currency symbols and the underscore. The underscore is not recommended for the names of variables. Constants (static final attributes and enums) should be in all Uppercase letters.
iii. Most importantly identifiers are case-sensitive.
iv. A keyword cannot be used as an identifier since it is a reserved word and has some special meaning.
Legal identifiers: MinNumber, total, ak74, hello_world, $amount, _under_value Illegal identifiers: 74ak, -amount
8. White spaces in Java
A line containing only white spaces, possibly with the comment, is known as a blank line, and the Java compiler totally ignores it.
9. Access Modifiers: These modifiers control the scope of class and methods.
- Access Modifiers: default, public, protected, private.
- Non-access Modifiers: final, abstract, static, transient, synchronized, volatile, native.
10. Understanding Access Modifiers: