Java programming language learning from scratch. A selection of books for Java programmers with various experiences

  • 2 months of Java EE training (2 times a week for 4 hours)
  • if you show good results (you successfully defend your project, which you have been writing for these two months), then you are offered a job.
The company is very good, foreign, well-known, and the working conditions are excellent - in short, I wanted to go there much more than the place where they had already made me an offer. Selection for training with her involved 3 stages:
  1. Doing practical tasks at home.
  2. If successful, you are invited to computer testing in the office.
  3. If the test is successful, you will be interviewed on the same day.
I completed the practical tasks without any problems - many thanks to JavaRush and their problems, after which these tasks seemed quite simple. There were 3 tasks: on RegExp (Google helped, because I myself couldn’t stand them and didn’t remember), on algorithms (quite simple, more of a mental exercise) and on writing/reading from a file (there are a lot of these in the JavaRush course). I was invited to computer testing. I prepared for testing using the quizful website. These tests helped a lot, some questions even ended up intersecting. I passed the test successfully and they started interviewing me. I will probably never forget this interview in my life. All the person interviewing me wanted to hear from me was the basics of Java theory, such as:
  • what is the difference between checked exceptions and unchecked;
  • what methods does the Object class have and why are they needed;
  • what kinds of collections are there and why are they;
  • and a little about multithreading.
JavaRush is an excellent course, it will teach you how to solve problems and program, but the theory (for interviews) needs to be learned separately, as I was convinced of by swimming in these issues like a fish in an aquarium. They wanted to wrap me up. I understand him - I couldn’t clearly answer almost anything, I tried to tell everything from the point of view of writing code, but he was interested in theory. But I knew for sure that I really wanted to get into this internship, and I knew that if they gave me time, I would catch up on all this and learn the unfortunate theory. I told him all this, and he met me halfway - he offered to meet again in a week, but for now he gave me a list of topics (approximately as I described above) and said where they can be learned - just an Oracle tutorial, it contains all: http://docs.oracle.com/javase/tutorial/ Over the course of a week, I thoroughly studied this tutorial and went for a second interview the day before I was expected at a new job. Apparently, the person who interviewed me was most impressed by my sense of purpose (I knew that if I accepted this internship, what happened next depended only on me - in two months I would have figured out everything I needed). Be that as it may, I accepted this internship and refused to go to work at the place where I was previously offered. Over the course of 2 months, we were introduced to many topics from Java EE, such as: Servlets, JSP, Hibernate JSF, Spring and much, much more - as a result of the internship, we were familiar (we had a rough idea) about the main stack of Java EE technologies. Also, during the internship, we wrote our own project, which at the end had to be successfully presented for employment. I just remember my first feelings when I was at the first lecture. I looked at the assignment for this project (it was given immediately at the very first lecture) and did not even understand where to start and how to do it. I also remember what it took me to successfully do it. These two months, almost all the thoughts in my head were that successful employment and the fulfillment of a dream were in my hands and nothing more. It didn’t depend on anyone else whether I could do it. Only from me. I had already quit my job, had almost no money, and it was really hard. I sat in the morning, sat during the day, sat in the evening, but never tired of rejoicing - I don’t remember when I devoted myself to something with such obsession. This time once again helped me realize how much I like programming and how much I would like to work in this field. At graduation I presented my project. I defended it really well, apparently much better than expected, and as an exception, I was hired not for the initial position, but immediately for the position of Middle Java Developer. It was December 9, 2014. I couldn't believe it, but the job offer was in front of me on my monitor. Software engineer. It happened. I went back to work on December 15th. Never once have I had the thought “damn, I don’t want to go to work.” Every day, leaving home in the morning, I know why I am going to work, what I will do, and how much I want it. This makes me incredibly happy. It is worth and was worth the price you had to pay to achieve your dream. I wish all of you who really want to be a programmer go ahead in achieving your goal. It is more than real, it is very close, but you have to pay for it. Pay with your wasted time and nerves, because learning something from scratch is really not the easiest step. JavaRush helped me take these first steps with ease, and I wasn't the one who turned away from programming at the very beginning because of the apparent complexity and abundance of theory. Thus, I was able to bring my rather crazy idea of ​​​​a radical change in the field of professional activity (even in the absence of technical education) to the end. And you definitely can.

