0% found this document useful (0 votes)
110 views

Java 1 Unit

The document describes a Java programming course that covers fundamental programming structures and the "Hello World" program. It includes an introduction to Java, its history and key features such as being object-oriented, platform independent, secure, robust, and high-performance. The document also dissects the "Hello World" program, explaining the need for the source file and class to have the same name and how it uses packages, comments, and defines behavior through a class.

Uploaded by

MANOJKUMAR M
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
110 views

Java 1 Unit

The document describes a Java programming course that covers fundamental programming structures and the "Hello World" program. It includes an introduction to Java, its history and key features such as being object-oriented, platform independent, secure, robust, and high-performance. The document also dissects the "Hello World" program, explaining the need for the source file and class to have the same name and how it uses packages, comments, and defines behavior through a class.

Uploaded by

MANOJKUMAR M
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

COURSE TITLE: PROGRAMMING WITH JAVA

COURSE CODE: 18BCS33

UNIT-1

FUNDAMENTAL PROGRAMMING STRUCTURES

❖ Introduction to Java Language


➢ Java is one of the world’s most important and widely used computer languages. Java leapt to the
forefront of internet programming with its first release. Today, it is still the first and best choice for
developing web-based applications.
➢ Java is related to C++, which is a direct descendant of C. Much of the character of java is inherited from
these 2 languages. From C, java derives its syntax. Many of Java’s object oriented features were
influenced by C++.
➢ C is procedure-oriented programming language developed by Dennis Ritchie in the year 1972 at Bell
Labs.
➢ C++ is object-oriented programming language developed by Bjarne Stroustrup in the year 1979 at Bell
Labs.
➢ Java is general-purpose object-oriented programming language developed by James Gosling, Mike
Sheriden and Patrick Naughton in the year 1991 at Sun Microsystems. The Language was initially
called as “Oak”, but was renamed “Java” in 1995.
➢ The primary motivation of java language invention was the need for a platform-independent
(architecture neutral) language that could be used to create software to be embedded in various
consumer electronic devices, such as microwave ovens and remote controls. The second force that made
java very famous was it was used for developing web based applications (World Wide Web).
➢ Java provided security or protection by confining an applet to the java execution environment and not
allowing it access to other parts of the computer. An applet is a special kind of Java program that is
designed to be transmitted over the Internet and automatically executed by a Java-compatible web
browser.
➢ The key that allows Java to solve both the security and the portability problems just described is that
the output of a Java compiler is not executable code. Rather, it is bytecode. Bytecode is a highly
optimized set of instructions designed to be executed by the Java run-time system, which is called the
Java Virtual Machine (JVM). In essence, the original JVM was designed as an interpreter for bytecode.

Features of Java/Buzz words of java

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.

A list of most important features of Java language is given below.


1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic

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

Java is an object-oriented programming language. Everything in Java is an object. Object-oriented means we


organize our software as a combination of different types of objects that incorporates both data and behavior.

Object-oriented programming (OOPs) is a methodology that simplifies software development and


maintenance by providing some rules.

Basic concepts of OOPs are:

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

Robust simply means strong. Java is robust because:

• It uses strong memory management.


• There is a lack of pointers that avoids security problems.
• There is automatic garbage collection in java which runs on the Java Virtual Machine to get rid of
objects which are not being used by a Java application anymore.
• There are exception handling and the type checking mechanism in Java. All these points make Java
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).

❖ Dissecting the “Hello, World” Program

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.

Let’s examine this program


➢ A package is a set of related classes. It is a good idea to place each class in a package so you can group
related classes together and avoid conflicts when multiple classes have the same name. The full name
of our class is ch01.sec01.HelloWorld.
➢ The line starting with // is a single-line comment. All characters between // and the end of the line are
ignored by the compiler and are meant for human readers only.
➢ Java is an object-oriented language. In your program, you manipulate objects by having them do work.
Each object that you manipulate belongs to a specific class, and we say that the object is an instance of
that class. A class defines what an object’s state can be and what it can do. In java, all code is defined
inside classes. This program is made up of a single class HelloWorld.
The next line of code is shown here

public static void main(String args[ ])


