When calling the getLogger method, you pass it a String. For now, just get in the habit of passing the name of the class that the code you're writing is located in. From any regular that is, nonstatic method, the preceding code always references the name of the class and passes that to the Logger. If you are making a Logger call inside of a static method, reference the name of the class you're inside of:. In this example, the code you're inside of is the Person class, so you reference a special literal called class that retrieves the Class object more on this later and gets its Name attribute.
This tutorial's " Writing good Java code " section includes a tip on how not to do logging. Eclipse has a handy code generator to generate getters and setters among other things. When the dialog box opens, click Select All , as shown in Figure 6. For the insertion point, choose Last member and click OK. Now, add a constructor to Person by typing the code from Listing 5 into your source window just below the top part of the class definition the line immediately beneath public class Person.
A class is not required to have a main method — in fact, most never will — and a class can have at most one main method. In enterprise development, you would use test libraries such as JUnit, but using main as your test harness can be a quick-and-dirty way to create a test harness.
Now you generate a JUnit test case where you instantiate a Person , using the constructor in Listing 5, and then print the state of the object to the console. In this sense, the "test" makes sure that the order of the attributes on the constructor call are correct that is, that they are set to the correct attributes.
Accept the defaults by clicking Next. You see the Test Methods dialog box, shown in Figure 8. In this dialog box, you select the method or methods that you want the wizard to build tests for. In this case, select just the constructor, as shown in Figure 8. Click Finish , and Eclipse generates the JUnit test case.
Next, open PersonTest , go into the testPerson method, and make it look like Listing 6. Don't worry about the Logger class for now. Just enter the code as you see it in Listing 6. You're now ready to run your first Java program and JUnit test case. In Eclipse, right-click PersonTest. Figure 9 shows what happens. The Console view opens automatically to show Logger output, and the JUnit view indicates that the test ran without errors.
Person is looking good so far, but it can use some additional behavior to make it more interesting. Creating behavior means adding methods. This section looks more closely at accessor methods — namely, the getters and setters you've already seen in action. The getters and setters that you saw in action at the end of the preceding section are called accessor methods.
A getter is a method for retrieving the value of an attribute; a setter is a method for modifying that value. To encapsulate a class's data from other objects, you declare its variables to be private and then provide accessor methods. 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. 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. If I don't use Eclipse to generate getters and setters for me, I have a good reason. Using value as the setter's parameter value reminds me that this setter is special. 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. Now you'll learn the formal mechanics of making method calls. To invoke a method on an object, you need a reference to that object. And here's an example setting the Name attribute of Person:. Remember that constructors are methods, too.
And you can separate the parameters with spaces and newlines. The Java compiler doesn't care. 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. You don't need a Logger reference to make the invocation; instead, you use the name of the class as the left side of the invocation. 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. Without even using a method, you've already done something interesting within the Person class's testPerson method by concatenating, or combining, two String s:. You incur a performance penalty for doing this type of concatenation inside a loop, but for now, you don't need to worry about that. 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.
- Blackjack: Dreaming of a Morgan Horse (The Morgan Horse series Book 1).
- Introduction to Java programming, Part 1: Java language basics;
- HENRY FORDS REASONS FOR INTRODUCING A FIVE-DAY WORKWEEK IN 1926 - with comments from his grandson an.
You can then concatenate them when another object requests Person 's full name. 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:. Comment out the name definition; you don't need it anymore, because you're replacing it with firstName and lastName.
Now, tell the Eclipse code generator to generate getters and setters for firstName and lastName refer back to the " Your first Java class " section if necessary. Then, remove the setName and getName methods, and add a new getFullName method to look like this:. This code illustrates chaining of method calls. Chaining is a technique commonly used with immutable objects like String , where a modification to an immutable object always returns the modification but doesn't change the original. 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. In addition to the operators in Table 2, you've seen several other symbols that are called operators in the Java language, including:. 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. Now that you have a bunch of operators, it's time to use them. This code shows what happens when you add some logic to the Person object's getHeight accessor:. If the current locale is in the United States where the metric system isn't in use , it might make sense to convert the internal value of height in centimeters to inches. 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.
Within SomeClass , someClassVariable is accessible by all instance that is, nonstatic methods. Within someMethod , someParameter is visible, but outside of that method it isn't, and the same is true for someLocalVariable. Within the if block, someOtherLocalVariable is declared, and outside of that if block it's out of scope.
Scope has many rules, but Listing 7 shows the most common ones. Take a few minutes to familiarize yourself with them. Sometimes in a program's control flow, you want to take action only if a particular expression fails to evaluate to true. That's when else comes in handy:. 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 does not evaluate to true , then conditional2 is evaluated.
If conditional2 is true, then Block 2 is executed, and the program jumps to the next statement after the final curly brace. If conditional2 is not true, then the program moves on to conditional3 , and so on. Only if all three conditionals fail is Block 4 executed. This operator's syntax is:. If conditional evaluates to true , statementIfTrue is executed; otherwise, statementIfFalse is executed.
Compound statements are not allowed for either statement. The ternary operator comes in handy when you know that you need to execute one statement as the result of the conditional evaluating to true , and another if it doesn't. Ternary operators are most often used to initialize a variable such as a return value , like so:.
The parentheses following the question mark aren't strictly required, but they do make the code more readable. 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. You'll learn about arrays in the next section. Three loop constructs make it possible to iterate over code or execute it more than once:.
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 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.
Java platform overview
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. You'll see in the next section that an alternative for loop syntax is available for looping over constructs that implement the Iterable interface such as arrays and other Java utility classes.
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.
So it's possible that a while loop will never execute if its conditional expression is not true at least once. Look again at the for loop in Listing 8. For comparison, Listing 9 uses a while loop to obtain the same result. 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 At times, you need to bail out of — or terminate — a loop before the conditional expression evaluates to false.
This situation can occur if you're searching an array of String s for a particular value, and once you find it, you don't care about the other elements of the array. For the times when you want to bail, the Java language provides the break statement, shown in Listing The break statement takes you to the next executable statement outside of the loop in which it's located.
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. The square brackets in this section's code examples are part of the required syntax for Java arrays, not indicators of optional elements.
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:. Another way to create an array is to create it and then code a loop to initialize it:. 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.
You'll learn about exceptions and how to handle them in Part 2. 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. This syntax also works, and because it's simpler to work with I use it throughout this section:. 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  , and the last is at arrayName [ arrayName.
You've seen how arrays can hold primitive types, but it's worth mentioning that they can also hold objects. Creating an array of java. Integer objects isn't much different from creating an array of primitive types and, again, you can do it in two ways:. 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:. This technique is known as boxing , because you're putting the primitive into a wrapper, or box. Similarly, to convert the Integer representation back to its int counterpart, you unbox it:.
Strictly speaking, you don't need to box and unbox primitives explicitly. Instead, you can use the Java language's autoboxing and auto-unboxing features:. I recommend that you avoid autoboxing and auto-unboxing, however, because it can lead to code-readability issues.
The code in the boxing and unboxing snippets is more obvious, and thus more readable, than the autoboxed code; I believe that's worth the extra effort. You've seen how to obtain a boxed type, but what about parsing a numeric String that you suspect has a boxed type into its correct box? The JDK wrapper classes have methods for that, too:. You can also convert the contents of a JDK wrapper type to a String:. Note that when you use the concatenation operator in a String expression you've already seen this in calls to Logger , the primitive type is autoboxed, and wrapper types automatically have toString invoked on them.
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. List is an interface, so you can't instantiate it directly. You'll learn about interfaces in Part 2. You'll work here with its most commonly used implementation, ArrayList. You can make the declaration in two ways.
The first uses the explicit syntax:. Notice that the type of the object in the ArrayList instantiation isn't specified. This is the case because the type of the class on the right side of the expression must match that of the left side. Throughout the remainder of this tutorial, I use both types, because you're likely to see both usages in practice. 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.
In a later section, you'll look more at the rules governing these types of variable assignments. If you want to tighten up the constraints on what can or cannot go into the List , you can define the formal type differently:. Using List s — like using Java collections in general — is super easy. Here are some of the things you can do with List s:. The add method adds the element to the end of the List. To retrieve an item from the List , call get and pass it the index of the item you want:.
In a real-world application, a List would contain records, or business objects, and you'd possibly want to look over them all as part of your processing. 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.
If a collection implements java. Iterable , it's called an iterable collection. You can start at one end and walk through the collection item-by-item until you run out of items. In the " Loops section, I briefly mentioned the special syntax for iterating over collections that implement the Iterable interface.
Here it is again in more detail:. The first snippet uses shorthand syntax: It has no index variable aa in this case to initialize, and no call to the List 's get method. 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. Because Set is an interface, you can't instantiate it directly. One of my favorite implementations is HashSet , which is easy to use and similar to List.
A Set 's distinguishing attribute is that it guarantees uniqueness among its elements but doesn't care about the order of the elements. 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. 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. As you might imagine, the key to the Map must be unique, and it's used to retrieve the value at a later time. A Java Map collection can only hold objects, and it defines a strict contract about how it behaves. Because Map is an interface, you can't instantiate it directly. 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.
Java Programming Basics
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. Uniqueness not order is the distinguishing characteristic of a Set which might explain why there's no keyList method.
Now that you've learned a bit about writing Java applications, you might be wondering how to package them up so that other developers can use them, or how to import other developers' code into your applications. 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. 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. The JDK is comprehensive, but it doesn't do everything you need for writing great Java code. 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 It's common in naming a JAR file to include the version number, in this case 3. Now all you need to do is tell Eclipse to include the classes in the commons-lang After Eclipse processes the code that is, the class files in the JAR file, they're available to reference import from your Java code. Notice in Project Explorer that you have a new folder called Referenced Libraries that contains the commons-lang You've got enough Java syntax under your belt to write basic Java programs, which means that the first half of this tutorial is about to conclude.
This final section lays out a few best practices that can help you write cleaner, more maintainable Java code. So far you've created a few classes. At that size, Person is a small class. It's not uncommon and it's unfortunate to see classes with 50 or methods and a thousand lines or more of source. 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. In general, a class represents a conceptual entity in your application, and a class's size should reflect only the functionality to do whatever that entity needs to do. Keep your classes tightly focused to do a small number of things and do them well.
Keep only the methods that you need. If you need several helper methods that do essentially the same thing but take different parameters such as the printAudit method , that's a fine choice. 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. Certainly, a ridiculously long name can be inconvenient, but a name that conveys what a method does needn't be ridiculously long.
Six months after you write a bunch of code, you might not remember what you meant to do with a method called compInt , but it's obvious that a method called computeInterest , well, probably computes interest. 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. In the footsteps of Fowler The best book in the industry in my opinion, and I'm not alone is Refactoring: This book is even fun to read. The authors talk about "code smells" that beg for refactoring, and they go into great detail about the various techniques for fixing them. 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. I've found that a method doing only one thing well doesn't usually take more than about 30 lines of code. 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.
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? I'll give you two reasons why I believe this adage is false:.
Java (programming language)
About this Course Taking this course will provide you with a basic foundation in Java syntax, which is the first step towards becoming a successful Java developer. Free Course Java Programming Basics Enhance your skill set and boost your hirability through innovative, independent learning.
Nanodegree Program Android Basics by. Discover the basic idea behind programing. Write your first Java program. Use variables to store and retrieve information. Use if-else statements and switch-case statements. Write Java programs to tackle any decision making scenario.
- Using Methods and Conditional Statements;
- Essentials of the Java Programming Language, Part 1;
- The Survivors Guide to Theology?
- Java (programming language) - Wikipedia?
- Table of Contents.
- Java language basics.
- Mountain Ranges: Geography & Nature!
Create functions in Java. Declare methods with input arguments and return types. Call the functions you create. Use for and while loops to iterate over a block of code. Learn how to write nested loops. Use 2D arrays to store and retrieve information. Use the IDE to find and solve problems in code.
No prior programming experience is needed.