We are accustomed to quick access to information and equally rapid absorption. We prefer five-minute videos to deep lectures and short articles to books. I will not claim that a good book on programming will replace any article, this is not so. And it certainly won’t replace practice. However, for me personally, a real understanding of the basics of programming came after I, having solved hundreds of problems in a programming course and read a ton of articles, began to simultaneously study the theory from books and delved into them well. I have been searching for my personal “best Java tutorial for beginners” for quite some time. Below are several books that were useful to me to a greater or lesser extent at different stages of my studies. "For the little ones" You can start reading the next two books at the start of your studies, in parallel with the video, or, if you study with JavaRush, along with the first levels. They, especially the first one, are suitable for people with zero programming background.

Head First Java

I started with this book not because it is my favorite, but because it is the simplest. This book, according to many programmers, is the best Java tutorial from scratch. Moreover, it is truly and completely “from scratch”, that is, it is suitable for those who are just starting out and do not yet quite understand what kind of beast programming is. She came to me too late. I think that's why I couldn't appreciate it. It was very pleasant to “just read” it, but I had to look for something specific in it for a long time. The material there is presented vividly, but rather superficially (because it’s from scratch!) and many topics and necessary explanations are simply not there. But my friend, to whom it was inherited, was delighted with it and shouted that this was not just the best Java textbook for beginners, but a real world masterpiece and this is how complex material should be presented. Advantages:
  • The best Java tutorial from scratch, for complete dummies, written in living language;
  • Cool illustrations and humor;
  • Explanations with real-life examples.
Flaws:
  • A lot of “water” for those who have already entered into the topic;
  • Not always successful puzzles and exercises.

Herbert Shildt. Java 8 Beginner's Guide

After looking through this textbook, I thought that it would be well suited for those who like a more traditional presentation of the material than in Headfirst, and at the same time are looking for a tutorial from scratch. In some places, the presentation in the book is very detailed, reminiscent of expanded and translated documentation with good visual examples. Sometimes, as for me, the author crosses the line and begins to chew too much, reading becomes boring... and suddenly - somersault - and some rather complex place is missed almost instantly, and you are completely bewildered trying to understand what and where you missed. However, there are not too many such passages in the book, and I know people who believe that the Beginner's Guide is the best Java tutorial for those who do not know anything yet. Personally, I didn't find it very smooth. Let's say I start sorting through collections, and instead of a human explanation, they give me the task of independently creating a Set based on arrays. Cool problem, but I'd like to better understand what standard collections are first! Although this book, like the previous one, is considered a textbook for beginners, my experience as a teacher suggests that it is only good in conjunction with other materials: not everything will be simple and understandable for a humanities student. The “Beginner’s Guide” is best suited for someone who at least learned programming (for example, at university), gave up on it a long time ago, and at the same time likes the author’s presentation style. Advantages:
  • Traditional thoughtful presentation of the basics;
  • Good examples.
Flaws:
  • There are “jumps” from “too chewy” to “quickly said”;
  • A bit boring in places.
By the way, Herbert Schildt has another famous book on programming - “Java 8. The Complete Guide”. This is a completely different textbook, more fundamental. Let's move on to it. References and advanced guides The books in this section will be useful to those who have already gotten involved in the fullest and are looking for books for a better understanding of theory and practice.

Herbert Shildt "Java 8. The Complete Guide"

I decided to download this book from the Internet to evaluate it, and then decide whether to buy it or not. No joke, 1300 pages of text! Well, the price is no less impressive than the volume. I did exactly the same thing with the two-volume “Professional's Library” by Kay Horstmann (more about it below). Looking ahead, I will say that I chose the second one. Why? Because in the book “Java. The Complete Guide" I saw the same shortcomings as in the "Beginner's Guide". Sometimes it’s chewed, sometimes it’s crumpled, but at the same time it’s not just crumpled, but somehow verbosely crumpled. This is probably the author’s style and I think someone will like it, or rather, their way of thinking. Overall, Java 8: The Definitive Guide is a good reference book for Java. But personally, I liked the presentation of the same topics more in another book. Advantages:
  • Complete guide. It seems to have all the topics a beginner, and not just a beginner, needs to know.
  • Detailed explanations.
Flaws:
  • Lots of water (but some people might like that!);
  • The Russian translation is not the best.

Java. The Professional's Library, Kay S. Horstmann, Gary Cornell