{
➢ This line begins the main( ) method. As the comment preceding it suggests, this is the line at which the
program will begin executing. All Java applications begin execution by calling main( ). The public
keyword is an access specifier, which allows the programmer to control the visibility of class members.
When a class member is preceded by public, then that member may be accessed by code outside the
class in which it is declared. In this case, main( ) must be declared as public, since it must be called by
code outside of its class when the program is started. The keyword static allows main( ) to be called
without having to instantiate a particular instance of the class. This is necessary since main( ) is called
by the Java Virtual Machine before any objects are made. The keyword void simply tells the compiler
that main( ) does not return a value.
➢ Any information that you need to pass to a method is received by variables specified within the set of
parentheses that follow the name of the method. These variables are called parameters. If there are no
parameters required for a given method, you still need to include the empty parentheses. In main( ),
there is only one parameter, albeit a complicated one. String args[ ] declares a parameter named args,
which is an array of instances of the class String. Objects of type String store character strings. In this
case, args receives any command-line arguments present when the program is executed.
➢ A complex program will have dozens of classes, only one of which will need to have a main( ) function
to get things started.

The next line of code is shown here

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.

❖ Compiling and Running a Java Program

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

1. Signed Integer types


The signed integer types are for numbers without fractional parts. Negative values are allowed
Type Storage Requirement Range (inclusive)
byte 1 byte -128 to 127
short 2 bytes -32,768 to 32,767
int 4 bytes -2,147,483,648 to
2.147,483,647 (just over 2
billion)
long 8 bytes -9,223,372,036,854,775,808
to
9,223,372,036,854,775,807

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

3. The char type


➢ The char type describes “code units” in the UTF-16 character encoding used by Java.
Occasionally, you may encounter character literals, enclosed in single quotes. For example, 'J' is
a character literal with ASCII value 74.
➢ The special codes '\n', '\r', '\t', '\b'denote a line feed, carriage return, tab, and backspace. Use a
backslash to escape a single quote '\''and a backslash '\\'.
❖ Variables
1. Variable Declarations
• Java is a strongly typed language. Each variable can only hold values of a specific type.
When you declare a variable, you need to specify the type, the name, and an optional
initial value. For example,

int total = 0;

• You can declare multiple variables of the same type in a single statement:

int total = 0, count; // count is an uninitialized integer

• 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,

final int DAYS_PER_WEEK = 7;


By convention, uppercase letters are used for names of constants.
• You can also declare a constant outside a method, using the statickeyword:

public class Calendar


{
public static final int DAYS_PER_WEEK = 7;
...
}

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

<< >> >>> (arithmetic shift) Left

< > <= >= instanceof Left


== != Left
& (bitwise and) Left
^ (bitwise exclusive or) Left
| (bitwise or) Left
&& (logical and) Left
|| (logical or) Left
? : (conditional) Left
= += -= *= /= %= <<= >>= >>>= Right
&= ^= |=

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

amount = amount - 10;

Basic Arithmetic Operators

• Addition, subtraction, multiplication, and division are denoted by + - * /.


For example, 2 * n + 1means to multiply 2 and n and add 1.
You need to be careful with the /operator. If both operands are integer types, it denotes integer
division, discarding the remainder. For example, 17 / 5is 3, whereas 17.0 / 5is 3.4. An integer
division by zero gives rise to an exception which, if not caught, will terminate your program.
• A floating-point division by zero yields an infinite value or NaN (Not a Number) without
causing an exception.
• The % operator yields the remainder. For example, 17 % 5 is 2, the amount that remains
from 17 after subtracting 15 (the largest integer multiple of 5 that “fits” into 17). If the
remainder of a % b is zero, then a is an integer multiple of b.

• Java has increment and decrement operators:

n++; // Adds one to n

n--; // Subtracts one from n

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.

Number type Conversions


When an operator combines operands of different number types, the numbers are converted to
a common type before they are combined. Conversion occurs in this order:
1. If either of the operands is of type double, the other one is converted to double.
2. If either of the operands is of type float, the other one is converted to float.
3. If either of the operands is of type long, the other one is converted to long.
4. Otherwise, both operands are converted to int.
• For example, if you compute 3.14 + 42, the second operand is converted to, and then the sum is
computed, yielding 45.14.
• If you compute 'J' + 1, the charvalue 'J'is converted to the intvalue 74, and the result is the int
value 75. Read on to find out how to convert that value back to a char.
• When you assign a value of a numeric type to a variable, or pass it as an argument to a method, and
the types don't match, the value must be converted.
• For example, in the assignment

double x = 42;

the value 42 is converted from int to double.

In Java, conversion is always legal if there is no loss of information:


• From byte to short, int, long, or double
• From short and char to int, long, or double
• From int to long or double
Conversion from an integer type to a floating-point type is always legal.

• 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;

In this case, the fractional part is discarded, and n is set to 3.


• If you want to round to the nearest integer instead, use the Math.roundmethod. That method returns a
long. If you know the answer fits into an int, call

int n = (int) Math.round(x);

In our example, where xis 3.75, nis set to 4.


To convert an integer type to another one with fewer bytes, also use a cast:

int n = 1;

char next = (char)('J' + n); // Converts 75 to 'K'

Relational and Logical Operators


• The ==and !=operators test for equality. For example, n != 0is truewhen nis not zero. There are
also the usual <(less than), >(greater than), <=(less than or equal), and >=(greater than or equal)
operators.
• You can combine expressions of type booleanwith the &&(and), ||(or), and !not) operators.
For example,

