0% found this document useful (0 votes)
24 views8 pages

Chapter One Part II

programming pdf java

Uploaded by

yeansiraab
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views8 pages

Chapter One Part II

programming pdf java

Uploaded by

yeansiraab
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Chapter One-Part-II

Java basics

Listing 1.1. Welcome.java

public class Welcome {

public static void main(String[]args){

System.out.println("welcome to java");
}
}
1. Anatomy of a Java Program
The application program in Listing 1.1 has the following components:
 Comments
 Reserved words
 Modifiers
 Statements
 Blocks
 Classes
 Methods
 The main method
To build a program, you need to understand these basic elements. They are explained in the
sections that follow.
Comments
Comment tells what the program is and how the program is constructed. Comments help
programmers to communicate and understand the program. Comments are not programming
statements and thus are ignored by the compiler. In Java, comments are preceded by two slashes
(//) on a line, called a line comment, or enclosed between /* and */ on one or several lines, called
a paragraph comment. When the compiler sees //, it ignores all text after // on the same line.
When it sees /*, it scans for the next */ and ignores any text between /* and */.
Here are examples of the two types of comments:
// This application program prints Welcome to Java!
/* This application program prints Welcome to Java! */
/* This application program
prints Welcome to Java! */
Reserved Words
Reserved words, or keywords, are words that have a specific meaning to the compiler and cannot
be used for other purposes in the program. For example, when the compiler sees the word class,
it understands that the word after class is the name for the class. Other reserved words in Listing
1.1 are public, static, and void. Their use will be introduced later in next chapter.
Tip Because Java is case-sensitive, public is a reserved word, but Public is not.
Nonetheless, for clarity and readability, it would be best to avoid using
reserved words in other forms.
Modifiers
Java uses certain reserved words called modifiers that specify the properties of the data, methods,
and classes and how they can be used. Examples of modifiers are public and static. Other
modifiers are private, final, abstract, and protected. A public datum, method, or class can be
accessed by other classes. A private datum or method cannot be accessed by other classes.
Statements
A statement represents an action or a sequence of actions. The statement
System.out.println("Welcome to Java!"); in the program in Listing 1.1 is a statement to display
the greeting "Welcome to Java!". Every statement in Java ends with a semicolon (;).
Blocks
The braces in the program form a block that groups the components of the program. In Java, each
block begins with an opening brace ({) and ends with a closing brace (}). Every class has a class
block that groups the data and methods of the class. Every method has a method block that
groups the statements in the method. Blocks can be nested, meaning that one block can be placed
within another.
Classes
The class is the essential Java construct. To program in Java, you must understand classes and be
able to write and use them. The mystery of classes will be unveiled throughout the course. For
now, though, it is enough to know that a program is defined by using one or more classes.
Declaring a class
Every java program consists of at least one class that you (the programmer) define. “class”
keyword followed by the class name (identifier). Just as every entity in the real world has a
name, so you need to choose names for the things you will refer to in your programs.
Programming languages use special symbols called identifiers to name such programming
entities as variables, constants, methods, classes, and packages. Here are the rules for naming
identifiers:
 An identifier is a sequence of characters that consists of letters, digits, underscores (_),
and dollar signs ($).
 An identifier must start with a letter, an underscore (_), or a dollar sign ($). It cannot start
with a digit.
 An identifier cannot be a reserved word. ("Java Keywords,")
 An identifier cannot be true, false, or null.
 An identifier can be of any length.
For example, $2, ComputeArea, area, radius, and showMessageDialog are legal identifiers,
whereas 2A and d+4 are illegal identifiers because they do not follow the rules. The Java
compiler detects illegal identifiers and reports syntax errors.

Note Since Java is case-sensitive, X and x are different identifiers. Meth


ods
What is System.out.println? System.out is known as the standard output object. println is a
method in the object, which consists of a collection of statements that perform a sequence of
operations to display a message to the standard output device. If you run the program from the
command window, the output from the System.out.println is displayed in the command window.
The method can be used even without fully understanding the details of how it works. It is used
by invoking a statement with a string argument. The string argument is enclosed in parentheses.
In this case, the argument is "Welcome to Java!" You can call the same println method with a
different argument to print a different message.
The main Method
Every Java application must have a user-declared main method that defines where the program
execution begins. The JVM executes the application by invoking the main method. The main
method looks like this:
public static void main(String[] args) {
// Statements;
}
2. Getting Input from the Console
Java uses System.out to refer to the standard output device, and System.in to the standard input
device. By default, the output device is the console, and the input device is the keyboard. To
perform console output, you simply use the println method to display a primitive value or a
string to the console. Console input is not directly supported in Java, but you can use the Scanner
class to create an object to read input from System.in, as follows:
Scanner scanner = new Scanner(System.in);
Scanner is a new class in JDK. The syntax new Scanner(System.in) creates an object of the
Scanner type. The syntax Scanner scanner declares that scanner is a variable whose type is
Scanner. The whole line Scanner scanner = new Scanner(System.in) creates a Scanner object and
assigns its reference to the variable scanner. An object may contain methods. Invoking a method
on an object is to ask the object to perform a task. A Scanner object contains the following
methods for reading an input:
 next(): reading a string. A string is delimited by spaces.
 nextByte(): reading an integer of the byte type.
 nextShort(): reading an integer of the short type.
 nextInt(): reading an integer of the int type.
 nextLong(): reading an integer of the long type.
 nextFloat(): reading a number of the float type.
 nextDouble(): reading a number of the double type.
For example, the following statements prompt the user to enter a double value from the console.
System.out.print("Enter a double value: ");
Scanner scanner = new Scanner(System.in);
double d = scanner.nextDouble();

Note The print method is identical to the println method except that println moves
the cursor to the next line after displaying the string, but print does not
advance the cursor to the next line when completed.

Listing 1.2 gives an example that reads various types of data from the console using the Scanner
class.
Listing 1.2 TestScanner.java
1 import java.util.Scanner; // Scanner is in java.util
2
3 public class TestScanner {
4 public static void main(String args[]) {
5 // Create a Scanner
6 Scanner scanner = new Scanner(System.in);
7
8 // Prompt the user to enter an integer
9 System.out.print("Enter an integer: ");
10 int intValue = scanner.nextInt();
11 System.out.println("You entered the integer " + intValue);
12
13 // Prompt the user to enter a double value
14 System.out.print("Enter a double value: ");
15 double doubleValue = scanner.nextDouble();
16 System.out.println("You entered the double value "
17 + doubleValue);
18
19 // Prompt the user to enter a string
20 System.out.print("Enter a string without space: ");
21 String string = scanner.next();
22 System.out.println("You entered the string " + string);
23 }
24 }

Listing 2.10. ComputeLoanAlternative.java


1 import java.util.Scanner;
2
3 public class ComputeLoanAlternative {
4 /** Main method */
5 public static void main(String[] args) {
6 // Create a scanner for input
7 Scanner input = new Scanner(System.in);
8
9 // Enter yearly interest rate
10 System.out.print("Enter yearly interest rate, for example 8.25: ");
11 double annualInterestRate = input.nextDouble();
12
13 // Obtain monthly interest rate
14 double monthlyInterestRate = annualInterestRate / 1200;
15
16 // Enter number of years
17 System.out.print(
18 "Enter number of years as an integer, \nfor example 5: ");
19 int numberOfYears = input.nextInt();
20
21 // Enter loan amount
22 System.out.print("Enter loan amount, for example 120000.95: ");
23 double loanAmount = input.nextDouble();
24
25 // Calculate payment
26 double monthlyPayment = loanAmount * monthlyInterestRate / (1
27 – 1 / Math.pow(1 + monthlyInterestRate, numberOfYears * 12));
28 double totalPayment = monthlyPayment * numberOfYears * 12;
29
30 // Format to keep two digits after the decimal point
31 monthlyPayment = (int)(monthlyPayment * 100) / 100.0;
32 totalPayment = (int)(totalPayment * 100) / 100.0;
33
34 // Display results
35 System.out.println("The monthly payment is " + monthlyPayment);
36 System.out.println("The total payment is " + totalPayment);
37 }
38

3. Numeric Data Types and Operations


Every data type has a range of values. The compiler allocates memory space to store each
variable or constant according to its data type. Java provides eight primitive data types for
numeric values, characters, and Boolean values. In this section, numeric data types are
introduced.
Table 1.1 lists the six numeric data types, their ranges, and their storage sizes.

Table 1.1. Numeric Data Types

Name Range Storage Size

Byte -27 (-128) to 27 - 1(127) 8-bit signed

Short -215 (-32768) to 215 - 1(32767) 16-bit signed

Int -231 (-2147483648) to 231 - 1(2147483647) 32-bit signed

Long -263 to 263 – 1 64-bit signed

(i.e., -9223372036854775808 to
9223372036854775807)

Float Negative range: -3.4028235E + 38 to -1.4E-45 32-bit IEEE


754
Positive range: 1.4E-45 to 3.4028235E + 38

Double Negative range: -1.7976931348623157E+308 to - 64-bit IEEE


4.9E-324 754

Positive range: 4.9E-324 to


1.7976931348623157E+308
Java uses four types for integers: byte, short, int, and long. Choose the type that is most
appropriate for your variable. For example, if you know an integer stored in a variable is within
a range of byte, declare the variable as a byte.
Java uses two types for floating-point numbers: float and double. The double type is twice as big
as float. So, the double is known as double precision, while float is known as single precision.
Normally, you should use the double type because it is more accurate than the float type.
Note: The float and double types are used to represent numbers with a decimal point.
Why are they called floating-point numbers? These numbers are stored into
scientific notation. When a number such as 50.534 is converted into scientific
notation such as 5.053e1, its decimal point is moved (i.e., floated) to a new
position.
4. Arithmetic Expressions
Writing numeric expressions in Java involves a straightforward translation of an arithmetic
expression using Java operators. For example, the arithmetic expression can be translated into a
Java expression as:
(3 + 4 * x) / 5 – 10 * (y - 5) * (a + b + c) / x +
9 * (4 / x + (9 + x) / y)
The numeric operators in a Java expression are applied the same way as in an arithmetic
expression. Operators contained within pairs of parentheses are evaluated first. Parentheses can
be nested, in which case the expression in the inner parentheses is evaluated first. Multiplication,
division, and remainder operators are applied next. If an expression contains several
multiplication, division, and remainder operators, they are applied from left to right. Addition
and subtraction operators are applied last. If an expression contains several addition and
subtraction operators, they are applied from left to right.
Listing 1.3 gives a program that converts a Fahrenheit degree to Celsius using the formula
celsius = (fahrenheit - 32).
Listing 1.3. FahrenheitToCelsius.java
1 public class FahrenheitToCelsius {
2 public static void main(String[] args) {
3 double fahrenheit = 100; // Say 100;
4 double celsius = (5.0 / 9) * (fahrenheit - 32);
5 System.out.println("Fahrenheit " + fahrenheit + " is " +
6 celsius + " in Celsius");
7 }
8}
Be careful when applying division. Division of two integers yields an integer in Java. is
translated to 5.0 / 9 instead of 5 / 9 in line 4, because 5 / 9 yields 0 in Java.
The increment operator ++ and the decrement operator – – can be applied to all integer and
floating-point types. These operators are often used in loop statements. A loop statement is a
structure that controls how many times an operation or a sequence of operations is performed in
succession.
Note Like the assignment operator (=), the operators (+=, -=, *=, /=, %=, ++, and ——)
can be used to form an assignment statement as well as an expression. For example,
in the following code, x = 2 is a statement in the first line and is an expression in the
second line.
x = 2; // statement
System.out.println(x += 2); // expression If a statement is used as an expression, it is
called an expression statement.
5. Numeric Type Conversions(Casting)
Sometimes it is necessary to mix numeric values of different types in a computation. Consider
the following statements:
byte i = 100;
long k = i * 3 + 4;
double d = i * 3.1 + k / 2;
Are these statements correct? Java allows binary operations on values of different types. When
performing a binary operation involving two operands of different types, Java automatically
converts the operand based on the following rules:
1. If one of the operands is double, the other is converted into double.
2. Otherwise, if one of the operands is float, the other is converted into float.
3. Otherwise, if one of the operands is long, the other is converted into long.
4. Otherwise, both operands are converted into int.
For example, the result of 1 / 2 is 0, because both operands are int values. The result of 1.0 / 2 is
0.5, because 1.0 is double and 2 is converted to 2.0.
You can always assign a value to a numeric variable whose type supports a larger range of
values; thus, for instance, you can assign a long value to a float variable. You cannot, however,
assign a value to a variable of a type with smaller range unless you use type casting. Casting is
an operation that converts a value of one data type into a value of another data type. Casting a
variable of a type with a small range to a variable of a type with a larger range is known as
widening a type. Casting a variable of a type with a large range to a variable of a type with a
smaller range is known as narrowing a type. Widening a type can be performed automatically
without explicit casting. Narrowing a type must be performed explicitly.
The syntax for casting gives the target type in parentheses, followed by the variable's name or
the value to be cast. For example:
float f = (float)10.1;
int i = (int)f;
In the first line, the double value 10.1 is cast into float. In the second line, i has a value of 10;
the fractional part in f is truncated.
Caution Casting is necessary if you are assigning a value to a variable of a smaller type
range, such as assigning a double value to an int variable. A compilation error will
occur if casting is not used in situations of this kind. Be careful when using
casting. Lost information might lead to inaccurate results.
Note Casting does not change the variable being cast. For example, d is not
changed after casting in the following code:
double d = 4.5;
int i = (int)d; // d is not changed

Note To assign a variable of the int type to a variable of the short or byte type,
explicit casting must be used. For example, the following statements have a
syntax error:
int i = 1;
byte b = i; // Error because explicit casting is required

Listing 1.4 gives a program that displays the sales tax with two digits after the decimal point.
Listing 1.4. SalesTax.java
1 public class SalesTax {
2 public static void main(String[] args) {
3 double purchaseAmount = 197.55;
4 double tax = purchaseAmount * 0.06;
5 System.out.println((int)(tax * 100) / 100.0);
6 }
7}

Variable purchaseAmount is 197.55 (line 3). The sales tax is 6% of the purchase, so the tax is
evaluated as 11.853 (line 4). The statement in line 5 displays the tax 11.85 with two digits after
the decimal point. Note that (int)(tax * 100) is 1185, so (int)(tax * 100) / 100.0 is 11.85.
6. The String Type
The char type only represents one character. To represent a string of characters, use the data
type called String. For example, the following code declares the message to be a string that has
an initial value of "Welcome to Java".
String message = "Welcome to Java";
String is actually a predefined class in the Java library just like the System class and
JOptionPane class. The String type is not a primitive type. It is known as a reference type. Any
Java class can be used as a reference type for a variable. As first shown in Listing 2.1, two
strings can be concatenated. The plus sign (+) is the concatenation operator if one of the
operands is a string. If one of the operands is a non-string (e.g., a number), the non-string value
is converted into a string and concatenated with the other string. Here are some examples:
// Three strings are concatenated
String message = "Welcome" + "to" + "Java";

// String Chapter is concatenated with number 2


String s = "Chapter" + 2; // s becomes Chapter2

// String Supplement is concatenated with character B


String s1 = "Supplement" + 'B'; // s becomes SupplementB
If neither of the operands is a string, the plus sign (+) is the addition operator that adds two
numbers.
The shorthand += operator can also be used for string concatenation. For example, the following
code appends the string "and Java is fun" with the string "Welcome to Java" in message.
message += " and Java is fun"; So the new message is "Welcome to Java and Java is fun".
Suppose that i = 1 and j = 2, what is the output of the following statement?
System.out.println("i + j is " + i + j);
The output is "i + j is 12" because "i + j is " is concatenated with the value of i first. To force i +
j to be executed first, enclose i + j in the parentheses, as follows: System.out.println("i + j is " +
(i + j));

You might also like