Schildt's and Horstmann's books are often compared to each other. Both have loyal fans. For me, Horstmann's two-volume book is the best textbook on Java. It also became a reference book for me at beginner and intermediate levels of JavaRush. When I didn’t understand a topic, I mostly turned to Horstmann, and he clarified a lot of things. The book covers everything from syntax to multithreaded programming, application localization, and working with XML. And don’t let the name “Professional’s Library” scare you off (that’s what scared me off), the basics are covered pretty well. In addition, it is useful to re-read it periodically to refresh and organize your knowledge. They say that even professionals find something useful for themselves in it... I don’t know. If I become a professional, I’ll tell you! Advantages:
  • With an impressive number of pages, there is little water (unlike Schildt).
  • Contains everything beginners need.
  • Reveals Java 8.
  • Good presentation of topics on collections and generics.
  • Pairs very well with JavaRush. Get to the topic, solve problems, at some point you don’t understand something - watch Horstmann, try again.
Flaws:
  • Some may find the book a bit dry;
  • No practice;
  • Russian translation with mistakes.

"Java" Programming methods". Blinov, Romanchik

I once read on a forum that there was a book called “Industrial Programming”, and it had some good problems. It turned out that they didn’t lie. I found a copy of it in PDF on the Belarusian EPAM website. The publication there is not the newest (on Java 6), but the book is written as a solid university textbook, that is, in places the presentation is somewhat ponderous and academic. BUT! There is really a very good collection of Java programming problems, as well as test tasks. They say that EPAM trainees study from this book, and it has also been adopted by many offline Java courses.

The approach to tasks there is a little different from that of JavaRush, that is, on average, the tasks here are a little more complicated and each of them is something like... not a mini, but a micro-project. So I recommend JavaRush even to students, since I think the disadvantage of the practical side of the course is that all the tasks in it are already completely designed and there are too many tips. Let's say, the OOP problems from this collection helped me understand this very OOP very well, along with the books of the “timeless classics” that I write about below. The book was written as if for future “rowers”, therefore it describes Hibernate technologies for developing distributed systems, as well as the basics of HTML, XML, JavaScript. “Industrial Programming” is, if not the best Java tutorial, then a very good textbook. But you need to come to it already prepared. Let's say, after a dozen or two levels of JavaRush. Later I discovered its newer and revised edition, already under the name “Java. Programming methods."

Advantages:
  • Excellent selection of problems and test items;
  • There is an official free version (I believe that it is official, since it is not on some root tracker, but on the EPAM website);
  • Comparison with C++.
  • Opportunity to understand what goes into an EPAM internship.
Flaws:
  • Too fundamental presentation. But for repetition with practice it will be suitable.
  • No Java 8.
Timeless classic The books that I write about below can be called sacred texts for beginners and advanced “javistes.”

Effective Java, Joshua Bloch

It's just a treasure, not a book, and it's dedicated to the basic principles of the language from one of its authors, Joshua Bloch. Most likely, you have already used its libraries (in the Java Collection, for example). I’ll make a reservation right away: complete beginners, except for some prodigies-speedrunners, do not need the Effective Java book. First, it’s better to learn the syntax and get at least some programming practice, so to speak, “get the hang of it,” and then take on Joshua Bloch’s creation. The book will be useful for those who want to truly understand Java, form the right approach when programming in this language, and understand not only how to do it, but everything else that needs to be done exactly that way. And also for those who want to deeply understand OOP (in principle, these are interrelated things). This book is the best textbook on Java in the context of the object-oriented approach to programming. Advantages
  • A brilliant presentation of material on the topic of OOP.
  • Best programming practices are provided.
  • The author knows Java very well from the inside.
Flaws
  • There is currently no translation of the newest edition of the book (the third).

Java Philosophy, Bruce Eckel

The title of this book speaks for itself. This is another “alpha and omega” for everyone who wants to know Java! In this book you will find good and clear examples, and from them it will be clear how Java works. It's hard for me to say which of the two books - "The Philosophy of Java" or "Effective Programming" - is better. I would say that Eckel is somewhat more friendly to beginners, while Bloch requires some experience. I first read the chapter from “Java Philosophy” when I was just starting to learn JavaRush (I think it was listed as recommended at one of the early levels). Then she didn't suit me. But after level 10 or 12 - it was a song! And, I will say, a very useful song. I returned to it later, when I came to Effective Programming. I will say this: let Bloch and Eckel talk about the same thing, but in different ways, and give different examples. Advantages
  • An in-depth presentation of Java principles from a professional;
  • It will be good for those who are switching from other languages ​​- there are many comparisons with C++, for example.
  • It seems to me that you can start reading it at level 10, but Eckel - a little later.
Flaws
  • Very unsuccessful Russian translations;
  • Lack of a new edition of the book in Russian.