<= n && n < length

is trueif nlies between zero (inclusive) and length(exclusive).


• If the first condition is false, the second condition is not evaluated. This “short circuit”
evaluation is useful when the second condition could cause an error.
• Finally, the conditional operator takes three operands: a condition and two values. The
result is the first of the values if the condition is true, the second otherwise. For example,

time < 12 ? "am" : "pm"

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);

You can also construct a BigIntegerfrom a string of digits:

BigInteger k = new BigInteger("9876543210123456789");

• There are predefined constants BigInteger.ZERO, BigInteger.ONE, BigInteger.TWO, and


BigInteger.TEN.
• Java does not permit the use of operators with objects, so you must use method calls to work
with big numbers.

• The result of the floating-point subtraction 2.0 - 1.1 is 0.8999999999999999. The


BigDecimalclass can compute the result accurately. The call BigDecimal.valueOf(n, e)
returns a BigDecimalinstance with value n× 10–e.

The result of

BigDecimal.valueOf(2, 0).subtract(BigDecimal.valueOf(11, 1))

is exactly 0.9.

❖ Strings
A string is a sequence of characters. In Java, a string can contain any Unicode characters.

1. String Concatenation

Java String concat


The java string concat() method combines specified string at the end of this string. It returns
combined string. It is like appending another string.

Java String concat() method example program

public class ConcatExample{


public static void main(String args[]){
String s1="java string";
s1.concat("is immutable");
System.out.println(s1);
s1=s1.concat(" is immutable so assign it explicitly");
System.out.println(s1);
}}

Output:
java string
java string is immutable so assign it explicitly
programming example 2:

public class ConcatExample2 {


public static void main(String[] args) {
String str1 = "Hello";
String str2 = "Reva";
String str3 = "University";
// Concatenating one string
String str4 = str1.concat(str2);
System.out.println(str4);
// Concatenating multiple strings
String str5 = str1.concat(str2).concat(str3);
System.out.println(str5);
}
}
Output:
HelloReva
HelloRevaUniversity

Use the +operator to concatenate two strings. For example,

String location = "Java";

String greeting = "Hello " + location;

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.

int age = 42;


String output = age + " years";

Now output is "42years".


If you mix concatenation and addition, then you may get unexpected results. For example,

"Next year, you will be " + age + 1 // Error

first concatenates ageand then 1. The result is "Next year, you will be 421". In such
cases, use parentheses:

"Next year, you will be " + (age + 1) // OK

To combine several strings, separated with a delimiter, use the joinmethod:

String names = String.join(", ", "Peter", "Paul", "Mary");


// Sets names to "Peter, Paul,Mary"
The first argument is the separator string, followed by the strings you want to join. There can
be any number of them, or you can supply an array of strings.
It is somewhat inefficient to concatenate a large number of strings if all you need is the final
result. In that case, use a StringBuilderinstead:

StringBuilder builder = new StringBuilder(); while (more strings) {


builder.append(next string);
}
String result = builder.toString();

2. Substrings

The java string substring() method returns a part of the string.

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.

To take strings apart, use the substringmethod. For example,

String greeting = "Hello, World!";


String location = greeting. substring(7, 12); // Sets location to
"World"

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.

String names = "Peter, Paul, Mary"; String[] result =


names.split(", ");

// An array of three strings ["Peter", "Paul", "Mary"]

The separator can be any regular expression . For example,


input.split("\\s+")splits inputat white space.

substring() method example program

public class SubstringExample{


public static void main(String args[]){
String s1="revacse";
System.out.println(s1.substring(2,4));//returns va
System.out.println(s1.substring(2));//returns vacse
}}

