Java 1 Unit
Java 1 Unit
UNIT-1
The primary objective of Java programming language creation was to make it portable, simple and secure
programming language. Apart from this, there are also some excellent features which play an important role in
the popularity of this language. The features of Java are also known as java buzzwords.
Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to Sun, Java
language is a simple programming language because:
• Java syntax is based on C++ (so easier for programmers to learn it after C++).
• Java has removed many complicated and rarely-used features, for example, explicit pointers, operator
overloading, etc.
• There is no need to remove unreferenced objects because there is an Automatic Garbage Collection in
Java.
Object-oriented
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
Platform Independent
Java is platform independent because it is different from other languages like C, C++, etc. which are
compiled into platform specific machines while Java is a write once, run anywhere language. A platform is
the hardware or software environment in which a program runs.
There are two types of platforms software-based and hardware-based. Java provides a software-based
platform.
The Java platform differs from most other platforms in the sense that it is a software-based platform that runs
on the top of other hardware-based platforms. It has two components:
1. Runtime Environment
2. API(Application Programming Interface)
Java code can be run on multiple platforms, for example, Windows, Linux, Sun Solaris, Mac/OS, etc. Java
code is compiled by the compiler and converted into bytecode. This bytecode is a platform-independent code
because it can be run on multiple platforms, i.e., Write Once and Run Anywhere(WORA).
Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is secured because:
• No explicit pointer
• Java Programs run inside a virtual machine sandbox
• Classloader: Classloader in Java is a part of the Java Runtime Environment(JRE) which is used to
load Java classes into the Java Virtual Machine dynamically. It adds security by separating the
package for the classes of the local file system from those that are imported from network sources.
• Bytecode Verifier: It checks the code fragments for illegal code that can violate access right to
objects.
• Security Manager: It determines what resources a class can access such as reading and writing to the
local disk.
Java language provides these securities by default. Some security can also be provided by an application
developer explicitly through SSL, JAAS, Cryptography, etc.
Robust
Architecture-neutral
Java is architecture neutral because there are no implementation dependent features, for example, the size of
primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes of memory
for 64-bit architecture. However, it occupies 4 bytes of memory for both 32 and 64-bit architectures in Java.
Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't require any
implementation.
High-performance
Java is faster than other traditional interpreted programming languages because Java bytecode is "close" to
native code. It is still a little bit slower than a compiled language (e.g., C++). Java is an interpreted language
that is why it is slower than compiled languages, e.g., C, C++, etc.
Distributed
Java is distributed because it facilitates users to create distributed applications in Java. RMI and EJB are used
for creating distributed applications. This feature of Java makes us able to access files by calling the methods
from any machine on the internet.
Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs that deal with many
tasks at once by defining multiple threads. The main advantage of multi-threading is that it doesn't occupy
memory for each thread. It shares a common memory area. Threads are important for multi-media, Web
applications, etc.
Dynamic
Java is a dynamic language. It supports dynamic loading of classes. It means classes are loaded on demand. It
also supports functions from its native languages, i.e., C and C++. Java supports dynamic compilation and
automatic memory management (garbage collection).
package ch01.sec01;
// our first java program. Call this file “HelloWorld.java”
class HelloWorld
{
public static void main(String args[ ])
{
System.out.println(“Hello, World!”);
}
}
➢ For most computer languages, the name of the file that holds the source code to a program is immaterial.
However, this is not the case with Java. The first thing that you must learn about Java is that the name
you give to a source file is very important. For this example, the name of the source file should be
HelloWorld.java.
➢ As you can see by looking at the program, the name of the class defined by the program is also Example.
This is not a coincidence. In Java, all code must reside inside a class. By convention, the name of that
class should match the name of the file that holds the program. You should also make sure that the
capitalization of the filename matches the class name. Java is case-sensitive language.
System.out.println(“Hello, World!”);
➢ This line outputs the string “Hello, World!” followed by a new line on the screen. Output is actually
accomplished by the built-in println( ) method. In this case, println( ) displays the string which is
passed to it. As you will see, println( ) can be used to display other types of information, too. The line
begins with System.out. While too complicated to explain in detail at this time, briefly, System is a
predefined class that provides access to the system, and out is the output stream that is connected to the
console.
➢ To compile and run the program, you need to install the Java Development Kit(JDK) and, optionally,
an Integrated Development Environment(IDE). Once you have installed the JDK, Open a terminal
window and run the commands
javac ch01/sec01/HelloWorld.java
java ch01.sec01.HellWorld
➢ Note that 2 steps are involved to execute the program. The javac command compiles the java source
code into an intermediate machine-independent representation called bytecodes, and saves them in class
files. The javac compiler creates a file called HelloWorld.class that contains the bytecode version of
the program. The java command launches a virtual machine that loads the class files, and executes the
bytecodes.
➢ Once compiled, byte codes can run on any JVM, whether on your desktop computers or on a device in
a galaxy far, far away. The promise of “write once, run anywhere” was an important design criterion
for java.
❖ Primitive Types
Even though Java is an object-oriented programming language, not all Java values are objects. Instead, some
values belong to primitive types. Four of these types are signed integer types, two are floating-point number
types, one is the character type char that is used in the encoding for strings, and one is the boolean type for truth
values.
➢ In most situations, the int type is the most practical. If you want to represent the number of
inhabitants of our planet, you’ll need to resort to a long. The byte and short types are mainly
intended for specialized applications, such as low-level file handling, or for large arrays when
storage space is at a premium. In Java, the ranges of the integer types do not depend on the machine
on which you will be running your program.
➢ You write long integer literals with a suffix L. There is no syntax for literals of type byte or
short. Use the cast notation, for example, (byte) 127. Hexadecimal literals have a prefix
0x. Binary values have a prefix 0b. For example, 0b1001 is 9.
2. Floating-Point types
The floating-point types denote numbers with fractional parts.
Type Storage Requirement Range
float 4 bytes Approximately +-
3.4028347E+38F (6-7
significant decimal digits)
double 8 bytes Approximately +-
1.79769313486231570E+308(15
significant decimal digits)
➢ Many years ago, when memory was a scarce resource, four-byte floating-point numbers were in
common use. But seven decimal digits don't go very far, and nowadays, “double precision”
numbers are the default. It only makes sense to use floatwhen you need to store a large number
of them.
➢ Numbers of type float have a suffix F (for example, 3.14F). Floating-point literals without an F
suffix (such as 3.14) have type double. You can optionally supply the D suffix (for example,
3.14D).
int total = 0;
• You can declare multiple variables of the same type in a single statement:
• Most Java programmers prefer to use separate declarations for each variable. The name of a
variable (as well as a method or class) must begin with a letter. It can consist of any letters,
digits, and the symbols _and $. However, the $symbol is intended for automatically generated
names, and you should not use it in your names. Finally, the _by itself is not a valid variable
name.
• You cannot use spaces or symbols in a name. Finally, you cannot use a keyword such as
doubleas a name.
• By convention, names of variables and methods start with a lowercase letter, and names of
classes start with an uppercase letter. Java programmers like “camel case,” where uppercase
letters are used when names consist of multiple words, like CountOfInvalidInputs.
2. Variable Initialization
• When you declare a variable in a method, you must initialize it before you can use it. For example,
the following code results in a compile-time error:
int count;
count++; // Error—uses an uninitialized variable
• The compiler must be able to verify that a variable has been initialized before it has been used.
The variable is declared at the point at which its initial value is available.
3. Constants
• The final keyword denotes a value that cannot be changed once it has been assigned. In other
languages, one would call such a value a constant. For example,
Then the constant can be used in multiple methods. Inside Calendar, you refer to the constant
as DAYS_PER_WEEK. To use the constant in another class, prepend the class name:
Calendar.DAYS_PER_WEEK.
❖ Arithmetic Operations
Java uses the familiar operators of any C-based language. We will review them in the following sections.
Operators Associativity
[] . () (method call) Left
! ~ ++ -- + (unary) - (unary) () (cast) Right
new
* / % (modulus) Left
+ - Left
In this table, operators are listed by decreasing precedence. For example, since + has a higher
precedence than <<, the value of 3 + 4 << 5is (3 + 4) << 5. An operator is left-associative when it is
grouped left to right. For example, 3 - 4 - 5 means (3 - 4) - 5. But -= is right- associative, and i -= j
-= k means i -= (j -=k).
Assignment Operator
The statement
x = expression;
sets x to the value of the right-hand side, replacing the previous value. When = is preceded by an
operator, the operator combines the left- and right-hand sides and the result is assigned. For example,
amount -= 10;
is the same as
As in other C-based languages, there is also a prefix form of these operators. Both n++ and
++n increment the variable n, but they have different values when they are used inside an
expression. The first form yields the value before the increment, and the second the value after
the increment.
Mathematical Methods
• There is no operator for raising numbers to a power. Instead, call the Math.pow method:
Math.pow(x, y) yields xy. To compute the square root of x, call Math.sqrt(x). These are static
methods that don't operate on objects. Like with staticconstants, you prepend the name of the
class in which they are declared.
• Also useful are Math.minand Math.maxfor computing the minimum and maximum of two
values. In addition, the Mathclass provides trigonometric and logarithmic functions as well as
the constants Math.PIand Math.E.
• A few mathematical methods are in other classes. For example, there are methods
compareUnsigned, divideUnsigned, and remainderUnsignedin the Integerand Longclasses
to work with unsigned values.
double x = 42;
• To make a conversion that is not among these permitted ones, use a castoperator: the name of the
target type in parentheses. For example,
double x =3.75;
int n = (int) x;
int n = 1;
yields the string "am"if time < 12and the string "pm" otherwise.
Big Numbers
• If the precision of the primitive integer and floating-point types is not sufficient, you can turn
to the BigInteger and BigDecimal classes in the java.math package. Objects of these classes
represent numbers with an arbitrarily long sequence of digits. The BigInteger class implements
arbitrary-precision integer arithmetic, and BigDecimal does the same for floating-point
numbers.
The static valueOfmethod turns a longinto a BigInteger:
BigInteger n = BigInteger.valueOf(876543210123456789L);
The result of
is exactly 0.9.
❖ Strings
A string is a sequence of characters. In Java, a string can contain any Unicode characters.
1. String Concatenation
Output:
java string
java string is immutable so assign it explicitly
programming example 2:
sets greetingto the string "Hello Java". (Note the space at the end of the first operand.)
When you concatenate a string with another value, that value is converted to a string.
first concatenates ageand then 1. The result is "Next year, you will be 421". In such
cases, use parentheses:
2. Substrings
We pass begin index and end index number position in the java substring method where start
index is inclusive and end index is exclusive. In other words, start index starts from 0 whereas
end index starts from 1.
The first argument of the substring method is the starting position of the substring to extract.
Positions start at 0.The second argument is the first position that should not be included in the
substring. In our example, position 12 of greeting is the !, which we do not want. It may seem
curious to specify an unwanted position, but there is an advantage: the difference 12 - 7is the
length of the substring.
Sometimes, you want to extract all substrings from a string that are separated by a delimiter.
The splitmethod carries out that task, returning an array of substrings.
Output:
va
vacse
3. String Comparison
The java string equals() method compares the two given strings based on the content of the string. If
any character is not matched, it returns false. If all characters are matched, it returns true.
}}
output
true
false
false
The String compareTo() method compares values lexicographically and returns an integer value that
describes if first string is less than, equal to or greater than second string.
• s1 == s2 :0
• s1 > s2 :positive value
• s1 < s2 :negative value
class Teststringcomparison4{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
System.out.println(s1.compareTo(s2));//0
System.out.println(s1.compareTo(s3));//1(because s1>s3)
System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
}
}
Output:0
1
-1
To compare two strings without regard to case, use the equalsIgnoreCase method. For example,
"world".equalsIgnoreCase(location);
returns trueif locationis "World", "world", "WORLD", and so on. Sometimes, one needs to put strings in
order. The compareTomethod tells you whether one string comes before another in dictionary order. The call
Syntax
Return Value
• This method returns a negative integer, zero, or a positive integer as the specified String
is greater than, equal to, or less than this String, ignoring case considerations.
Example program
This method has two variants. The first variant converts all of the characters in this String to lower
case using the rules of the given Locale.
Syntax:
Return Value
Example program
import java.io.*;
public class Test {
This method has two variants. The first variant converts all of the characters in this String to upper case using
the rules of the given Locale.
Syntax
Return Value
Example program
import java.io.*;
public class Test {
int n = 42;
String str = Integer.toString(n); // Sets str to "42"
A variant of this method has a second parameter, a radix (between 2 and 36):
Method Purpose
boolean Checks whether a string starts with, ends with, or contains a
startsWith(String str) given string.
boolean
endsWith(String str)
boolean
contains(CharSequence
str)
int indexOf(String str) Gets the position of the first or last occurrence of str, searching
int lastIndexOf(String the entire string or the substring starting at fromIndex. Returns
str) -1if no match is found.
int indexOf(String str,
int fromIndex) int
lastIndexOf(String str,
int fromIndex)
Note that in Java, the Stringclass is immutable. That is, none of the String
methods modify the string on which they operate. For example,
greeting.toUpperCase()
1. Reading Input
When you call System.out.println, output is sent to the “standard output stream” and shows up in a terminal
window. Reading from the “standard input
stream” isn’t quite as simple because the corresponding System.in object only has methods to read
individual bytes. To read strings and numbers, construct a Scannerthat is attached to System.in:
Here, it makes sense to use the nextLinemethod because the input might contain spaces. To read a single
word (delimited by whitespace), call
if (in.hasNextInt()) {
...
}
The Scannerclass is located in the java.utilpackage. In order to use the class, add the line
import java.util.Scanner
import java.util.*;
public class ScannerExample {
public static void main(String args[]){
Scanner in = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = in.nextLine();
System.out.println("Name is: " + name);
in.close();
}
}
Output:
Example program2
import java.util.*;
public class ScannerClassExample1 {
public static void main(String args[]){
String s = "Hello, This is REVA";
//Create scanner Object and pass string in it
Scanner scan = new Scanner(s);
//Check if the scanner has a token
System.out.println("Boolean Result: " + scan.hasNext());
//Print the string
System.out.println("String: " +scan.nextLine());
scan.close();
System.out.println("--------Enter Your Details-------- ");
Scanner in = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = in.next();
System.out.println("Name: " + name);
System.out.print("Enter your age: ");
int i = in.nextInt();
System.out.println("Age: " + i);
System.out.print("Enter your salary: ");
double d = in.nextDouble();
System.out.println("Salary: " + d);
in.close();
}
}
Output:
2. Formatted Output
You have already seen the println method of the System.out object for writing a line of output. There is
also a printmethod that does not start a new line. That method is often used for input prompts:
Then the cursor rests after the prompt instead of the next line.
When you print a fractional number with printor println, all of its digits except trailing zeroes will be
displayed. For example,
System.out.print(1000.0 / 3.0);
prints
333.3333333333333
That is a problem if you want to display, for example, dollars and cents. To limit the number of digits, use
the printfmethod:
The format string "%8.2f"indicates that a floating-point number is printed with a field width of 8 and 2
digits of precision. That is, the printout contains two leading spaces and six characters:
333.33
Each of the format specifiers that start with a % character is replaced with the corresponding argument. The
conversion character that ends a format specifier indicates the type of the value to be formatted: fis a floating-
point number, sa string, and da decimal integer
Conversion characters for formatted output
c or C Character j or J
In addition, you can specify flags to control the appearance of the formatted output.. For example, the
comma flag adds grouping separators, and + yields a sign for positive numbers. The statement
# (for x
or o Adds 0x or 0 prefix 0xcafe
format)
Specifies the index of the argument to be formatted; for
$ example, %1$d %1$x prints the first argument in decimal and 159 9f
hexadecimal.
Formats the same value as the previous specification; for
159 9f
< example, %d %<x prints the same number in decimal and hexadecimal.
❖ Control Flow
In the following sections, you will see how to implement branches and loops. The Java syntax for control
flow statements is very similar to that of other commonly used languages, in particular C/C++ and
JavaScript.
1. Branches
The ifstatement has a condition in parentheses, followed by either one statement or a group of statements
enclosed in braces.
if (count > 0) {
You can have an elsebranch that runs if the condition is not fulfilled.
if (count > 0) {
} else {
System.out.println(0);
else if (count == 0)
System.out.println(0);
else
System.out.println("Huh?");
When you need to test an expression against a finite number of constant values, use the switch statement.
switch (count)
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
default:
Execution starts at the matching caselabel or, if there is no match, at the default label (if it is present). All
statements are executed until a break or the end of the switchstatement is reached.
In the preceding example, the caselabels were integers. You can use values of any of the following types:
• A constant expression of type char, byte, short, or int
• A string literal
• A value of an enumeration
2. Loops
The whileloop keeps executing its body while more work needs to be done, as determined by a condition.
For example, consider the task of summing up numbers until the sum has reached a target. For the source
of numbers, we will use a random number generator, provided by the Randomclass in the java.utilpackage.
count++;
This is a typical use of a whileloop. While the sum is less than the target, the loop keeps executing.
Sometimes, you need to execute the loop body before you can evaluate the condition. Suppose you want
to find out how long it takes to get a particular value. Before you can test that condition, you need to enter
the loop and get the value. In this case, use a do/whileloop:
int next;
do
The loop body is entered, and nextis set. Then the condition is evaluated. As long as it is fulfilled, the loop
body is repeated.
In the preceding examples, the number of loop iterations was not known. However, in many loops that
occur in practice, the number of iterations is fixed. In those situations, it is best to use the for loop.
This loop computes the sum of a fixed number of random values:
This loop runs 20 times, with iset to 1, 2, ..., 20 in each loop iteration.
You can rewrite any for loop as a whileloop. The loop above is equivalent to
int i = 1;
i++;
However, with the whileloop, the initialization, test, and update of the variable i
are scattered in different places. With the for loop, they stay neatly together.
The initialization, test, and update can take on arbitrary forms. For example, you can double a value while
it is less than the target:
Instead of declaring a variable in the header of the forloop, you can initialize an existing variable:
You can declare or initialize multiple variables and provide multiple updates, separated by commas. For
example,
If no initialization or update is required, leave them blank. If you omit the condition, it is deemed to always
be true.
You will see in the next section how you can break out of such a loop.
while (!done)
if ("Q".equals(input))
done = true;
else
Process input
}
This loop carries out the same task with a breakstatement:
while (true)
Process input
// breakjumps here
while (in.hasNextInt())
Process input
Process input
The break statement only breaks out of the immediately enclosing loop or switch. If you want to jump to
the end of another enclosing statement, use a labeled breakstatement. Label the statement that should be
exited, and provide the label with the breaklike this:
outer:
while (...)
...
while (...)
...
...
...
A regular breakcan only be used to exit a loop or switch, but a labeled break
can transfer control to the end of any statement, even a block statement:
exit: {
...
...
There is also a labeled continuestatement that jumps to the next iteration of a labeled loop
while (...)
System.out.println(...);
In other words, a new copy of inputis created for each loop iteration, and the variable does not exist outside
the loop.
The scope of a parameter variable is the entire method.
...
Here is a situation where you need to understand scope rules. This loop counts how many tries it takes to
get a particular random digit:
int next;
do
The variable next had to be declared outside the loop so it is available in the condition. Had it been declared
inside the loop, its scope would only reach to the end of the loop body.
When you declare a variable in a for loop, its scope extends to the end of the loop, including the test and
update statements.
...
If you need the value of iafter the loop, declare the variable outside:
int i;
{
...
// istill available
In Java, you cannot have local variables with the same name in overlapping scopes.
...
However, if the scopes do not overlap, you can reuse the same variable name:
String[] names;
The variable isn't yet initialized. Let's initialize it with a new array. For that, we need the new operator:
Now namesrefers to an array with 100 elements, which you can access as
names[0] ... names[99].
//Java Program to illustrate how to declare, instantiate, initialize and traverse the Java array.
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}
1. arr[0][0]=1;
2. arr[0][1]=2;
3. arr[0][2]=3;
4. arr[1][0]=4;
5. arr[1][1]=5;
6. arr[1][2]=6;
7. arr[2][0]=7;
8. arr[2][1]=8;
9. arr[2][2]=9;
class Testarray3{
Output:
1 2 3
2 4 5
4 4 5
Output:
0 1 2
3 4 5 6
7 8
2. Array Construction
When you construct an array with the newoperator, it is filled with a default value.
1.Arrays of numeric type (including char) are filled with zeroes.
2.Arrays of booleanare filled with false.
3.Arrays of objects are filled with nullreferences.
You can fill an array with values by writing a loop, as you saw in the preceding section. However,
sometimes you know the values that you want, and you can just list them inside braces:
You don't use the new operator, and you don't specify the array length. A trailing comma is allowed, which
can be convenient for an array to which you keep adding values over time:
// Add more names here and put a comma after each name
};
Use a similar initialization syntax if you don't want to give the array a name—for example, to assign it to
an existing array variable:
3. Array Lists
When you construct an array, you need to know its length. Once constructed, the length can never change.
That is inconvenient in many practical applications. A remedy is to use the ArrayList class in the java.util
package. An ArrayList object manages an array internally. When that array becomes too small or is
insufficiently utilized, another internal array is automatically created, and the elements are moved into it.
This process is invisible to the programmer using the array list.
The syntax for arrays and array lists is completely different. Arrays use a special syntax—the []operator
for accessing elements, the Type[]syntax for array types, and the new Type[n] syntax for constructing
arrays. In contrast, array lists are classes, and you use the normal syntax for constructing instances and
invoking methods.
However, unlike the classes that you have seen so far, the ArrayList class is a generic class—a class
with a type parameter.
To declare an array list variable, you use the syntax for generic classes and specify the type in angle
brackets:
ArrayList<String> friends;
As with arrays, this only declares the variable. You now need to construct an array list:
// or new ArrayList<String>()
Note the empty <>. The compiler infers the type parameter from the type of the variable. (This shortcut is
called the diamond syntax because the empty angle brackets have the shape of a diamond.)
There are no construction arguments in this call, but it is still necessary to supply the
()at the end.
The result is an array list of size 0. You can add elements to the end with the add
method:
friends.add("Peter"); friends.add("Paul");
Unfortunately, there is no initializer syntax for array lists. The best you can do is construct an array list like
this:
The List.ofmethod yields an unmodifiable list of the given elements which you then use to construct an
ArrayList.
friends.remove(1);
To access elements, use method calls, not the [] syntax. The getmethod reads an element, and the set
method replaces an element with another:
The sizemethod yields the current size of the list. Use the following loop to traverse all elements:
Conversion between primitive types and their corresponding wrapper types is automatic. In the call to add,
an Integerobject holding the value 42was automatically constructed in a process called autoboxing.
In the last line of the code segment, the call to get returned an Integer object. Before assigning to the int
variable, the object was unboxed to yield the intvalue inside.
int sum = 0;
sum += numbers[i];
As this loop is so common, there is a convenient shortcut, called the enhanced for
loop:
int sum = 0;
sum += n;
The loop variable of the enhanced forloop traverses the elements of the array, not the index values. The
variable nis assigned to numbers[0], numbers[1], and so on.
You can also use the enhanced forloop with array lists. If friendsis an array list of strings, you can print
them all with the loop
}
6. Copying Arrays and Array Lists
You can copy one array variable into another, but then both variables will refer to the same array, as shown
in the figure
If you don't want this sharing, you need to make a copy of the array. Use the static
Arrays.copyOfmethod.
This method constructs a new array of the desired length and copies the elements of the original array into
it.
Array list references work the same way:
To copy an array list, construct a new array list from the existing one:
That constructor can also be used to copy an array into an array list. Wrap the array into an immutable list,
using the List.of method, and then construct an ArrayList:
7. Array Algorithms
The Arraysand Collectionsclasses provide implementations of common algorithms for arrays and
array lists. Here is how to fill an array or an array list:
Arrays.sort(names); Collections.sort(friends);
The Arrays.toStringmethod yields a string representation of an array. This is particularly useful to print an
array for debugging.
System.out.println(Arrays.toString(primes));
For printing, you don't even need to call it—the printlnmethod takes care of that.
System.out.println(friends);
There are a couple of useful algorithms for array lists that have no counterpart for arrays.
As you have already seen, the mainmethod of every Java program has a parameter that is a string array:
When a program is executed, this parameter is set to the arguments specified on the command line.
For example, consider this program:
then args[0]is "-g", args[1]is "cruel", and args[2]is "world". Note that neither "java"nor "Greeting"
are passed to the mainmethod.
9. Multidimensional Arrays
Java does not have true multidimensional arrays. They are implemented as arrays of arrays. For example, here
is how you declare and implement a two-dimensional array of integers:
int[][] square = {
{ 16, 3, 2, 13 },
{ 5, 10, 11, 8 },
{ 9, 6, 7, 12 },
{ 4, 15, 14, 1}
};
The first index selects the row array square[1]. The second index picks the element from that row.
You can even swap rows:
Behind the scenes, an array of rows is filled with an array for each row.
There is no requirement that the row arrays have equal length. For example, you can store
the Pascal triangle:
11
121
1331
14641
...
triangle[i][i] = 1;
[j];
To traverse a two-dimensional array, you need two loops, one for the rows and one for the
columns:
}
System.out.println();
System.out.printf("%4d", element);
System.out.println();
These loops work for square arrays as well as arrays with varying row lengths.