Brief conclusions

  1. The best Java tutorial from scratch for those who know nothing at all - Head First Java;
  2. The best Java reference-textbook and reference book is “Professional's Library”. And, of course, Oracle documentation.
  3. The best collection of Java programming tasks - JavaRush. Well, among the books - “Java. Programming methods".
  4. The best timeless classics are “The Philosophy of Java” and “Effective Java”. This is a must read for everyone who decided to understand everything for real, for a deep understanding. But it is better to read them gradually and in order.
  5. Additional conclusion: there is an opportunity - read in English. Russian translations are generally very weak.

Russian-language channels that will help you learn Java

1. Education online

I think everyone has come across lessons from this author at least once. It may seem that he explains too slowly, but in fact it is precisely this pace that allows you to well assimilate and consolidate the information received. Works with Eclipse, which is suitable for those who are not familiar with shortcuts, libraries and other advantages of this IDE (especially since knowledge of Eclipse is required everywhere). The playlists are divided into introduction, Java for professionals, sorting algorithms, JSP, Swing, patterns and more.

2. ZhirniToni

Also a popular channel that is focused on learning the basics. In addition to the programming itself, it also presents a schematic visualization of the process, right down to an analysis of the basics of OOP. Here is an overview of the main class, console output, and loops. In general, everything you need to learn Java from scratch. The videos are short, up to 20 minutes each. The explanations, although laconic, are succinct, so that after viewing there are no unnecessary questions left. Playlists include materials "for dummies", Java Production and methodology. If you are preparing for an interview, this is what you need.

3. loftblog

Hodgepodge. No, really: this channel contains a lot of things. You can find lessons on the basics of programming, HTML, CSS, Python, Git. Even video editing in Adobe Premiere. That is, the guys have enormous experience. But we'll talk about Java. Here we are shown working with everyone (well, certainly many) beloved IntelliJ IDEA. They even show you how to install the IDE, which is useful if you're a beginner or have simply never worked with IntelliJ. At the same time, the lessons vary in duration, which depends on the complexity of the topic. The presentation of the material is easy but thorough.

4. Evil Nerd

It’s very good that the lessons here are divided into levels: there is Java training for beginners, intermediate level, JavaFX and “Writing programs in Java.” But no, you will have to write programs not only there: explanations with visualized coding are everywhere. It’s just that the last section is more detailed, designed to prepare a program from scratch. An indispensable assistant channel for beginners, whose playlists you want to peek at, even if you already have some experience.

English-language Youtube channels

5. Derek Banas

The author is not limited to Java, although learning Java with this channel will not be difficult. A lot of supporting materials are collected here. For example, if after Java you want to “transition” to Android, there is no question, because the channel has corresponding video tutorials. Both algorithms and Java tutorials are presented. The videos are equipped with presentations that succinctly and as clearly as possible explain the operation of both the language itself and the program written on it. The author also uses Eclipse.

6. Durga Software Solutions

And only now we have entered the channel with lectures. Yes, sometimes you just need lecture material - with a board, a marker, so that everything is black and white. Many people actually learn information better this way. The lecturer understands the topic and it shows in his confident explanations. A very good presentation of the material and really a lot of lectures, after watching which you can not only learn Java, but also thoroughly prepare for the future. Each lesson will take about an hour of your time.

7. Java Brains

The Java Brains teacher is an excellent teacher and technical expert in what he teaches. He has been working as a software developer for a long time, so you know that you are guaranteed to get the right content in every sense. Sometimes the author shows one of the methods, and then explains how you can change the code to do the same thing, but better, cleaner. There are many playlists, including Java Enterprise Edition, as well as analysis of such popular frameworks as Spring and Hibernate.

8. Deege U

On this channel they will tell you what it is, how to create a repository on Github, demonstrate microservices, tutorials, etc. In general, nothing new, but this channel will be an excellent addition to the previous ones, since some really interesting topics are touched on that are not covered everywhere. For example, Java EE application server Wildfly. A good lifesaver, both for beginner Javaists and for more experienced developers.

Take our selection for a pencil. It will definitely be useful for beginners who want to learn Java, and for experienced programmers who want to remember the “material parts”. Good luck in opening new horizons!

In this article I will try to present the basics of programming in Delphi as simply and clearly as possible.

Java for dummies. Lesson 1. Hello World!

First, I'll tell you what Java can do. Firstly, in this language you can write applets - programs that are embedded in the website’s web page. For example, it could be a game, a business graphics system, and much more. Secondly, you can write full-fledged applications in Java that are not necessarily related to the Web. Or you can use servlets - programs that, unlike applets, are executed not on the client side, but on the server side.

Let's start with the very basics. Let's pay tribute to tradition and write a simple program that displays a greeting on the screen Hello World. If you don't have Java, then it can be downloaded from the official website http://www.java.com/ru. Then install it.