Output:
va
vacse

3. String Comparison

String equals() method

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.

Java String equals() method example

public class EqualsExample{


public static void main(String args[]){
String s1="Reva";
String s2="Reva";
String s3="REVA";
String s4="python";
String s5=new string(“Reva”);
System.out.println(s1.equals(s2));//true because content and case is
same
System.out.println(s1.equals(s3));//false because case is not same
System.out.println(s1.equals(s4));//false because content is not sam
e
System.out.println(s1.equals(s5);//false s5 refers to instance
created in non pool

}}

output
true
false
false

String compare by compareTo() method

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.

Suppose s1 and s2 are two string variables. If:

• 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

String compareToIgnoreCase() Method

This method compares two strings lexicographically, ignoring case differences.

Syntax

Here is the syntax of this method −

int compareToIgnoreCase(String str)

• str − the String to be compared.

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

public class Test {

public static void main(String args[]) {


String str1 = "Strings are immutable";
String str2 = "Strings are immutable";
String str3 = "Integers are not immutable";

int result = str1.compareToIgnoreCase( str2 );


System.out.println(result);

result = str2.compareToIgnoreCase( str3 );


System.out.println(result);

result = str3.compareToIgnoreCase( str1 );


System.out.println(result);
}
}
Output
0
10
-10

4. String toLowerCase() Method

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:

public String toLowerCase()

Return Value

• It returns the String, converted to lowercase.

Example program

import java.io.*;
public class Test {

public static void main(String args[]) {


String Str = new String("Welcome to REVA");

System.out.print("Return Value :");


System.out.println(Str.toLowerCase());
}
}
Output
Return Value :welcome to reva

5. String toUpperCase() Method

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

public String toUpperCase()

Return Value

• It returns the String, converted to uppercase.

Example program

import java.io.*;
public class Test {

public static void main(String args[]) {


String Str = new String("Welcome to reva");

System.out.print("Return Value :" );


System.out.println(Str.toUpperCase() );
}
}
Output
Return Value :WELCOME TO REVA

6. Conversion Between Numbers and Strings


To turn an integer into a string, call the static Integer.toStringmethod:

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):

String str2 = Integer.toString(n, 2); // Sets str2 to "101010"

Conversely, to convert a string containing an integer to the number, use the


Integer.parseIntmethod:

String str = "101010";


int n = Integer.parseInt(str); // Sets nto 101010

You can also specify a radix:

int n2 = Integer.parseInt(str, 2); // Sets n2 to 42

For floating-point numbers, use Double.toStringand


Double.parseDouble:

String str = Double.toString(3.14); // Sets str to "3.14" double x =


Double.parseDouble(str); // Sets x to 3.14.
int n2 = Integer.parseInt(str, 2); // Sets n2 to 42

For floating-point numbers, use Double.toStringand


Double.parseDouble:

String str = Double.toString(3.14); // Sets str to "3.14" double x =


Double.parseDouble(str); // Sets x to 3.14.

7. The String API


Useful String methods

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)

String Returns a string that is obtained by replacing all occurrences


replace(CharSequence of oldStringwith newString.
oldString,
CharSequence
newString)

String toUpperCase() Returns a string consisting of all characters of the original


String toLowerCase() string converted to upper- or lowercase.

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()

returns a new string "HELLO, WORLD!"without changing greeting.


Also note that some methods have parameters of type CharSequence. This is a common supertype of
String, StringBuilder, and other sequences of characters.

❖ Input and Output


To make our sample programs more interesting, they should be able to interact with the user. In
the following sections, you will see how to read terminal input and how to produce formatted
output.

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:

Scanner in = new Scanner(System.in);

The nextLinemethod reads a line of input.

System.out.println("What is your name?"); String name =


in.nextLine();

Here, it makes sense to use the nextLinemethod because the input might contain spaces. To read a single
word (delimited by whitespace), call

String firstName = in.next();

To read an integer, use the nextIntmethod.

System.out.println("How old are you?"); int age = in.nextInt();

Similarly, the nextDoublemethod reads the next floating-point number.


You can use the hasNextLine, hasNext, hasNextInt, and hasNextDoublemethods to check that there
is another line, word, integer, or floating-point number available.

if (in.hasNextInt()) {

int age = in.nextInt();

...
}

The Scannerclass is located in the java.utilpackage. In order to use the class, add the line

import java.util.Scanner

to the top of your program file.

