Uncategorized

Programming Language Fundamentals by Example

Data types help classify what information a variable can hold and what can be done with it. Meanwhile, a data structure is also a data type, but one that contains an unlimited number of named sub-categories. In this way, the program can parse individual data types while still treating the entire structure as one data type. Functions are self-contained modules of code that accomplish a particular task.

Once a function is written, it can be called and used repeatedly. They operate like a black box: Functions let you reuse code rather than constantly rewrite it, and allow you to think about your program as a series of sub-steps. Functions are also known as routines or subroutines. Recognizing these five components of a computer language will help you situate yourself when learning a new language.

Simple to learn and easily read Associated web frameworks for developing web-based applications Free interpreter and standard library available in source or binary on major platforms Where did it start? Create a dice rolling simulator at KnightLab. Software engineers, Java developers Used by employers in communications, education, finance, health sciences, hospitality, retail and utilities Major Organizations: Java is the core foundation for developing Android apps. Application portability Robust and interpreted language Extensive network library Where did it start?

Create a City Classified and Search application or choose another project through Javatpoint. Ruby on Rails developers, software engineers, data science engineers Used by employers in technology, engineering, professional services, design, science and quality control Major Organizations: Ruby is used for simulations, 3D modeling, and to manage and track information. NASA uses Ruby to conduct simulations.

Free to use, copy, modify and distribute Intuitive and flexible language Completely object-oriented ability to use method chaining Where did it start? Web Development, Email Programming What makes learning it important? Tweetmap, created by Pete Smart and Rob Hawkes using JavaScript, represents a world map that is proportionally sized according to the number of tweets. Basic features are easy to learn Multiple frameworks Users can reference JQuery, a comprehensive Javascript library Where did it start?

Software developers, computer engineers, business and systems analysts, IT and Web content administrators, embedded software engineers Used by employers in Information Technology, Engineering, Management, Healthcare and Professional Services Major Organizations: Most device drivers are still developed using C Language. Simple to learn; there are only 32 keywords to master Easy to write systems programs such as compilers and interpreters Foundational language for beginners Where did it start?

Forums Stack Overflow Cprogramming. Create a tic-tac-toe game using opensource code. Often the first programming language taught at college level Quick processing and compilation mechanism Robust standard library STL Where did it start? Create a student database or other similar system through Code in code:: C developers, automation test engineers, software engineers, senior. Microsoft Intel, Hewlett Packard Specializations: Windows-based platforms What makes learning it important? Similar to Java in capabilities Ideal for beginners The go-to for working on Microsoft apps Where did it start?

Code Try it out! 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.

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.

Account Options

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. 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.

Language fundamentals - Wikibooks, open books for an open world

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 [0] , 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.

Language fundamentals

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.

Language types

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.

C Programming Tutorial 1 - Intro to C

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.

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.


  • The Closing and Reuse of the Philadelphia Naval Shipyard.
  • The Horrible Witches of Ice!
  • Urban Growth Analysis and Remote Sensing: A Case Study of Kolkata, India 1980–2010 (SpringerBriefs in Geography).
  • Novena Meditations With Teresa of Calcutta.

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.