Lesson: A Closer Look at the «Hello World!» Application
Now that you've seen the "Hello World!" application (and perhaps even compiled and run it), you might be wondering how it works. Here again is its code:
The "Hello World!" application consists of three primary components: source code comments, the HelloWorldApp class definition, and the main method. The following explanation will provide you with a basic understanding of the code, but the deeper implications will only become apparent after you've finished reading the rest of the tutorial.
Source Code Comments
Comments are ignored by the compiler but are useful to other programmers. The Java programming language supports three kinds of comments:
/* text */ The compiler ignores everything from /* to */ . /** documentation */ This indicates a documentation comment (doc comment, for short). The compiler ignores this kind of comment, just like it ignores comments that use /* and */ . The javadoc tool uses doc comments when preparing automatically generated documentation. For more information on javadoc , see the Javadoc™ tool documentation . // text The compiler ignores everything from // to the end of the line.
The HelloWorldApp Class Definition
As shown above, the most basic form of a class definition is:
The keyword class begins the class definition for a class named name , and the code for each class appears between the opening and closing curly braces marked in bold above. Chapter 2 provides an overview of classes in general, and Chapter 4 discusses classes in detail. For now it is enough to know that every application begins with a class definition.
The main Method
In the Java programming language, every application must contain a main method whose signature is:
The modifiers public and static can be written in either order ( public static or static public ), but the convention is to use public static as shown above. You can name the argument anything you want, but most programmers choose "args" or "argv".
The main method is similar to the main function in C and C++; it's the entry point for your application and will subsequently invoke all the other methods required by your program.
The main method accepts a single argument: an array of elements of type String .
This array is the mechanism through which the runtime system passes information to your application. For example:
Each string in the array is called a command-line argument. Command-line arguments let users affect the operation of the application without recompiling it. For example, a sorting program might allow the user to specify that the data be sorted in descending order with this command-line argument:
The "Hello World!" application ignores its command-line arguments, but you should be aware of the fact that such arguments do exist.
Finally, the line:
uses the System class from the core library to print the "Hello World!" message to standard output. Portions of this library (also known as the "Application Programming Interface", or "API") will be discussed throughout the remainder of the tutorial.
Java Tutorial — A Beginner’s Guide To Java Programming
![]()
In this Java Tutorial blog, I am going to introduce you to some of the basic concepts of Java. But before moving ahead, I would suggest you get familiar with what is Java, features of Java and how can you install Java on your system. This will help you grab the coming concepts quickly and easily.
Now, let us move ahead in this Java Tutorial blog, where we will understand each aspect of Java in the following sequence:
- Hello World Program
- Member variables in Java
- Data types and operators
- Control Statements
- Classes & Objects
- Structure of a program
- Arrays
- OOPs concept — Inheritance, Encapsulation, Polymorphism, Abstraction
Let’s get started with the first topic in Java Tutorial blog i.e Hello World Program.
Hello World Program
First of all, I will give you a simple overview of how a Java program looks like. In the below code, I have created a class — MyFirstJavaProgram and printed “Hello World”. Go ahead and try to execute the below example in your Eclipse IDE. Do not worry, we will discuss Java class in a while.
Next, let us understand different member variables in Java.
Member Variables
A member variable plays a major role in a class as it is used to store a data value. When we define a class, we can declare a member variable. These variables are members of a class.
Member variables are further classified into three types:
- Local variable
- Instance variable
- Class/Static variable
Let me discuss each one of them:
Local variable:
These are the variables which are declared within the method of a class. Let’s understand this with a programmatic example:
In the above code, my local variable is ‘model’ which I have declared inside a method ‘display’ which has a parameter ‘m’.
Instance variable:
An instance variable is declared in a class but outside a method, constructor or any block. Let’s understand this with a programmatic example.
In the above code, ‘color’ is my instance variable which has a value “black” associated with it.
Class variable:
Class variables are also called static variables. These variables have only one copy that is shared by all the different objects in a class. Let’s understand this with a programmatic example.
All cars must be having 4 tyres, right? So in my above code, I have declared a static variable as ‘tyre’ whose value remains same throughout the class.
Let’s move ahead in this article and look at our next topic i.e data types and operators in Java.
Data types
A data type is used to represent different values which are stored in a variable. They are mainly classified into 4 different aspects — Integer, Float, Character, and Boolean. You can refer to the below image to understand the different data types with respect to the memory allocated to them.
As you can see in the above image, data types are of 4 major types.
- The first data type is an Integer which stores a numerical value.
- Now, if a numerical value contains a decimal part, it will be referred to as float.
- Next, if you wish to store a character, then the third data type i.e char is used. In char, you can store any alphabetical character as well as a special character.
- The last data type is Boolean which stores only ‘true’ or ‘false’ value.
Let’s move forward and look at the various data operations which you can perform in Java.
Data Operators
There are mainly 4 different types of operators, which are listed below:
- Arithmetic Operator: Perform arithmetic operations such as addition, subtraction, multiplication, division, and modulus.
- Unary Operator: Unary operators are used to increment or decrement a particular value. For example: ++ stands for increment, — — stands for decrement.
- Relational Operator: It defines some kind of relation between two entities. For example: <, >, <=, >=, !=, ==.
- Logical Operator: Logical operators are typically used with boolean (logical) values.
Next, let us move forward and understand the concept of control statements.
Control statements
Control statements are the statements that define the flow of your program. There are 3 types of control statements in Java: Selection, iteration, and jump statements.
Let us see these control statements one by one.
Selection Statements:
Selection statements allow you to control the flow of the program during runtime on the basis of the outcome of expression or state of a variable. For example: you want to eat pizza, but then where can you get that pizza at the best price. You can select between various popular options like Domino’s, Pizza Hut or any other outlet. So here you are following a selection process from the various options available.
Now, these statements can be further classified into the following:
- If-else Statements
- Switch Statements
Refer to the following flowchart to get a better understanding of if-else statements:
In this flowchart, the code will respond in the following way:
- First of all, it will enter the loop where it checks the condition.
- If the condition is true, the set of statements in ‘if’ part will be executed.
- If the condition is false, the set of statements in the ‘else’ part will be executed.
Here you must have got an idea of how these if-else statements work. Now, how can we use these statements in Eclipse IDE? Let’s have a look at the code:
In the above code, I have created a class Compare where I have compared two numbers ‘a’ and ‘b’. First of all, it will go in ‘if’ condition where it checks whether the value of ‘a’ is greater than ‘b’ or not. If the condition is true, it will print “A is greater than B” else it will execute “B is greater”.
Moving on, we have a Switch case statement. The switch statement defines multiple paths for execution of a set of statements. It is a better alternative than using a large set of if-else statements as it is a multi-way branch statement.
Refer to the following flowchart to get a better understanding of switch statements:
In this Switch case flowchart, the code will respond in the following steps:
- First of all, it will enter the switch case which has an expression.
- Next, it will go to Case 1 condition, checks the value passed to the condition. If it is true, Statement block will execute. After that, it will break from that switch case.
- In case it is false, then it will switch to the next case. If Case 2 condition is true, it will execute the statement and break from that case, else it will again jump to the next case.
- Now let’s say you have not specified any case or there is some wrong input from the user, then it will go to the default case where it will print your default statement.
Again, if we look at the code for switch statements in IDE, here it is:
In the above code, I have created a class SwitchExample which has 3 cases that print days of a week. It also has a default case which is executed whenever a user doesn’t specify a case.
Concluding both of the selection statements, we understood that if we are comparing two statements, we are using if-else, but let’s say if you are checking a specific value against a particular statement, then we are going for the Switch statement.
Next, there is another set of control statements, i.e Iteration Statements.
Iteration Statements:
In Java, these statements are commonly called loops, as they are used to iterate through small pieces of code. Iteration statements provide the following types of loop to handle looping requirements.
Let’s understand each one of them in detail:
While statement:
Repeat a group of statements while a given condition is true. It tests the condition before executing the loop body. Let’s understand this better with a flowchart:
In this flowchart, the code will respond in the following steps:
- First of all, it will enter the loop where it checks the condition.
- If it’s true, it will execute the set of code and repeat the process.
- If it’s False, it will directly exit the loop.
Now, let us see how you can implement the code in IDE.
In the above code, it first checks the condition whether the value of a is less than 10 or not. Here, the value of a is 5 which in turn satisfy the condition, and thus perform functions.
Do-while statement:
It is like a while statement, but it tests the condition at the end of the loop body. Also, it will execute the program at least once. Let’s understand this better with a flowchart:
In this do-while flowchart, the code will respond in the following steps:
- First of all, it will execute a set of statements that is mentioned in your ‘do’ block.
- After that, it will come to ‘while’ part where it checks the condition.
- If the condition is true, it will go back and execute the statements.
- If the condition is false, it will directly exit the loop.
Let’s see how you can implement the code in IDE.
In the above code, it will first execute the ‘do’ statements and then jump to the while part. In this program, the output would be: 1 2 3 4 5 6 7 8 9.
For statement:
For statement execute a sequence of statements multiple time where you can manage the loop variable. You basically have 3 operations here: initialization, condition, and iteration. Let’s understand this better with a flowchart:
In this flowchart, the code will respond in the following steps:
- First of all, it will enter the loop where it checks the condition.
- Next, if the condition is true, the statements will be executed.
- If the condition is false, it directly exits the loop.
Let’s see how you can implement the code in IDE.
In the above code, it will directly print the numbers from 1 to 10.
The last type of control statement we will be discussing is Jump Statement.
Jump statement:
Jump statements are used to transfer the control to another part of your program. These are further classified into — break and continue.
Let’s learn about them in detail:
Break statement:
Whenever a break statement is used, the loop is terminated and the program control is resumed to the next statement following the loop. Let’s understand this better with a flowchart:
In this flowchart, the code will respond in the following steps:
1. First of all, it will enter the loop where it checks the condition.2. If the loop condition is false, it directly exits the loop.
3. If the condition is true, it will then check the break condition.
4. If break condition is true, it exists from the loop.
5. If the break condition is false, then it will execute the statements that are remaining in the loop and then repeat the same steps.
The syntax for this statement is just the ‘break’ keyword followed by a semicolon.
Continue statement:
Continue statement is another type of control statements. The continue keyword causes the loop to immediately jump to the next iteration of the loop. Let’s understand this better with a flowchart:
In this flowchart, the code will respond in the following steps:
1. First of all, it will enter the loop where it checks the condition.
2. If the loop condition is false, it directly exits the loop.
3. If the loop condition is true, it will execute block 1 statements.
4. After that it will check for ‘continue’ statement. If it is present, then the statements after that will not be executed in the same iteration of the loop.
5. If ‘continue’ statement is not present, then all the statements after that will be executed.
The syntax is just the ‘continue’ keyword followed by a semicolon.
Next, let us see what are classes and objects in Java.
Classes and Objects
A class in Java is a blueprint that includes all your data. A class contains fields(variables) and methods to describe the behavior of an object. Let’s have a look at the syntax of a class.
But how can you access these member variables and methods? Here comes the concept of Object.
An object is a major element in a class which has a state and behavior. It is an instance of a class which can access your data. Let’s see the syntax to create an object in Java:
Here, Student is your class name followed by the name of the object. Then there is a “new” keyword which is used to allocate memory. Finally, there is a call to the constructor. This call initializes the new object.
Now let’s see how can you call a method using an object in Java:
Next, let us move ahead in our Java Tutorial blog where we’ll be discussing another key concept i.e. Arrays.
Arrays
Arrays in Java is similar to that of C++ or any other programming language. An array is a data structure which holds the sequential elements of the same type.
Let’s say you want to store 50 numbers. Instead of declaring individual variables, such as number0, number1, … and so on. You can declare one array variable — “numbers” and use number[0], number[1] to represent individual variables. This will ease your task and minimizes the redundancy.
Each array has two components: index and value. Refer to the below image for better understanding:
Here the indexing starts from zero and goes till (n-1) where n= size of the array. Let’s say you want to store 10 numbers, then the indexing starts from zero and goes till 9.
There are two types of arrays in Java:
- Single-dimension Array
- Multi-dimension Array
Single-dimension Array:
In a single-dimension array, a list of variables of the same type can be accessed by a common name. You can initialize the array using the following syntax:
int a[] = new int[12];
You can refer to the below image where I have stored data with respect to the given index.
Multi-dimension Array:
In a multi-dimension array, your data is stored in a matrix form. Here, you can initialize the array using the following syntax:
int table[][]= new int[4][5];
It is quite similar to the matrix that we use in mathematics. Refer to the below image where I have stored data with respect to different dimensions.
Thus, arrays help you in optimizing the code where you can insert the data at any location.
Let’s see the below code to understand the concept of an array in Java.
In the above code, I have explained how you can take input for the array and print the same.
I hope you guys are clear with how an array looks like and how do you initialize one. Now, let’s summarize the above topics and see the entire structure of a Java program.
Structure of a Program
Till now, we have learned about member variables, data types, control statements, classes and objects. Let’s see how all of them are structured together in a class in Java.
Finally, we come to our last topic in our articlei.e Object Oriented programming concepts.
OOPs Concept
We have already discussed classes and objects in Java. Let’s discuss the 4 main concepts of object-oriented programming — Inheritance, Encapsulation, Polymorphism, and Abstraction.
Let’s begin with the first concept i.e. Inheritance.
Inheritance:
Most of you must be familiar with inheritance. Inheritance is a process where one class acquires the properties of another. But whose properties are inherited? Here we have two classes, a child class which inherits the properties of a base class.
A Class which inherits the properties are known as Child class. It is also referred to as the derived class or a subclass. Next, the class whose properties are inherited are known as Parent class or a base class.
Let’s understand these classes by looking at this real-life example of animals.
In the above image, Animal is the superclass whereas amphibians, reptiles, mammals, and birds are your child classes which are inheriting the properties from ‘Animal’ class.
Encapsulation:
Encapsulation in Java is a mechanism of wrapping up the data and code together as a single unit. Refer to the below image where all your methods, variables are binded together in a single class.
In encapsulation, the variables of a class will be hidden from other classes and can be accessed only through the methods of their current class.
Polymorphism:
Polymorphism is the ability of a variable, function or object to take multiple forms. The most common use of polymorphism in OOPs occur when a parent class is used to refer a child class object. Polymorphism is also achieved through function overloading. Don’t worry! I will be explaining the whole concept in my next blog. For now, let’s take a real life scenario where a teacher tells the student to draw different shape/figure having different functionalities.
Let’s say I want to draw a specific shape which already has multiple functions present as part of my program. So the functions that are dealing with shape, I’ll call them as draw(). Now based on the values that I have passed to these functions, it will draw different shapes. Let’s say in case of a rectangle, I am passing two values — length and breadth. Similarly, for a circle, I am passing a radius. Based on the values you pass, the different function will be called that serve different purposes. So this can be achieved through function overloading. Stay tuned, the concept of function overloading will be covered in detail in my next blog.
Abstraction:
It is basically the quality of dealing with ideas rather than events. Abstraction is the methodology of hiding the implementation details from the user and only providing the functionality to the users. Let’s see this real-life example of a car where I’ll help you understand what exactly abstraction is.
If you consider the case of this car, here the mechanic is repairing a certain function in a car. But the user or you can say driver doesn’t want to know about these things, he just wants his car back in a working condition. So here, you basically segregate the implementation and show the other person what he actually wants to see and that exactly refers to abstraction.
With this, we come to an end to this blog.If you wish to check out more articles on the market’s most trending technologies like Artificial Intelligence, DevOps, Ethical Hacking, then you can refer to Edureka’s official site.
Do look out for other articles in this series which will explain the various other aspects of Java.
Java: краткое руководство для начинающих. Пишем простое приложение без опыта программирования
Java – один из самых востребованных языков программирования в мире и один из двух официальных языков программирования, используемых в разработке Android (другой – Kotlin). Разработчики, знакомые с Java, весьма востребованы и способны создавать широкий спектр различных приложений, игр и инструментов. С помощью этой краткой статьи по Java для начинающих вы сможете сделать свои первые шаги к тому, чтобы стать одним из таких разработчиков. Мы рассмотрим все, что вам нужно знать, чтобы начать работу, и поможем вам создать свое первое простое приложение.
Что такое Java?
Java-это объектно-ориентированный язык программирования, разработанный компанией Sun Microsystems в 1990-х годах (позже купленной Oracle).
Понятие «объектно-ориентированный» относится к способу написания структурного кода Java, а именно: разделение кода на так называемые «классы», которые запускаются вместе, чтобы обеспечить согласованное порождение объектов. Мы обсудим это позже, но достаточно сказать, что это приводит к универсальному и организованному коду, который легко редактировать и перепрофилировать.
Java находится под влиянием C и C++, поэтому она имеет много общего с этими языками (и C#). Одним из больших преимуществ Java является то, что он «платформенно-независимый». Это означает, что код, который вы пишете на одной платформе, можно легко запустить на другой. Это называется принципом «пишем один раз, запускаем где угодно» (хотя на практике это не всегда так просто, как кажется).
Чтобы запустить и использовать Java, вам нужно три вещи:
- JDK – Java Development Kit
- JRE – Java Runtime Environment
- JVM – Java Virtual Machine
Виртуальная машина Java (JVM) гарантирует, что у ваших приложений Java есть доступ к минимальным ресурсам, необходимым для их запуска. Именно благодаря JVM программы Java так легко запускаются на разных платформах.
Среда исполнения Java (JRE) предоставляет собой «контейнер» для всех этих элементов и кода для запуска приложения. JDK – это «компилятор», который интерпретирует сам код и выполняет его. В JDK также есть инструменты разработчика, необходимые для написания кода Java (как и следует из названия).
Хорошая новость заключается в том, что разработчикам нужно только позаботиться о загрузке JDK, поскольку он поставляется вместе с двумя другими компонентами.
Как начать писать на Java
Если вы планируете разрабатывать приложения на Java на своем настольном компьютере, то вам нужно будет загрузить и установить JDK.

Вы можете получить последнюю версию JDK непосредственно с сайта Oracle. Как только вы установите его, ваш компьютер будет иметь возможность понимать и запускать код на Java. Тем не менее, вам все равно понадобится некоторое вспомогательное ПО, чтобы было действительно удобно писать код. Это так называемая «интегрированная среда разработки» или IDE: интерфейс, используемый разработчиками для ввода текста кода и вызова JDK.
При разработке для Android вы будете использовать IDE Android Studio. Она не только послужит интерфейсом для кода на Java (или Kotlin), но и станет мостом для доступа к специфичным для Android вызовам из SDK.
Для целей нашего краткого руководства по Java может быть и проще написать свой код непосредственно в приложении-компиляторе Java. Они могут быть скачаны для Android и iOS, можно даже найти веб-приложения, которые работают в вашем браузере. Эти инструменты предоставляют все необходимое в одном месте и позволяют сразу начать тестирование кода. Например, compilejava.net.
Насколько легко научиться программированию на Java?
Если вы новичок в разработке на Java, то ваши опасения вполне понятны. Так насколько же легко изучить Java?
Этот вопрос имеет несколько субъективную природу, но лично я бы отнес Java к языкам, не самым простым для изучения. Хотя он проще, чем C++, и часто описывается как более удобный для пользователя, но он, безусловно, не столь прост, как такие его конкуренты, как Python или BASIC, которые больше подходят для изучения начинающим программистам.
C# также немного проще по сравнению с Java, хотя они очень похожи.
Конечно, задавшись конкретной целью – стать разработчиком приложений для Android, – проще всего сразу начать с языка, который уже поддерживается этой платформой.
У языка Java есть свои особенности, но его, безусловно, можно изучить, и как только вы его освоите, вам откроется множество возможностей. А поскольку Java имеет много общего с C и C#, вы сможете перейти на эти языки без особых усилий.
Каков синтаксис Java?
Прежде чем мы погрузимся в самую суть этого руководства по Java для начинающих, стоит уделить некоторое время изучению синтаксиса Java.
Синтаксис Java относится к способу написания конкретных алгоритмов. Java очень принципиален в этом вопросе, и, если вы не пишете код определенным образом, то ваша программа не будет работать!
На самом деле я написал целую статью о синтаксисе Java для разработки Android, кратко перечислю особенности синтаксиса:
- Большинство строк должно заканчиваться точкой с запятой «;».
- Исключение составляет строка, открывающая новый блок кода. Она должна начинаться открытой фигурной скобкой « <». В качестве альтернативы эту открытую скобку можно поместить на новую строку под оператором. Блоки кода – это фрагменты кода, которые выполняют определенные, отдельные задачи.
- Код внутри блока кода должен иметь отступ, чтобы отделить его от остальных.
- Открытые блоки кода должны быть закрыты закрывающей фигурной скобкой «>».
- Комментарии – это строки, которым предшествуют символы «//».
Если вы нажимаете кнопку «запустить» или «скомпилировать» и получаете ошибку, то есть большая вероятность, что вы где-то пропустили точку с запятой!
Вы никогда не перестанете делать это, и это никогда не перестанет вас раздражать. Расслабьтесь!
С этими знаниями мы сможем глубже погрузиться в руководство по Java!
Основы Java: ваша первая программа
Зайдите на compilejava.net, и вас встретит редактор с кучей готовых примеров.
(Если же вы предпочитаете использовать другую IDE или стороннее приложение, это тоже прекрасно! Скорее всего, ваш новый проект будет состоять из аналогичного кода).
Удалите все, кроме следующего:
Это то, что мы, программисты, мы называем «шаблоном» (этот код скопирован из учебника Java от Фила Данфи). Шаблонный код – так можно назвать любой код, который встречается внутри практически любой программы.
Первая строка здесь определяет «класс», который по сути является модулем кода. Затем нам нужен метод внутри этого класса, который представляет собой небольшой блок кода, выполняющий задачу. В каждой программе Java должен быть метод main, так как он сообщает Java, где начинается программа.
Об остальном поговорим чуть ниже, не беспокойтесь. Все, что нам нужно знать для этого урока Java прямо сейчас, – это то, что код, который мы действительно хотим запустить, должен быть помещен в фигурные скобки под словом «main».
Поместите сюда следующий оператор:
Этот оператор напишет слова: «Hello world!» на вашем экране. Нажмите «Compile & Execute» и вы увидите его в действии.
Поздравляю! Вы только что написали свое первое Java-приложение!
Переменные в Java
Теперь пришло время рассказать о некоторых более важных вещах, лежащих в основе Java. Мало что может быть более фундаментальным в программировании, чем обучение использованию переменных!
Переменная по сути является «контейнером» для некоторых данных. Это означает, что вы выберете слово, которое будет представлять какое-то значение. Нам также необходимо определить переменные, основанные на типе данных, на которые они будут ссылаться.
Вот три основных типа переменных, которые мы собираемся ввести в этом руководстве по Java:
- Целые числа (integers) – как целые числа.
- Плавающие точки (floats) – или «переменные с плавающей точкой». Они содержат все числа, в том числе те, которые представляют десятичные дроби. «Плавающая точка» относится к десятичному разряду.
- Строки (strings)– строки содержат буквенно-цифровые символы и символы. Обычно строка используется для хранения чьего-то имени или, возможно, предложения.
Как только мы определяем переменную, мы можем вставить ее в наш код, чтобы изменить выходные данные. Например:
В этом примере кода мы определили строковую переменную с именем name . Мы сделали это, используя тип данных String , за которым следует имя нашей переменной, а затем данные. Когда вы помещаете что-то в двойные кавычки, то Java интерпретирует это дословно как строку.
Теперь мы печатаем на экране, как и раньше, но на этот раз заменяем «Hello world!» на «Hello + имя». Этот код показывает строку «Hello», за которой следует любое значение, содержащееся в следующей строковой переменной!
Самое замечательное в использовании переменных заключается в том, что они позволяют нам манипулировать данными, чтобы наш код мог вести себя динамически. Изменяя значение name , вы можете изменить поведение программы, не изменяя никакого фактического кода!
Условные операторы в Java
Еще одна из самых важных основ Java – это работа с условными операторами.
Условные операторы используют блоки кода, которые выполняются только при определенных условиях. Например, мы можем захотеть предоставить специальные пользовательские права основному пользователю нашего приложения.
Посмотрите на следующий код:
Запустите этот код, и вы увидите, что специальные разрешения предоставлены. Но, если вы измените значение name на что-то другое, то код не будет работать.
В этом коде используется оператор if . Он проверяет, является ли утверждение, содержащееся в скобках, истинным. Если это так, то будет запущен следующий блок кода. Не забудьте сделать отступ в коде, а затем закрыть блок в конце! Если оператор в скобках имеет значение false, то код просто пропустит этот раздел и продолжит работу с закрытых скобок.
Обратите внимание, что при наложении условия на данные мы используем два знака «=». Вы же используете только один, когда присваиваете какие-то данные переменным.
Методы на Java
Еще одна простая концепция, которую мы можем ввести в этом руководстве Java – это использование методов. Это даст вам немного больше понимания того, как структурирован Java-код и что с ним можно сделать.
Все, что мы собираемся сделать, – это взять часть кода, который мы уже написали, а затем поместить его в другой метод вне метода main :
Мы создали новый метод в строке, которая начинается со static void . Это означает, что метод определяет функцию, а не свойство объекта, и что он не возвращает никаких данных.
Но все, что мы вставляем в следующий блок кода, теперь будет выполняться каждый раз, когда мы «вызываем» метод, записывая его имя в нашем коде: grantPermission() . Затем программа выполнит этот блок кода и вернется к точке, из которой она вышла.
Если бы мы написали вызов grantPermission() несколько раз, то сообщение «Special user priveleges granted» также отобразилось бы несколько раз. Именно это делает методы такими фундаментальными основами Java: они позволяют выполнять повторяющиеся задачи, не записывая код снова и снова.
Передача аргументов в Java
Но самое замечательное в методах то, что они могут принимать переменные и манипулировать ими. Мы сделаем это, передав переменные в наши методы как «строки». Вот для чего и нужны скобки, следующие за названием метода.
В следующем примере я создал метод, который получает строковую переменную, названную nameCheck . Затем я могу обратиться к nameCheck из этого блока кода, и ее значение будет равно тому, что я поместил в фигурные скобки, когда вызвал метод.
Для этого руководства по Java я передал значение name методу и поместил туда оператор if . Таким образом, мы можем проверять несколько имен подряд, не набирая один и тот же код снова и снова.
Надеюсь, это даст вам представление о том, насколько мощными могут быть методы!
В завершение
Надеюсь, теперь у вас есть хорошее представление о том, как изучать Java. Вы даже можете сами написать какой-нибудь простой код: используя переменные и условные операторы, вы действительно можете заставить Java делать некоторые интересные вещи уже сейчас.
Следующий этап состоит в понимании объектно-ориентированного программирования и классов. Это понимание есть то, что действительно дает Java и подобным языкам их силу, но поначалу может быть немного сложным для осмысления.
1. Основы Java.
Java является объектно-ориентированным языком, поэтому всю программу можно представить как набор взаимодействующих между собой классов и объектов. Простейшая программа на Java представлена следующим образом:
То есть основу программы составляет класс Program . При определении класса вначале идет модификатор доступа public , который указывает, что данный класс будет доступен всем, в том числе для JVM, и мы сможем его запустить из командной строки. Далее идет ключевое слово class , а затем название класса. После названия класса идет блок кода, в котором расположено содержимое класса.
Входной точкой в программу на языке Java является метод main , который определен в классе Program . Именно с него начинается выполнение программы. Он обязательно должен присутствовать в программе. При этом его заголовок может быть только таким:
При запуске приложения виртуальная машина Java (JVM) ищет в главном классе программы метод main с подобным заголовком, и после его обнаружения запускает его. Если метод отсутствует, то компиляция возможна, но при запуске будет получена ошибка Error: Main method not found .
Вначале заголовка метода идет модификатор public , который указывает, что метод будет доступен извне. Слово static указывает, что метод main — статический (не связан с конкретным объектом), а слово void — что он не возвращает никакого значения. Далее в скобках у нас идут параметры метода — String args[] — это массив args , который хранит значения типа String , то есть строки. При запуске программы через этот массив мы можем передать в программу различные данные.
После заголовка метода идет его блок, который содержит набор выполняемых инструкций.
Структура программы
Основным строительным блоком программы на языке Java являются инструкции (statement). Каждая инструкция выполняет некоторое действие, например, вызовы методов, объявление переменных и присвоение им значений. После завершения инструкции в Java ставится точка с запятой ( ; ). Данный знак указывает компилятору на конец инструкции. Например:
Данная строка представляет вызов метода System.out.println , который выводит на консоль строку Hello Java! . В данном случае вызов метода является инструкцией и поэтому завершается точкой с запятой.
Кроме отдельных инструкций распространенной конструкцией является блок кода. Блок кода содержит набор инструкций, он заключается в фигурные скобки, а инструкции помещаются между открывающей и закрывающей фигурными скобками:
Комментарии
Код программы может содержать комментарии. Комментарии позволяют понять смысл программы, что делают те или иные ее части. При компиляции комментарии игнорируются и не оказывают никакого влияния на работу приложения и на его размер.
В Java есть два типа комментариев: однострочный и многострочный. Однострочный комментарий размещается на одной строке после двойного слеша // . А многострочный комментарий заключается между символами /* текст комментария */ . Он может размещаться на нескольких строках. Например:
Существует продвинутый (и более сложный формат комментариев), называемый JavaDoc. Он используется совместно с одноименной утилитой, входящей в состав JDK, и предназначен для создания документации разработчика из исходного кода. Такие комментарии используются при разработке крупных и средних проектов, и нужны для описания классов, методов и других объектов с целью упрощения разработки. Комментарий JavaDoc пишется на языке HTML, может содержать метаинформацию (например, описание параметров метода). Такие комментарии также поддерживаются средами разработки для создания подсказок. Пример метода с JavaDoc комментариями представлен ниже. JavaDoc комментарий является обычным многострочным комментарием, но начинается с /** на отдельной строчке.
Переменные и константы
Для хранения данных в программе предназначены переменные.
Переменная – это именованная область памяти, в которой программа может установить некоторое значение. Значение переменной может изменяться во время выполнения программы.
Переменная определяется комбинацией идентификатора (имени), типа и необязательного инициализатора. Переменная должна быть объявлена перед ее использованием.
Идентификаторы используются в качестве имен классов, методов и переменных. Идентификатор может быть любой последовательностью букв верхнего и нижнего регистра (в том числе, кириллических), чисел или символов подчеркивания _ и знака доллара ( $ ). Он не должен начинаться с цифры, чтобы не вступать в конфликт с числовой константой. Язык Java чувствителен к регистру, поэтому идентификатор VALUE , например, отличается от идентификатора Value .
Тип, также называемый тип данных, определяет, какую информацию может хранить переменная или диапазон допустимых значений.
Синтаксис объявления переменной:
- type – один из типов Java, имя класса или интерфейса,
- identifier – имя переменной,
- value – литерал (значение подходящего типа) или выражение.
Примеры объявления переменной:
Начиная с Java 10 в язык было добавлено ключевое слово var , которое также позволяет определять переменную:
Слово var ставится вместо типа данных, а сам тип переменной выводится из того значения, которое ей присваивается. Например, переменной x присваивается число 10 , значит, переменная будет представлять целочисленный тип int .
Но если переменная объявляется с помощью var , то ее необходимо обязательно инициализировать, то есть предоставить ей начальное значение, иначе мы получим ошибку, как, например, в следующем случае:
Начинающим разработчикам рекомендуется использовать var в тех случаях, когда тип легко понять из выражения справа, и использовать явное указание типа в других случаях.
Кроме переменных, в Java для хранения данных можно использовать константы. В отличие от переменных константам можно присвоить значение только один раз. Константа объявляется также, как и переменная, только вначале идет ключевое слово final :
Константы позволяют задать такие переменные, которые не должны больше изменяться. Например, если у нас есть переменная для хранения числа pi , то мы можем объявить ее константой, так как ее значение постоянно.
Типы данных
Язык Java является строго типизированным. А это значит, что каждая переменная и константа представляет определенный тип и данный тип строго определен. Тип данных определяет диапазон значений, которые может хранить переменная или константа.
В Java существует два вида типов данных — примитивные(рассмотрены выше) и ссылочные.
Примитивные типы
Итак, рассмотрим систему встроенных базовых типов данных, которая используется для создания переменных в Java. А она представлена следующими типами.