Example program for nextLine() method.

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:

Enter your name: sonoo jaiswal


Name is: sonoo jaiswal

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:

Boolean Result: true


String: Hello, This is REVA.
-------Enter Your Details---------
Enter your name: Aryan
Name: Aryan
Enter your age: 23
Age: 23
Enter your salary: 50000
Salary: 50000.0

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:

System.out.print("Your age: "); // Not println int age = in.nextInt();

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:

System.out.printf("%8.2f", 1000.0 / 3.0);

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

You can supply multiple parameters to printf. For example

System.out.printf("Hello, %s. Next year, you'll be %d.\n", name, age);

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

Character Purpose Example


d Decimal integer 159
x or X Hexadecimal integer 9f or 9F
o Octal integer 237

f Fixed floating-point 15.9


e or E Exponential floating-point 1.59e+01 or 1.59E+01
General floating-point: e/E if the exponent is greater 15.9000 at the default
g or G
than the precision or < –4, f/F otherwise precision of 6, 2e+01 at
precision 1
0x1.fccdp3 or
a or A Hexadecimal floating-point
0X1.FCCDP3

s or S String Java or JAVA

c or C Character j or J

b or B boolean false or FALSE


h or H Hash code (see Chapter 4) 42628b2 or 42628B2
Date and time (obsolete; see Chapter 12 instead)
t or T —
% The percent symbol %
N The platform-dependent line separator —

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

System.out.printf("%,+.2f", 100000.0 / 3.0);

Flags for Formatted Output


Flag Purpose Example
+ Prints sign for positive and negative numbers +3333.33
space Adds a space before positive numbers _3333.33
- Left-justifies field 3333.33
0 Adds leading zeroes 003333.33
( Encloses negative values in parentheses (3333.33)
, Uses group separators 3,333.33
# (for f
format) Always includes a decimal point 3333.

# (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) {

double average = sum / count; System.out.println(average);