If Java you have installed, then type the following text in some editor:

Public class HelloWorld {

Public static void main ( String args ) {

System . out . print ( "Hello, world!" );

}

}

And be sure to save it under the name HelloWorld. java- The name of the executable class must match the file name. To compile, use the program javac.exe included in the standard package Java. This is what a compilation batch file might look like this java file:

"c:\Program Files\Java\jdk1.7.0\bin\javac" HellowWorld.java

pause

If no errors occurred during compilation:

then, most likely, the compilation was successful in yours in the same directory where HellowWorld was located. java HellowWorld has also appeared.class:

Now let's run another batch file that will call the Java interpreter along with our compiled file:

"c:\Program Files\Java\jdk1.7.0\bin\java" HellowWorld

pause

If everything is done correctly, you should get this result:

If you received it, then I can congratulate you - you have written your first program in Java. In the future we will learn how to write Java applets, and much more. And now a few words about the program itself. As you noticed, it starts with the word public. This is a modifier that means that we are declaring something publicly available: a class, a class method, or a variable. There are other modifiers, for example: private, protected, friendly, final, abstract, static. Some of them can be combined with each other. For example, private means that the variable we want to declare is private to other classes. But we'll get to the modifier later. Now let's look at the next keyword, class. It means that we are declaring a class. In java everything is based on classes. One of the classes is necessarily the base one. And the base class must be public. In this example, it is the HelloWord class. For now he is the only one we have.

Now I’ll try to explain in simple words what it is Class and what is object.

Let's remember the school zoology course. How is the living world classified? First, the concept of “kingdom” is introduced.

1. Kingdom of unicellular organisms,

2. plant kingdom

3. Animal kingdom.

Let's take animals. They can be divided by type. For example:

1. Type coelenterates.

2. Type of flatworms.

3. Type of shellfish.

4. Phylum chordata.

The latter are divided into mammals, reptiles, amphibians, birds, etc. You can go even further into the classification, but we won’t do that now, but will move directly to programming.

In the Java language, you can, similar to the classification of the living world, classify objects (pieces of program and data). It has classes for this.

Stop stop! - you say, - why classify these objects?

Imagine that you, like some demiurge (creator, god), are creating life on Earth. First you developed the simplest organic compounds. So, for the sake of experiment, what will happen. Then they combined them into complex molecules, from which, like bricks, they assembled the simplest microorganisms. But your ultimate goal is the creation of intelligent life. Therefore, you did not stop there, but created multicellular organisms. Then they began to improve them and develop them. Some species turned out to be viable, some became extinct (dinosaurs). And finally the goal was achieved - Homo Sapiens - Homo sapiens - appeared.

Now let’s come down to earth and imagine programming as a creation, where you force your program to evolve to a certain state when it can be used, and then further, gradually increasing and improving functionality.

Now let’s imagine that an atom is the simplest program command or a unit of information (which, you see, are inseparable from each other, because the program works with something – that’s right, with information).

Then the molecule is a subroutine. Or an object.

So we created a bunch of objects in our program. We need to classify them somehow so as not to get confused. This is what Java provides classes for. Using them, we describe a class of objects (a general concept, for example birds), and then, having the described class, we can create an object - an instance of this class. That is, the class is the word Birds itself, and the object is some specific bird, if we continue our analogy.

Further, birds come in different types. But they all have some common characteristics, inherited from the concept of “Birds”. Likewise in Java, from a class you can create another class that inherits its properties and methods (features). It's called inheritance.

Different birds have different feather colors, beak and wing shapes. Likewise for classes, when creating a new class, inherited characteristics can be changed. It's called polymorphism.

So, we figured out the basic concepts of Java. Now let's go through the program.

This is how we declare a class:

