Media, Inc. Learning Java, Fourth Edition, the image of a Bengal tigress This edition of Learning Java is actually the sixth edition—updated. Learning Computer. Programming using with. Examples. JAVA. Atiwong programming languages are presented through writing Java programs. Java is. Tutorials on Java language, Java computer programming language and others PDF courses- page 1.
|Language:||English, Spanish, Arabic|
|Genre:||Academic & Education|
|ePub File Size:||15.50 MB|
|PDF File Size:||11.57 MB|
|Distribution:||Free* [*Regsitration Required]|
Learning. Center abcd. W. R. F. S. MTWR. About This Book. This book teaches you all what programming is, but you've heard Java is easy to learn, really. Java is the most popular programming language & is the language of choice for Android Key Highlights of Java Tutorial PDF are. + pages. advanced concepts related to Java Programming language. Prerequisites can use to execute your Java programs at the spot and enjoy your learning.
The two-part Introduction to Java programming tutorial is meant for software developers who are new to Java technology. Work through both parts to get up and running with object-oriented programming OOP and real-world application development using the Java language and platform. This first part is a step-by-step introduction to OOP using the Java language. Programming examples in Part 2 build on the Person object that you begin developing in Part 1. This tutorial is for software developers who are not yet experienced with Java code or the Java platform.
Other methods look much like constructors, with a couple of exceptions. First, you can name other methods whatever you like though, of course, certain rules apply. I recommend the following conventions:. Armed with this basic information, you can see in Listing 4 what happens when you add a few more methods to the Person object.
Listing 4. Person with a few new methods package com. For now, all you need to know is that a getter is a method for retrieving the value of an attribute, and a setter is a method for modifying that value. Generally, two types of nonconstructor methods are used: Instance methods depend on the state of a specific object instance for their behavior.
The syntax for invoking a static method on a class is different from the syntax used to invoke a method on an object. You also use the name of the class that contains the static method, as shown in this invocation:.
In this example, Logger is the name of the class, and getLogger This section walks you through declaring a class and adding variables and methods to it using the Eclipse Package Explorer. The first step is to create a place for the class to live. Rather than use the default package almost always a bad idea , you create one specifically for the code you are writing. Type com. You can see the new package created in the Package Explorer. The New Class dialog box opens. In the Name text box, type Person and then click Finish.
The new class is displayed in your edit window. I recommend closing a few of the views Problems, Javadoc, and others that open by default in the Java Perspective the first time you open it to make it easier to see your source code. Figure 5 shows a workspace with the essential views open.
Eclipse generates a shell class for you and includes the package statement at the top. You just need to flesh out the class now. And notice that the code is unsaved.
Next, notice that I made a mistake when declaring the Name attribute: Of course, I can fix my mistake by adding a g to the end of Strin. This is a small demonstration of the power of using an IDE instead of command-line tools for software development. Go ahead and correct the error by changing the type to String.
Recall that a variable has an accessSpecifier accessSpecifier , a dataType dataType , a variableName variableName , and, optionally, an initialValue initialValue.
Earlier, you looked briefly at how to define the accessSpecifier accessSpecifier and variableName variableName. Now, you see the dataType dataType that a variable can have. A dataType dataType can be either a primitive type or a reference to another object. For example, notice that Age is an int a primitive type and that Name is a String an object. The JDK comes packed full of useful classes like java.
String , and those in the java. But whether the dataType dataType is a JDK class such as String or a user-defined class, the syntax is essentially the same.
Before going further into coding, you need to know how your programs tell you what they are doing. The Java platform includes the java.
Loggers are named entities that you create through a static method call to the Logger class:. When calling the getLogger method, you pass it a String. From any regular that is, nonstatic method, the preceding code always references the name of the class and passes that to the Logger. 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. 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.
Listing 5. Make sure that you have no wavy lines indicating compile errors. Using main as a test harness. 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.
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. Listing 6. Just enter the code as you see it in Listing 6.
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. The getters and setters that you saw in action at the end of the preceding section are called accessor methods. Quick review: 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. Java Notes for Professionals book Beginner Description: Hibernate Notes for Professionals book Beginner Description: Download free course Hibernate Notes for Professionals book, pdf ebook tutorials on 39 pages by GoalKicker.
Java Programming Basics Beginner Description: Spring by Example Beginner Description: Office Computer programming Web programming Database 93 Operating system 63 Mathematics 59 Graphics 53 Network 48 Computer security 44 Other 41 Computer architecture 23 design and analysis Learning Java Language Beginner new. Java Notes for Professionals book Beginner.
Hibernate Notes for Professionals book Beginner. Java Programming Basics Beginner.