You can have an elsebranch that runs if the condition is not fulfilled.
if (count > 0) {

double average = sum / count; System.out.println(average);

} else {

System.out.println(0);

The statement in the elsebranch may be another ifstatement:


if (count > 0)

double average = sum / count; System.out.println(average);

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:

output = "None"; break;

case 1:

output = "One"; break;

case 2:

case 3:

case 4:

case 5:

output = Integer.toString(count); break;

default:

output = "Many"; break;

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.

Random generator = new Random();

This call gets a random integer between 0and 9:

int next = generator.nextInt(10);

Here is the loop for forming the sum:

while (sum < target) {


int next = generator.nextInt(10); sum += next;

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

next = generator.nextInt(10); count++;

} while (next != target);

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:

for (int i = 1; i <= 20; i++)

int next = generator.nextInt(10); sum += next;

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;

while (i <= 20) {

int next = generator.nextInt(10); sum += next;

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:

for (int i = 1; i < target; i *= 2) { System.out.println(i);

Instead of declaring a variable in the header of the forloop, you can initialize an existing variable:

for (i = 1; i <= target; i++) // Uses existing variable i

You can declare or initialize multiple variables and provide multiple updates, separated by commas. For
example,

for (int i = 0, j = n - 1; i < j; i++, j--)

If no initialization or update is required, leave them blank. If you omit the condition, it is deemed to always
be true.

for (;;) // An infinite loop

You will see in the next section how you can break out of such a loop.

3. Breaking and Continuing


If you want to exit a loop in the middle, you can use the break statement. For example, suppose you want
to process words until the user enters the letter Q. Here is a solution that uses a boolean variable to control
the loop:

boolean done = false;

while (!done)

String input = in.next();

if ("Q".equals(input))

done = true;

else

Process input

}
This loop carries out the same task with a breakstatement:

while (true)

String input = in.next();

if (input.equals("Q")) break; // Exits loop

Process input

// breakjumps here

When the breakstatement is reached, the loop is exited immediately.


The continuestatement is similar to break, but instead of jumping to the end of the loop, it jumps to the end
of the current loop iteration. You might use it to skip unwanted inputs like this:

while (in.hasNextInt())

{ int input = in.nextInt();

if (input < 0) continue; // Jumps to test of in.hasNextInt()

Process input

In a forloop, the continuestatement jumps to the next update statement:

for (int i = 1; i <= target; i++)

{ int input = in.nextInt();

if (n < 0) continue; // Jumps to i++

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

...

if (...) break outer;

...

...

// Labeled breakjumps here

The label can be any name.

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: {

...

if (...) break exit;

...

// Labeled breakjumps here

There is also a labeled continuestatement that jumps to the next iteration of a labeled loop

4. Local Variable Scope


Now that you have seen examples of nested blocks, it is a good idea to go over the rules for variable scope.
A local variable is any variable that is declared in a method, including the method's parameter variables.
The scope of a variable is the part of the program where you can access the variable. The scope of a local
variable extends from the point where it is declared to the end of the enclosing block.

while (...)

System.out.println(...);

String input = in.next(); // Scope of input starts here


...

// Scope of inputends here

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.

public static void main(String[] args) { // Scope of args starts here

...

// Scope of argsends here

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

next = generator.nextInt(10); count++;

} while (next != target);

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.

for (int i = 0; i < n; i++)

{ // i is in scope for the test and update

...

// inot defined here

If you need the value of iafter the loop, declare the variable outside:

int i;

for (i = 0; !found && i < n; i++)

{
...

// istill available

In Java, you cannot have local variables with the same name in overlapping scopes.

int i = 0; while (...)

String i = in.next(); // Error to declare another variable i

...

However, if the scopes do not overlap, you can reuse the same variable name:

for (int i = 0; i < n / 2; i++) { ... }

for (int i = n / 2; i < n; i++) { ... } // OK to redefine i

4. Arrays and Array Lists


Arrays are a fundamental programming construct for collecting multiple items of the same type. Java has array
types built into the language, and it also supplies an
ArrayListclass for arrays that grow and shrink on demand. The ArrayList
class is a part of a larger collections framework.

1. Working with Arrays


For every type, there is a corresponding array type. An array of integers has type int[], an array of String
objects has type String[], and so on. Here is a variable that can hold an array of strings:

String[] names;

The variable isn't yet initialized. Let's initialize it with a new array. For that, we need the new operator:

names = new String[100];

Of course, you can combine these two statements:

String[] names = new String[100];

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]);
}
}

Multidimensional Array in Java


In such case, data is stored in row and column based index (also known as matrix form).

Syntax to Declare Multidimensional Array in Java

dataType[][] arrayRefVar; (or)

Example to instantiate Multidimensional Array in Java

int[][] arr=new int[3][3];//3 row and 3 column

Example to initialize Multidimensional Array in Java

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;

//Java Program to illustrate the use of multidimensional array

class Testarray3{

public static void main(String args[]){


//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}}

Output:

1 2 3
2 4 5
4 4 5

Jagged /ragged Array in Java


If we are creating odd number of columns in a 2D array, it is known as a jagged array. In other words, it is an
array of arrays with different number of columns.

//Java Program to illustrate the jagged array


class TestJaggedArray{
public static void main(String[] args){
//declaring a 2D array with odd columns
int arr[][] = new int[3][];
arr[0] = new int[3];
arr[1] = new int[4];
arr[2] = new int[2];
//initializing a jagged array
int count = 0;
for (int i=0; i<arr.length; i++)
for(int j=0; j<arr[i].length; j++)
arr[i][j] = count++;

//printing the data of a jagged array


for (int i=0; i<arr.length; i++){
for (int j=0; j<arr[i].length; j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();//new line
}
}
}

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:

int[] primes = { 2, 3, 5, 7, 11, 13 };

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:

String[] authors = { "James


Gosling",

"Bill Joy", "Guy


Steele",

// 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:

primes = new int[] { 17, 19, 23, 29, 31 };

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:

friends = new ArrayList<>();

// 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:

ArrayList<String> friends = new ArrayList<>(List.of("Peter", "Paul"));

The List.ofmethod yields an unmodifiable list of the given elements which you then use to construct an
ArrayList.

You can add and remove elements anywhere in the ArrayList.

friends.remove(1);

friends.add(0, "Paul"); // Adds before index 0

To access elements, use method calls, not the [] syntax. The getmethod reads an element, and the set
method replaces an element with another:

String first = friends.get(0); friends.set(1, "Mary");

The sizemethod yields the current size of the list. Use the following loop to traverse all elements:

for (int i = 0; i < friends.size(); i++) { System.out.println(friends.get(i));

4. Wrapper Classes for Primitive Types


There is one unfortunate limitation of generic classes: You cannot use primitive types as type parameters.
For example, an ArrayList<int> is illegal. The remedy is to use a wrapper class. For each primitive type,
there is a corresponding wrapper class: Integer, Byte, Short, Long, Character, Float, Double, and Boolean.
To collect integers, use an ArrayList<Integer>:

ArrayList<Integer> numbers = new ArrayList<>(); numbers.add(42);

int first = numbers.get(0);

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.

5. The Enhanced forLoop


Very often, you want to visit all elements of an array. For example, here is how you compute the sum of
all elements in an array of numbers:

int sum = 0;

for (int i = 0; i < numbers.length; i++)

sum += numbers[i];

As this loop is so common, there is a convenient shortcut, called the enhanced for
loop:

int sum = 0;

for (int n : numbers)

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

for (String name : friends) { System.out.println(name);

}
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

Figure 1 Two variables referencing the same array

int[] numbers = primes;

numbers[5] = 42; // Now primes[5]is also 42

If you don't want this sharing, you need to make a copy of the array. Use the static
Arrays.copyOfmethod.

int[] copiedPrimes = Arrays.copyOf(primes, primes.length);

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:

ArrayList<String> people = friends;

people.set(0, "Mary"); // Now friends.get(0) is also "Mary"

To copy an array list, construct a new array list from the existing one:

ArrayList<String> copiedFriends = new ArrayList<>(friends);

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:

String[] names = ...;

ArrayList<String> friends = new ArrayList<>(List.of(names));


You can also copy an array list into an array. For depressing reasons of backward compatibility that I will
explain in Chapter 6, you must supply an array of the correct type.

String[] names = friends.toArray(new String[0]);

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.fill(numbers, 0); // int[]array

Collections.fill(friends, ""); // ArrayList<String>

To sort an array or array list, use the sortmethod:

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));

// Prints [2, 3, 5, 7, 11, 13]

Array lists have a toStringmethod that yields the same representation.

String elements = friends.toString();

// Sets elements to "[Peter, Paul,Mary]"

For printing, you don't even need to call it—the printlnmethod takes care of that.

System.out.println(friends);

// Calls friends.toString()and prints the result

There are a couple of useful algorithms for array lists that have no counterpart for arrays.

Collections.reverse(names); // Reverses the elements

Collections.shuffle(names); // Randomly shuffles the elements


8. Command-Line Arguments
The java command-line argument is an argument i.e. passed at the time of running the java program.
The arguments passed from the console can be received in the java program and it can be used as an
input.
A command-line argument is an information that directly follows the program's name on the command
line when it is executed. To access the command-line arguments inside a Java program is quite easy.
They are stored as strings in the String array passed to main( ).

As you have already seen, the mainmethod of every Java program has a parameter that is a string array:

public static void main(String[] args)

When a program is executed, this parameter is set to the arguments specified on the command line.
For example, consider this program:

public class Greeting {

public static void main(String[] args) { for (int i = 0; i < args.length;


i++) {

String arg = args[i];

if (arg.equals("-h")) arg = "Hello";

else if (arg.equals("-g")) arg = "Goodbye"; System.out.println(arg);

If the program is called as

java Greeting -g cruel world

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}

};

Technically, this is a one-dimensional array of int []arrays—see Figure 2


Figure 2 A two-dimensional array

To access an element, use two bracket pairs:

int element = square[1][2]; // Sets elementto 11

The first index selects the row array square[1]. The second index picks the element from that row.
You can even swap rows:

int[] temp = square[0]; square[0] = square[1];


square[1] = temp;
If you do not provide an initial value, you must use the new operator and specify the
number of rows and columns.

int[][] square = new int[4][4]; // First rows, then columns

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

...

First construct an array of nrows:

int[][] triangle = new int[n][];

Then construct each row in a loop and fill it.

for (int i = 0; i < n; i++) { triangle[i] = new


int[i + 1]; triangle[i][0] = 1;

triangle[i][i] = 1;

for (int j = 1; j < i; j++) {

triangle[i][j] = triangle[i - 1][j - 1] + triangle[i - 1]

[j];

To traverse a two-dimensional array, you need two loops, one for the rows and one for the
columns:

for (int r = 0; r < triangle.length; r++) {

for (int c = 0; c < triangle[r].length; c++) { System.out.printf("%4d",


triangle[r][c]);

}
System.out.println();

You can also use two enhanced forloops:

for (int[] row :


triangle) { for
(int element : row) {

System.out.printf("%4d", element);

System.out.println();

These loops work for square arrays as well as arrays with varying row lengths.

You might also like