public class HelloWorld {

In this case, there is only one class in our program, and this is the base class, that is, the class responsible for launching the program. That is why its name must match the file name, so that the interpreter “knows” where to start executing the program.

The base class (HelloWorld) has a base method: main. We declared it as public and static. The first indicates that the method is public. If this were not so, then our program simply would not start. There are also methods that are not publicly available, but we will talk about them in the next lessons. For now, just remember that the base method (which is launched when we start the program) must be public. And its name should be main so that the interpreter knows where to start executing the program.

Now what is static. This is a modifier that indicates that the method is static. That is, it works even when an instance of the class (object) is not created. In general, fields and methods with the static modifier are common to all objects of the class. We'll also talk about this later.

Each method may or may not have a return value. If it does, then it's a function. The return value type is also included in the method declaration. If not, then set it to void (as in our example).

Access to the fields and methods of an object occurs through a dot. There are also built-in objects, for example, System, which we use in our example:

System . out . print ( "Hello, world!" );

in this case, we access the out field, which is also an object intended for outputting data, and call its print method, which displays text on the screen (like the PRINT command in good old BASIC).

(C) Shuravin Alexander

A Java source file is a text file containing one or more class definitions. The Java translator assumes

that the source code of programs is stored in files with Java extensions. The code obtained during the translation process for each class is written in a separate output file, with a name that matches the class name and a class extension.

First of all, in this chapter we will write, broadcast, and run the canonical “Hello World” program. After that, we'll look at all the essential lexical elements accepted by the Java translator: whitespace, comments, keywords, identifiers, literals, operators, and delimiters. By the end of the chapter, you will have enough information to navigate a good Java program on your own.

So here is your first Java program

:

class HelloWorld(

System. out. println("Hello World");

In order to work with the examples given in the book, you need to obtain and install the Java Developers Kit over the network from Sun Microsystems - a package for developing Java applications (

http://java.sun.com/products/jdk ). Full description of the package utilities JDK - in Appendix 1 .

The Java language requires that all program code be contained within named classes. The above example text should be written to the HelloWorld.java file. Be sure to check that the capital letters in the file name match those in the name of the class it contains. In order to translate this example, you need to run the Java translator - javac, specifying the name of the file with the source text as a parameter:

\> javac HelloWorld.Java

The translator will create a file HelloWorld.class with the processor-independent bytecode of our example. In order to execute the resulting code, you must have a Java runtime environment (in our case, this is the java program), into which you need to load a new class for execution. We emphasize that the name of the class is specified, and not the name of the file in which this class is contained.

>java HelloWorld

Not much useful work has been done, but we have verified that the installed Java translator and runtime environment work.

Step by step

HelloWorld is a trivial example. However, even such a simple program for a beginner in the languageJava can seem intimidatingly complex because it introduces you to a lot of new concepts and details of the language's syntax. Let's take a closer look at each line of our first example, analyzing the elements that make up a Java program.

class HelloWorld(

This line uses a reserved word

class. It tells the translator that we are going to define a new class.The full class definition appears between the opening curly brace on line 1 and the matching closing curly brace on line 5. The curly braces inJava is used in exactly the same way as in C and C languages++.

public static void main (String args) (

This seemingly overly complex example string is a consequence of an important requirement when the Java language was designed. The point is that in

Java lacks global functions. Since similar lines will appear in most of the examples in the first part of the book, let's take a closer look at each element of the second line.

By breaking this string into separate tokens, we immediately encounter the keyword

public This - access modifier, which allows the programmer to control the visibility of any method and any variable. In this case, the access modifierpublic means the methodmain is visible and accessible to any class. There are 2 more access level indicators - private and protected, which we will get to know in more detail inchapter 8 .

The next keyword is

static. This word is used to declare class methods and variables used to work with the class as a whole. Methods that use the static keyword in their declaration can only work directly with local and static variables.

You will often need methods that return a value of one type or another: for example,

int for integer values, float - for real ones, or the class name for programmer-defined data types. In our case, we just need to display a string and return the value from the methodmain is not required. That is why the modifier was usedvoid. This issue is discussed in more detail inchapter 4 .

Finally we get to the method name

main. There is nothing unusual here, it’s just that all existing implementations of Java interpreters, having received the command to interpret a class, begin their work by calling the method main. A Java translator can translate a class that does not have a main method. But the Java interpreter runs classes without a method main can't.

All parameters that need to be passed to the method are specified inside a pair of parentheses as a list of elements separated by ";" characters. (semicolon). Each element of the parameter list consists of a type and identifier separated by a space. Even if a method has no parameters, you still need to put a pair of parentheses after its name. In the example we are now discussing, the method

main has only one parameter, albeit of a rather complex type. String args declares a parameter namedargs, which is an array of objects - representatives of the classString. Note the square brackets after the args identifier. They indicate that we are dealing with an array, and not with a single element of the specified type. We'll return to a discussion of arrays in the next chapter, but for now let's note that the type String - this is class. We'll talk about strings in more detail inChapter 9 .

System. out. prlntln("Hello World!");

This line executes the method

println of the out object. Object out is declared in the classOutputStream and is statically initialized in the System class. IN chapters 9 And 13 you will have a chance to get acquainted with the nuances of how classes work String and OutputStream.

The closing curly brace on line 4 ends the method declaration

main, and the same parenthesis on line 5 ends the HelloWorld class declaration.

Lexical Basics

Now that we've looked at the minimal Java class in detail, let's go back and look at the general syntax of the language. Programs for

Java - it is a collection of spaces, comments, keywords, identifiers, literal constants, operators and delimiters.a language that allows arbitrary formatting of program text. In order for the program to work properly, there is no need to align its text in a special way. For example, classHelloWorld could be written in two lines or any other way you like. And it will work exactly the same, provided that there is at least one space, tab character, or newline character between the individual tokens (between which there are no operators or separators).

Comments

Although comments have no effect on the executable code of the program,

when used correctly, they turn out to be a very significant part of the source text. There are three types of comments: single-line comments, multi-line comments, and finally documentation comments. Single-line comments begin with // characters and end at the end of the line. This commenting style is useful for providing short explanations of individual lines of code:

a = 42; // If

42 - the answer, then what was the question?

For more detailed explanations, you can use comments placed on several lines, starting the comment text with the characters /* and ending with the characters */. In this case, all text between these pairs of characters will be regarded as a comment and the translator will ignore it.

* This code is a bit complicated...

*I'll try to explain:

The third, special form of comments is intended for the service program

javadocwhich uses Java translator components to automatically generate documentation for class interfaces. The convention used for this type of comment is to place a documenting comment before the declaration of a public class, method, or variable., you need to start it with the characters /** (slash and two asterisks). Such a comment ends in the same way as a regular comment - with the symbols */. The javadoc program can recognize in documenting comments some special variables whose names begin with the @ symbol. Here is an example of such a comment:

* This class can do amazing things. We recommend it to anyone who

* wants to write an even more advanced class, take it as

* basic.

* @see Java. applet. Applet

* ©author Patrick Naughton

class CoolApplet extends Applet ( /**

* This method has two parameters:

key is the name of the parameter.is the value of the parameter namedkey.

*/ void put (String key, Object value) (

Reserved Keywords

Reserved keywords are special identifiers that the language

Java is used to identify built-in types, modifiers, and program execution controls. Today in the language J ava has 59 reserved words (see Table 2). These keywords, along with the syntax of operators and delimiters, are included in the language descriptionJava. They can only be used for their intended purpose and cannot be used as identifiers for variable, class or method names.

Table 2

Java Reserved Words

Note that the words

byvalue, cast, const, future, generic, goto, inner, operator, outer, rest, varreserved in Java, but not yet used. In addition, in Java there are reserved method names (these methods are inherited by every class and cannot be used except in cases of explicit overriding of class methods Object).

Table 3

Reserved method names

Java

Identifiers

Identifiers are used to name classes, methods, and variables. The identifier can be any sequence of lowercase and uppercase letters, numbers, and the symbols _ (underscore) and $ (dollar). Identifiers should not begin with a number, so that the translator does not confuse them with numeric literal constants, which will be described below.

Java - case-sensitive language. This means that, for example, Value and VALUE - various identifiers.

Literals

Constants in

Java are given by their literal representation. Integers, floats, booleans, characters, and strings can be placed anywhere in the source code. The types will be discussed inchapter 4 .

Integer literals

Integers are the type most commonly used in regular programs. Any integer value, such as 1, 2, 3, 42, is an integer literal. This example shows decimal numbers, that is, numbers with a base of 10 - exactly the ones we use every day outside the world of computers. In addition to decimal, numbers with base 8 and 16 - octal and hexadecimal - can also be used as integer literals. Java recognizes octal numbers by leading them with a leading zero. Normal decimal numbers cannot start with a zero, so using the externally valid number 09 in a program will result in a translation error message because 9 is not in the range of 0..

7, valid for octal digits. A hexadecimal constant is distinguished by the leading zero-x characters (0x or 0X). The range of hexadecimal digit values ​​is 0..15, and as numbers for the values ​​10..15 letters from A to are used F (or from a to f). With hexadecimal numbers you can express computer-friendly values ​​in a concise and clear way, for example by writing Oxffff instead of 65535.

Integer literals are values ​​of type

int, which is in Java is stored in a 32-bit word. If you require a value that is greater than approximately 2 billion, you must use a constant likelong. In this case, the number will be stored in a 64-bit word. For numbers with any of the bases mentioned above, you can assign a lowercase or uppercase letter to the rightL, thus indicating that the given number is of the typelong. For example, Ox7ffffffffffffffL or9223372036854775807L is the largest value for a number of type long.

Floating point literals

Floating point numbers represent decimal values ​​that have a fractional part. They can be written in either regular or exponential formats. In the usual format, a number consists of a number of decimal digits, followed by a decimal point, and the following decimal digits of the fractional part. For example, 2.0, 3.14159, and .6667 are valid values ​​for floating-point numbers written in standard format. In exponential format, after the listed elements, the decimal order is additionally indicated. The order is determined by the positive or negative decimal number following the symbol E or e. Examples of numbers in exponential format: 6.022e23, 314159E-05, 2e+100. IN

Java floats are treated as doubles by default. If you require a type constantfloat, the symbol F or f must be added to the right of the literal. If you are a fan of redundant definitions, you can add to literals like double character D or d. Default Type Valuesdouble are stored in a 64-bit word, less precise type values float - in 32-bit.

Boolean literals

A boolean variable can only have two values ​​-

true and false (false). Boolean values true and false are not converted to any numeric representation. Keyword true in Java is not equal to 1, and false is not equal to 0. In In Java, these values ​​can only be assigned to boolean variables or used in expressions with logical operators.

Character literals

Symbols in

Java - these are the indexes in the symbol tableUNICODE. They are 16-bit values ​​that can be converted to integers and to which integer arithmetic operators, such as addition and subtraction, can be applied. Character literals are placed inside a pair of apostrophes (" "). All visible table symbolsASCII can be directly inserted inside a pair of apostrophes: -"a", "z", "@". For characters that cannot be entered directly, several escape sequences are provided.

Table 3.

2. Escape sequences

Control sequence

Description

Octal character

(ddd)

Hexadecimal character

UNICODE (xxxx)

Apostrophe

Backslash

Carriage return

Line feed (line feed, new line)

Page translation

(form feed)

Horizontal tabulation

(tab)

Go back one step

(backspace)

String literals

String literals in

Java looks exactly the same as many other languages ​​- it is arbitrary text enclosed in a pair of double quotes (""). Although lowercase literals inJava are implemented in a very unique way(Java creates an object for each line), this does not appear externally. Examples of string literals:“Hello World!”; "two\strings; \And this is in quotes\"". All escape sequences and octal/hexadecimal notations that are defined for character literals work exactly the same in strings. String literals inJava codes must start and end on the same line of source code. In this language, unlike many others, there is no escape sequence for continuing a string literal on a new line.

Operators

An operator is something that performs some action on one or two arguments and produces a result. Syntactically, operators are most often placed between identifiers and literals. The operators will be discussed in detail in

Chapter 5 , their list is given in Table 3. 3.

Table 3.

3. Language operators Java

Separators

Only a few groups of characters that can appear in a syntactically correct Java program still remain unnamed. These are simple delimiters that affect the appearance and functionality of program code.

Name

What are they used for?

parentheses

They highlight lists of parameters in a method declaration and call; they are also used to set the priority of operations in expressions, highlight expressions in program execution control statements, and in type casting operators.

braces

square brackets

Used in array declarations and when accessing individual array elements.

semicolon

Separates operators.

Separates identifiers in variable declarations, also used to link statements in a loop header

for.

Separates package names from subpackage and class names, and is also used to separate a variable or method name from a variable name.

Variables

A variable is the main element of storing information in a Java program. A variable is characterized by a combination of identifier, type, and scope. Depending on where you declare the variable, it may be local, such as to the code inside a for loop, or it may be an instance variable of the class that is available to all methods in that class. Local scopes are declared using curly braces.

Variable Declaration

The basic form of a variable declaration is:

type identifier [ = value] [, identifier [ = value

7...];

A type is either one of the built-in types, that is,

byte, short, int, long, char, float, double,boolean, or the name of a class or interface. We will discuss all these types in detail innext chapter . Below are some examples of declaring variables of various types. Note that some examples involve initializing an initial value. Variables for which no initial values ​​are specified are automatically initialized to zero.

The example below creates three variables corresponding to the sides of a right triangle and then

c Using the Pythagorean theorem, the length of the hypotenuse is calculated, in this case the number 5, the size of the hypotenuse of a classic right triangle with sides 3-4-5.

class Variables(

public static void main (String args) (

= Math.sqrt(a* a + b* b);

System.out.println("c = "+ c);

Your first step

We have already achieved a lot: first we wrote a small program in the language

Java and looked in detail at what it consists of (code blocks, comments). We've been introduced to a list of keywords and operators whose purpose will be explained in detail in later chapters. Now you are able to independently distinguish the main parts of any Java program and are ready to start readingchapter 4 , which covers simple data types in detail.