Java Programming Language Handbook: The Ultimate Source for Conquering the Java Programming Language · Read more. Java Programming 2: The Java Programming Language . The obvious reason that object-oriented programming languages use objects is due to the power. This book will take you to journey of Java programming language starting from very first version to the current Java 8 version. Benjamins Evans, author of the.
|Language:||English, Spanish, Japanese|
|Genre:||Science & Research|
|ePub File Size:||24.80 MB|
|PDF File Size:||8.37 MB|
|Distribution:||Free* [*Regsitration Required]|
answering interview problems by writing code on paper first, and then typing answering questions Cracking the Coding. Direct from the creators of the Java™ programming language, the Java™ Programming Language is an indispensable resource for novice. This book teaches you all about the Java language and how to use it to create applets and what programming is, but you've heard Java is easy to learn, really .
By default, you see three panes in the Javadoc. At times, you might end up using the same name to express two slightly different concepts. You can create an integer array of elements in two ways. Listing 1 contains various types of constructs, including package in line 1, import in line 2, and class in line 3. You want to iterate over the collection, which you can do because List implements the java. The answer should be obvious, yet for some reason, programmers have a tendency to give methods and variables, for that matter small, abbreviated names. The variableName variableName is up to you, but by convention, variable names use the camel case convention, except that they begin with a lowercase letter.
A getter is a method for retrieving the value of an attribute; a setter is a method for modifying that value. The naming of accessors follows a strict convention known as the JavaBeans pattern.
In this pattern, any attribute Foo has a getter called getFoo and a setter called setFoo. The JavaBeans pattern is so common that support for it is built into the Eclipse IDE, as you saw when you generated getters and setters for Person. By far the easiest way to declare accessors is to let Eclipse do it for you. But you also need to know how to hand-code a getter-and-setter pair.
Suppose I have an attribute, Foo , whose type is java. My complete declaration for Foo following the accessor guidelines is:. Notice that the parameter value passed to the setter is named differently than if it had been Eclipse-generated where the parameter name would be the same as the attribute name — for example, public void setFoo String foo public void setFoo String foo.
On the rare occasions when I hand-code a setter, I always use value as the name of the parameter value to the setter.
This eye-catcher — my own convention, and one that I recommend to other developers — reminds me that I hand-coded the setter.
Code comments can serve the same purpose. Invoking — or calling — methods is easy. The testPerson method in Listing 6 , for example, invokes the various getters of Person to return their values. To invoke a method on an object, you need a reference to that object. Method-invocation syntax comprises:. Remember that constructors are methods, too. And you can separate the parameters with spaces and newlines. These next two method invocations are equivalent:.
Notice how the comments in the second constructor invocation make it more readable for the next person who might work with this code. At a glance, that developer can tell what each parameter is for.
Here you pass the return value of Person. Remember that the getLogger method call is a static method call, so its syntax differs slightly. The tutorial has so far introduced several variables of type String , but without much explanation. You learn more about strings in this section, and also find out when and how to use operators.
In C, string handling is labor intensive because strings are null-terminated arrays of 8-bit characters that you must manipulate. The closest Java code gets to the C world with regard to strings is the char primitive data type, which can hold a single Unicode character, such as a. In the Java language, strings are first-class objects of type String , with methods that help you manipulate them.
Here are a couple of ways to create a String, using the example of creating a String instance named greeting with a value of hello:. Because String s are first-class objects, you can use new to instantiate them. Setting a variable of type String to a string literal has the same result, because the Java language creates a String object to hold the literal, and then assigns that object to the instance variable.
You can do many things with String , and the class has many helpful methods. Now, you can try concatenating two more String s inside of the Person class. At this point, you have a name instance variable, but it would be more realistic in a business application to have a firstName and lastName. Return to your Eclipse project, and start by adding the new instance variables at the same location in the source code where name is currently defined:.
Then, remove the setName and getName methods, and add a new getFullName method to look like this:. This code illustrates chaining of method calls. You then operate on the returned, changed value. As you might expect, the Java language can do arithmetic, and it uses operators for that purpose too. Now, I give you a brief look at some of the Java language operators you need as your skills improve. The Java language syntax also includes several operators that are used specifically for conditional programming — that is, programs that respond differently based on different input.
You look at those in the next section. In this section, you learn about the various statements and operators you can use to tell your Java programs how you want them to act based on different input.
The Java language gives you operators and control statements that you can use to make decisions in your code. Most often, a decision in code starts with a Boolean expression — that is, one that evaluates to either true or false. Such expressions use relational operators , which compare one operand to another, and conditional operators. This somewhat contrived example illustrates the use of the if statement, which evaluates a Boolean expression inside parentheses.
If that expression evaluates to true , the program executes the next statement. In this case, you only need to execute one statement if the Locale of the computer the code is running on is Locale. If you need to execute more than one statement, you can use curly braces to form a compound statement.
A compound statement groups many statements into one — and compound statements can also contain other compound statements. Every variable in a Java application has scope , or localized namespace, where you can access it by name within the code. Outside that space the variable is out of scope , and you get a compile error if you try to access it. Scope levels in the Java language are defined by where a variable is declared, as shown in Listing 7.
Listing 7. Within SomeClass , someClassVariable is accessible by all instance that is, nonstatic methods. Scope has many rules, but Listing 7 shows the most common ones.
Take a few minutes to familiarize yourself with them. The else statement works the same way as if , in that the program executes only the next statement that it encounters. In this case, two statements are grouped into a compound statement notice the curly braces , which the program then executes. You can also use else to perform an additional if check:. If conditional conditional does not evaluate to true , then conditional2 conditional2 is evaluated. If conditional2 conditional2 is true, then Block 2 Block 2 is executed, and the program jumps to the next statement after the final curly brace.
If conditional2 conditional2 is not true, then the program moves on to conditional3 conditional3 , and so on. Only if all three conditionals fail is Block 4 Block 4 executed. Compound statements are not allowed for either statement. Ternary operators are most often used to initialize a variable such as a return value , like so:. In this section, learn about constructs used to iterate over code or execute it more than once.
A loop is a programming construct that executes repeatedly while a specific condition or set of conditions is met. For instance, you might ask a program to read all records until the end of a data file, or to process each element of an array in turn. The basic loop construct in the Java language is the for statement.
You can use a for statement to iterate over a range of values to determine how many times to execute a loop. The abstract syntax for a for loop is:. At the beginning of the loop, the initialization statement is executed multiple initialization statements can be separated by commas.
Provided that loopWhileTrue loopWhileTrue a Java conditional expression that must evaluate to either true or false is true, the loop executes. For example, if you wanted the code in the main method in Listing 8 to execute three times, you can use a for loop. Listing 8. The local variable aa is initialized to zero at the beginning of Listing 8. This statement executes only once, when the loop is initialized. The loop then continues three times, and each time aa is incremented by one.
For now, just note the use of the for loop syntax in Listing 8. As you might suspect, if condition evaluates to true , the loop executes. At the top of each iteration that is, before any statements execute , the condition is evaluated.
If the condition evaluates to true , the loop executes. Look again at the for loop in Listing 8. For comparison, Listing 9 uses a while loop to obtain the same result.
Listing 9. As you can see, a while loop requires a bit more housekeeping than a for loop. You must initialize the aa variable and also remember to increment it at the bottom of the loop. If you want a loop that always executes once and then checks its conditional expression, you can use a do Listing At times, you need to bail out of — or terminate — a loop before the conditional expression evaluates to false.
For the times when you want to bail, the Java language provides the break statement, shown in Listing In the simplistic example in Listing 11 , you want to execute the loop only once and then bail. You can also skip a single iteration of a loop but continue executing the loop. For that purpose, you need the continue statement, shown in Listing In Listing 12, you skip the second iteration of a loop but continue to the third.
You can skip that record and move on to the next one. Most real-world applications deal with collections of things like files, variables, records from files, or database result sets. The Java language has a sophisticated Collections Framework that you can use to create and manage collections of objects of various types.
This section introduces you to the most commonly used collection classes and gets you started with using them. Most programming languages include the concept of an array to hold a collection of things, and the Java language is no exception. An array is basically a collection of elements of the same type. You can create an integer array of elements in two ways.
This statement creates an array that has space for five elements but is empty:. This statement creates the array and initializes it all at once:. The initial values go between the curly braces and are separated by commas. The preceding code declares an integer array of five elements. If you try to put more than five elements in the array, the Java runtime will throw an exception.
To load the array, you loop through the integers from 1 through the length of the array which you get by calling. In this case, you stop when you hit 5. Think of an array as a series of buckets, and into each bucket goes an element of a certain type. Access to each bucket is gained via an element index:. To access an element, you need the reference to the array its name and the index that contains the element that you want. Every array has a length attribute, which has public visibility, that you can use to find out how many elements can fit in the array.
To access this attribute, use the array reference, a dot. Arrays in the Java language are zero-based. That is, for any array, the first element in the array is always at arrayName  arrayName , and the last is at arrayName [ arrayName. Creating an array of java. Each JDK class provides methods to parse and convert from its internal representation to a corresponding primitive type. For example, this code converts the decimal value to an Integer:. Similarly, to convert the Integer representation back to its int counterpart, you unbox it:.
I recommend that you avoid autoboxing and auto-unboxing, however, because it can lead to code-readability issues. The JDK wrapper classes have methods for that, too:. You can also convert the contents of a JDK wrapper type to a String:.
Pretty handy. A List is an ordered collection, also known as a sequence. Because a List is ordered, you have complete control over where in the List items go. A Java List collection can only hold objects not primitive types like int , and it defines a strict contract about how it behaves. You can make the declaration in two ways. The first uses the explicit syntax:. This is the case because the type of the class on the right side of the expression must match that of the left side.
Note that I assigned the ArrayList object to a variable of type List. With Java programming, you can assign a variable of one type to another, provided the variable being assigned to is a superclass or interface implemented by the variable being assigned from.
If you want to tighten up the constraints on what can or cannot go into the List , you can define the formal type differently:. Now your List can only hold Person instances. Using List s — like using Java collections in general — is super easy. Here are some of the things you can do with List s:. To put something in a List , call the add method:. The add method adds the element to the end of the List.
To ask the List how big it is, call size:. To retrieve an item from the List , call get and pass it the index of the item you want:. How do you do that in a generic fashion? You want to iterate over the collection, which you can do because List implements the java.
Iterable interface. If a collection implements java. You can start at one end and walk through the collection item-by-item until you run out of items.
Here it is again in more detail:.
That little code snippet does the same thing as this longer one:. The first snippet uses shorthand syntax: Because List extends java. Collection , which implements Iterable , you can use the shorthand syntax to iterate over any List.
A Set is a collections construct that by definition contains unique elements — that is, no duplicates. Whereas a List can contain the same object maybe hundreds of times, a Set can contain a particular instance only once.
A Java Set collection can only hold objects, and it defines a strict contract about how it behaves. One of my favorite implementations is HashSet , which is easy to use and similar to List. Here are some things you do with a Set:. Consider the following code:. You might expect that the Set would have three elements in it, but it only has two because the Integer object that contains the value 10 is added only once. Keep this behavior in mind when iterating over a Set , like so:.
Chances are that the objects print out in a different order from the order you added them in, because a Set guarantees uniqueness, not order. You can see this result if you paste the preceding code into the main method of your Person class and run it. A Map is a handy collection construct that you can use to associate one object the key with another the value.
A Java Map collection can only hold objects, and it defines a strict contract about how it behaves. One of my favorite implementations is HashMap. To put something into a Map , you need to have an object that represents its key and an object that represents its value:.
In this example, Map contains Integer s, keyed by a String , which happens to be their String representation.
To retrieve a particular Integer value, you need its String representation:. On occasion, you might find yourself with a reference to a Map , and you want to walk over its entire set of contents.
In this case, you need a Set of the keys to the Map:. Note that the toString method of the Integer retrieved from the Map is automatically called when used in the Logger call. Map returns a Set of its keys because the Map is keyed, and each key is unique.
This section shows you how.
You use this tool to create JAR files. After you package your code into a JAR file, other developers can drop the JAR file into their projects and configure their projects to use your code.
Creating a JAR file in Eclipse is easy. In your workspace, right-click the com. You see the dialog box shown in Figure When the next dialog box opens, browse to the location where you want to store your JAR file and name the file whatever you like. Click Finish. You see your JAR file in the location you selected. You can use the classes in it from your code if you put the JAR in your build path in Eclipse.
Doing that is easy, too, as you see next. As you grow more comfortable with writing Java applications, you might want to use more and more third-party applications to support your code. The Java open source community provides many libraries to help shore up these gaps. The classes provided by Commons Lang help you manipulate arrays, create random numbers, and perform string manipulation.
To use the classes, your first step is to create a lib directory in your project and drop the JAR file into it:. The new folder shows up at the same level as src. For this example, the file is called commons-lang Now all you need to do is tell Eclipse to include the classes in the commons-lang Notice in Project Explorer that you have a new folder called Referenced Libraries that contains the commons-lang This final section lays out a few best practices that can help you write cleaner, more maintainable Java code.
At that size, Person is a small class. Some classes might be that large out of necessity, but most likely they need to be refactored. Refactoring is changing the design of existing code without changing its results. I recommend that you follow this best practice. Keep your classes tightly focused to do a small number of things and do them well.
Keep only the methods that you need. But be sure to limit the list of methods to what you need, and no more. A good coding pattern when it comes to method names is the intention-revealing method-names pattern. This pattern is easiest to understand with a simple example. Which of the following method names is easier to decipher at a glance?
The answer should be obvious, yet for some reason, programmers have a tendency to give methods and variables, for that matter small, abbreviated names. Small methods are as preferable as small classes, for similar reasons. One idiom I try to follow is to keep the size of a method to one page as I look at it on my screen.
This practice makes my application classes more maintainable. This book is even fun to read. If a method grows beyond one page, I refactor it. Eclipse has a wonderful set of refactoring tools. Usually, a long method contains subgroups of functionality bunched together. Take this functionality and move it to another method naming it accordingly and pass in parameters as needed.
Limit each method to a single job. Refactoring and the ability to write test-first code are the most important skills for new programmers to learn. If everybody were good at both, it would revolutionize the industry.
If you become good at both, you will ultimately produce cleaner code and more-functional applications than many of your peers. Please, use comments. The people who follow along behind you or even you, yourself, six months down the road will thank you.
You might have heard the old adage Well-written code is self-documenting, so who needs comments? Coding style is a matter of personal preference, but I advise you to use standard Java syntax for braces:. Eclipse does allow you to define code styles and format your code any way you like.
So I suggest you adopt the Java standard from the start. Before Java 1. I never use System. Another alternative is the commonly used log4j replacement library, part of the Apache umbrella project. In this tutorial, you learned about object-oriented programming, discovered Java syntax that you can use to create useful objects, and familiarized yourself with an IDE that helps you control your development environment. You know how to create and run Java objects that can do a good number of things, including doing different things based on different input.
In the second half of this tutorial , you begin learning about some of the more advanced constructs of Java programming, although the overall discussion is still introductory in scope. Java programming topics covered in that tutorial include:. Constructs for real-world applications.
May 15, Java Reactive Systems. May 14, May 1, New York. Back to top.
Linux Microservices Mobile Node. Skip to content. About this tutorial The two-part Introduction to Java programming tutorial is meant for software developers who are new to Java technology. Prerequisites This tutorial is for software developers who are not yet experienced with Java code or the Java platform. System requirements To complete the exercises in this tutorial, you will install and set up a development environment consisting of: The recommended system configuration is: At least MB of disk space to install the software components and examples.
Java platform overview Java technology is used to develop applications for a wide range of environments, from consumer devices to heterogeneous enterprise systems. Table 1. Using main as a test harness main is a special method that you can include in any class so that the JRE can execute its code. Table 2.
Table 3. Table 4. Boolean byte java. Byte char java. This book deals with the development of web applications where the focus is on the server side and how to develop dynamic web pages. The book is about developing of applications for Android, and especially for mobile phone applications. The subject is database applications, and how to write programs in Java that uses a database.
The subjects of this book are about files and how you in Java can manipulate files. This book leads you through a journey of developing your first web service application to more complex multitier enterprise application. This book is the eighth in a series of books on software development.
This book has primarily focus on Java and numerous of details regarding Java as an object-oriented programming language.
The book is a continuation of the subjects in the book about Java 11, but focusing on the development of enterprise applications. The book deals with Swing and how to use Swing to develop applications with a graphical user interface. This book deals together with the book Java 11 with development of web applications, but with focus on the client side. This book is the seventh in a series of books on software development. Standard introduction to data structures and algorithms using the Java programming language covering stacks, queues, lists, trees, sets, maps, graphs, hashing, searching, and sorting.
This book is the tenth in a series of books on software development. The book focuses on algorithms written in Java and presents several classic algorithms.