Computer program is a set of instructions that guide a computer to execute a particular task. It is like a recipe for a cook in making a particular dish. The recipe contains a list of ingredients called the data or variables, and a list of steps that guide the computer what to do with the data. So programming is the technique of making a computer to perform something you want to do.
Programming or coding is a language that is used by operating systems to perform the task. We know computer understands binary languages with digits 1s and 0s. These binary languages are difficult to understand by human; so we generally use an intermediate language instead of binary language. Again the program uses high-level language that is interpreted into bytes that the computer understands. So a programmer writes a source code and uses a tool or interpreter that allows the computer to read, translate and execute the programs to perform a function.
What is Java, it?s history?
Java is a high-level object-oriented programming language developed by the Sun Microsystems.
What is Java, it’s history?
Java is a high-level object-oriented programming language developed by the Sun Microsystems. Though it is associated with the World Wide Web but it is older than the origin of Web. It was only developed keeping in mind the consumer electronics and communication equipments. It came into existence as a part of web application, web services and a platform independent programming language in the 1990s.
Download JDK
What is JDK (Java Development Kit)
JDK is a software development program provided by sun Microsystems. Java Development Kit or JDK comes in various version and can be downloaded free from the sun Microsystems. JVM compiler, debugger and other tools are used with JDK for developing java based application & java applets. So make sure that your JVM compiler & JDK versions are same.
JDK also known as Java 2 Platform, That comes in three editions J2ME, J2SE & J2EE. If you are beginner or learning Java then start by downloading J2SE.
Acronyms:
JDK Java Development Kit
JVM Java virtual machine
Download JDK or Jcreator
You can download JDK from www.javasoft.com/j2se
Latest version of JDK
1. JDK 5.0 Update 6
The full internal version number for this update release is 1.5.0_06-b05 (where "b" means "build"). The external version number is 5.0u6. Java Version 1.5.0_06 introduces various security enhancements in Java Plug-in and Java Web Start to better protect users and enterprises. For more information please visit: http://java.sun.com/j2se/1.5.0/ReleaseNotes.html
Getting Started - Write your First Java Program
Let us begin by writing our first Java program that prints a message "Hello, world!" to the display console, as shown:
Hello, world!
You could write Java programs using a programming text editor or an integrated development tool (such as Eclipse or NetBeans), Depending on your choice, read:
* writing your first Java program using JDK and a programming text editor (try this if you are not sure).
* writing your first Java program using Eclipse.
* writing your first Java program using NetBeans.
Hello, world
Dissecting Hello.java: Let us dissect the "Hello-world" program (reproduced below with line numbers added on the left panel to help in the explanation).
1
2
3
4
5
6
7
8
/*
* First Java program, which says "Hello, world!"
*/
public class Hello { // To save as "Hello.java"
public static void main(String[] args) {
System.out.println("Hello, world!"); // Print message
}
}
The statements after // are called comments. Comments are not executable, but provide useful explanation to you and your readers. There are two kinds of comments:
1. Multi-line Comment: begins with "/*" and ends with "*/", and may span more than one lines (as in Lines 1-3).
2. End-of-line Comment: begins with "//" and lasts until the end of the current line (as in Lines 4 and 6).
The basic unit of a Java program is a class. A class called "Hello" is defined with the keyword "class" in Lines 4-8, as follows:
public class Hello { ...... } // Use keyword "class" to define a class
// { ...... } is the "body" of the class
// The keyword "public" will be discussed later
In Java, the name of the source file must be the same as the name of the public class with a mandatory file extension of ".java". Hence, this file must be saved as "Hello.java".
Lines 5-7 defines the so-called main() method, which is the starting point, or entry point, of program execution, as follows:
public static void main(String[] args) { ...... } // main() method is the entry point of program execution
// { ...... } is the "body" of the method,
// which contains your programming statements.
// Other keywords will be discussed later.
In Line 6, the method System.out.println("Hello, world!") is used to print the message string "Hello, world!". A string is surrounded by a pair of double quotes and contain texts. The text will be printed as it is, without the double quotes.
A programming statement performs a piece of programmming action, which must be terminated by a semi-colon ";", as in Line 6.
A block is a group of programming statements enclosed by braces { }. There are two blocks in this program. One contains the body of the class Hello. The other contains the body of the main() method. There is no need to put a semi-colon after the closing brace.
Extra white-spaces, tabs, and lines are ignored, but they could help you and your readers to better understand your program. Use them liberally.
Java is case sensitive - a ROSE is NOT a Rose, and is NOT a rose. The filename is also case sensitive.
Java Program Template
You can use the following template to write your Java programs. Choose a meaningful Classname that reflects the purpose of your program, and write your programming statements inside the body of the main() method. Don't worry about the other terms and keywords now, which will be explained in due course.
1
2
3
4
5
public class Classname { // Choose a meaningful classname, save as "Classname.java"
public static void main(String[] args) {
// Your programming statements here!
}
}
Printing via System.out.println() and System.out.print()
System.out.println(aString) prints aString to the display console, and brings the cursor to the beginning of the next line; while System.out.print(aString) prints aString but keeps the cursor after the printed string. Try the following program and explain the output produced.
1
2
3
4
5
6
7
8
9
10
11
public class PrintTest { // Save as "PrintTest.java"
public static void main(String[] args) {
System.out.println("Hello, world!"); // Advance to next line after printing "Hello, world!"
System.out.println(); // Print a empty line
System.out.print("Hello, world!"); // Cursor stayed after the printed string
System.out.println("Hello,");
System.out.print(" "); // Print a space
System.out.print("world!");
System.out.println("Hello, world!");
}
}
Hello, world!
Hello, world!Hello,
world!Hello, world!
Let's Write a Program to Add a Few Numbers
Let's write a program to add five integers as follows:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/*
* Sum five numbers and print the result
*/
public class FiveNumberSum { // Save as "FiveNumberSum.java"
public static void main(String[] args) {
int number1 = 11;
int number2 = 22;
int number3 = 33;
int number4 = 44;
int number5 = 55;
int sum;
sum = number1 + number2 + number3 + number4 + number5;
System.out.print("The sum is "); // Print a descriptive string
System.out.println(sum); // Print the value stored in sum
}
}
The sum is 165
Lines 6-10 declare five int (integer) variables called number1, number2, number3, number4, and number5; and assign then values of 11, 22, 33, 44, and 55 respectively, via the so-called assignment operator "=".
Line 11 declares a int (integer) variable called sum, without assigning an initial value.
Line 12 computes the sum of number1 to number5 and assign the result to the variable sum. The symbol '+' denotes arithmetic addition, just like Mathematics.
Line 13 prints a descriptive string. A String is surrounded by double quotes, and will be printed as it is (but without the double quotes).
Line 14 prints the value stored in the variable sum (in this case, the sum of the five numbers) - you should not surround a variable to be printed by double quotes.
What is a Program?
A program is a sequence of instructions (or programming statements), executing one after another - usually in a sequential manner, as illustrated in the following flow chart.
sequential flow
EXAMPLE: The following program prints the area and perimeter of a circle, given its radius. Take note that the programming statements are executed sequentially.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/*
* Print the area and perimeter of a circle, given its radius.
*/
public class CircleComputation { // Saved as "CircleComputation.java"
public static void main(String[] args) {
// Declare variables
double radius;
double area;
double perimeter;
// Assign a value to radius
radius = 1.2;
// Compute area and perimeter
area = radius * radius * 3.1416;
perimeter = 2.0 * radius * 3.1416;
// Print results
System.out.print("The radius is ");
System.out.println(radius);
System.out.print("The area is ");
System.out.println(area);
System.out.print("The perimeter is ");
System.out.println(perimeter);
}
}
The radius is 1.2
The area is 4.523904
The perimeter is 7.53984
Lines 7-9 declare three double variables, which can hold real numbers (or floating-point numbers). Line 12 assigns a value to the variable radius. Lines 15-16 compute the area and perimeter, based on the radius. Lines 19-24 print the results.
Take note that the programming statements inside the main() are executed one after another, sequentially.
What is a Variable?
Computer programs manipulate (or process) data. A variable is used to store a piece of data for processing. It is called variable because you can change the value stored.
More precisely, a variable is a named storage location, that stores a value of a particular data type. In other words, a variable has a name, a type and stores a value.
* A variable has a name (or identifier), e.g., radius, area, age, height. The name is needed to uniquely identify each variable, so as to assign a value to the variable (e.g., radius=1.2), and retrieve the value stored (e.g., area = radius*radius*3.1416).
* A variable has a type. Examples of type are:
o int: for integers (whole numbers) such as 123 and -456;
o double: for floating-point or real numbers, such as 3.1416, -55.66, having a decimal point and fractional part;
o String: for texts such as "Hello", "Good Morning!". Text strings are enclosed within a pair of double quotes.
* A variable can store a value of that particular type. It is important to take note that a variable in most programming languages is associated with a type, and can only store value of the particular type. For example, a int variable can store an integer value such as 123, but NOT real number such as 12.34, nor texts such as "Hello". The concept of type was introduced into the early programming languages to simplify intrepretation of data made up of 0s and 1s.
The following diagram illustrates three types of variables: int, double and String. An int variable stores an integer (whole number). A double variable stores a real number. A String variable stores texts.
variable
To use a variable, you need to first declare its name and type, in one of the following syntaxes:
var-type var-name; // Declare a variable of a type
var-type var-name-1, var-name-2,...; // Declare multiple variables of the same type
var-type var-name = initial-value; // Declare a variable of a type, and assign an initial value
var-type var-name-1 = initial-value-1, var-name-2 = initial-value-2,... ; // Declare variables with initial values
Take note that:
* Each declaration statement is terminated with a semi-colon ";".
* In multiple-variable declaration, the names are separated by commas ",".
* The symbol "=", known as the assignment operator, can be used to assign an initial value (of the declared type) to the variable.
For example,
int sum; // Declare a variable named "sum" of the type "int" for storing an integer.
// Terminate the statement with a semi-colon.
int number1, number2; // Declare two "int" variables named "number1" and "number2",
// separated by a comma.
double average; // Declare a variable named "average" of the type "double" for storing a real number.
int height = 20; // Declare an int variable, and assign an initial value.
Once a variable is declared, you can assign and re-assign a value to a variable, via the assignment operator "=". For example,
int number; // Declare a variable named "number" of the type "int" (integer)
number = 99; // Assign an integer value of 99 to the variable "number"
number = 88; // Re-assign a value of 88 to "number"
number = number + 1; // Evaluate "number + 1", and assign the result back to "number"
int sum = 0; // Declare an int variable named sum and assign an initial value of 0
sum = sum + number; // Evaluate "sum + number", and assign the result back to "sum", i.e. add number into sum
int num1 = 5, num2 = 6; // Declare and initialize two int variables in one statement, separated by a comma
double radius = 1.5; // Declare a variable name radius, and initialize to 1.5
int number; // ERROR: A variable named "number" has already been declared
sum = 55.66; // ERROR: The variable "sum" is an int. It cannot be assigned a floating-point number
sum = "Hello"; // ERROR: The variable "sum" is an int. It cannot be assigned a text string
Take note that:
* Each variable can only be declared once.
* You can declare a variable anywhere inside the program, as long as it is declared before it is being used.
* Once the type of a variable is declared, it can only store a value belonging to this particular type. For example, an int variable can hold only integer such as 123, and NOT floating-point number such as -2.17 or text string such as "Hello".
* The type of a variable cannot be changed inside the program.
I have shown your two data types in the above example: int for integer and double for floating-point number (or real number). Take note that in programming, int and double are two distinct types and special caution must be taken when mixing them in an operation, which shall be explained later.
Basic Arithmetic Operations
The basic arithmetic operations are:
* addition (+)
* subtraction (-)
* multiplication (*)
* division (/)
* remainder or modulo (%)
* increment (by 1) (++)
* decrement (by 1) (--)
Addition, subtraction, multiplication, division and remainder take two operands (binary operators); while increment and decrement take only one operand (unary operators).
The following program illustrates these arithmetic operations.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
* Test Arithmetic Operations
*/
public class ArithmeticTest { // Save as "ArithmeticTest.java"
public static void main(String[] args) {
int number1 = 98; // Declare an int variable number1 and initialize it to 98
int number2 = 5; // Declare an int variable number2 and initialize it to 5
int sum, difference, product, quotient, remainder; // Declare five int variables to hold results
// Perform arithmetic Operations
sum = number1 + number2;
difference = number1 - number2;
product = number1 * number2;
quotient = number1 / number2;
remainder = number1 % number2;
System.out.print("The sum, difference, product, quotient and remainder of "); // Print description
System.out.print(number1); // Print the value of the variable
System.out.print(" and ");
System.out.print(number2);
System.out.print(" are ");
System.out.print(sum);
System.out.print(", ");
System.out.print(difference);
System.out.print(", ");
System.out.print(product);
System.out.print(", ");
System.out.print(quotient);
System.out.print(", and ");
System.out.println(remainder);
number1++; // Increment the value stored in the variable "number1" by 1
// Same as "number1 = number1 + 1"
number2--; // Decrement the value stored in the variable "number2" by 1
// Same as "number2 = number2 - 1"
System.out.println("number1 after increment is " + number1); // Print description and variable
System.out.println("number2 after decrement is " + number2);
quotient = number1 / number2;
System.out.println("The new quotient of " + number1 + " and " + number2
+ " is " + quotient);
}
}
The sum, difference, product, quotient and remainder of 98 and 5 are 103, 93, 490, 19, and 3
number1 after increment is 99
number2 after decrement is 4
The new quotient of 99 and 4 is 24
Lines 7-8 declare and initialize two int (integer) variables number1 and number2. Line 9 declares five int variables sum, difference, product, quotient, and remainder to hold the results of operations, in one statement (with items separated by commas), without assigning initial values.
Lines 12-16 carry out the arithmetic operations on variables number1 and number2. Take note that division of two integers produces a truncated integer, e.g., 98/5 → 19, 99/4 → 24, and 1/2 → 0.
Lines 17-30 print the results of the arithmetic operations, with appropriate string descriptions in between. Take note that text string are enclosed within double-quotes, and will get printed as it is, including the white spaces but without the double quotes. To print the value stored in a variable, no double quotes should be used. For example,
System.out.println("sum"); // Print text string "sum" - as it is
System.out.println(sum); // Print the value stored in variable sum, e.g., 98
Lines 32 and 34 illustrate the increment and decrement operations. Unlike "+", "-", "*", "/" and "%", which work on two operands (binary operators), "++" and "--" operate on only one operand (unary operators).
Lines 36-37 print the new values stored after the increment/decrement operations. Take note that instead of using many print() statements as in Lines 17-30, we could simply place all the items (text strings and variables) into one println(), with the items separated by "+". In this case, "+" does not perform addition. Instead, it concatenates or joins all the items together. Line 36 provides another example.
TRY:
1. Combining Lines 17-30 into one single println() statement, using "+" to concatenate all the items together.
2. Introduce one more int variable called number3, and assign it an integer value of 77. Compute and print the sum and product of all the three numbers.
3. In Mathematics, we could omit the multiplication sign in an arithmetic expression, e.g., x = 5a + 4b. In programming, you need to explicitly provide all the operators, i.e., x = 5*a + 4*b. Try printing the sum of 31 times of number1 and 17 times of number2 and 87 time of number3.
What If Your Need To Add Many Numbers?
Suppose that you want to add all the integers from 1 to 1000. If you follow the previous example, you would require a thousand-line program! Instead, you could use a loop in your program to perform a repetitive task, that is what the computer is good at.
Loop
Try the following program, which sums all the integers from a lowerbound (=1) to an upperbound (=1000) using a so-called for-loop.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/*
* Sum from a lowerbound to an upperbound using a for-loop
*/
public class RunningNumberSum { // Save as "RunningNumberSum.java"
public static void main(String[] args) {
int lowerbound = 1; // Store the lowerbound
int upperbound = 1000; // Store the upperbound
int sum = 0; // Declare an int variable "sum" to accumulate the numbers
// Set the initial sum to 0
// Use a for-loop to repeatitively sum from the lowerbound to the upperbound
for (int number = 1; number <= upperbound; number++) { sum = sum + number; // Accumulate number into sum } // Print the result System.out.println("The sum from " + lowerbound + " to " + upperbound + " is " + sum); } } The sum from 1 to 1000 is 500500 Let us dissect this program: Lines 6 and 7 declare two int variables to store the lowerbound and upperbound respectively. Line 8 declares an int variable named sum and initializes it to 0. This variable will be used to accumulate numbers over the steps in the repetitive loop. Lines 11-13 contain a so-called for-loop. A for-loop takes the following syntax: // Syntax for ( initialization ; test ; post-processing ) { body ; } // Example int sum = 0; for (int number = 1; number <= 1000; number++) { sum = sum + number; } for-loop There are four parts in a for-loop. Three of them, initialization, test condition and post-processing, are enclosed in brackets ( ), and separated by two semi-colons ";". The body contains the repetitive task to be performed. As illustrated in the above flow chart, the initialization statement is first executed. The test is then evaluated. If the test returns true, the body is executed; followed by the post-processing statement. The test is checked again and the process repeats until the test is false. When the test is false, the for-loop completes and program execution continues to the next statement after the for-loop. In our program, the initialization statement declares an int variable named number and initializes it to lowerbound (=1). The test checks if number is equal to or less than upperbound (=1000). If it is true, the current value of number is added into the sum, and the post-processing statement "number++" increases the value of number by 1. The test is then checked again and the process repeats until the test is false (i.e., number increases to upperbound+1), which causes the for-loop to terminate. Execution then continues to the next statement (in Line 15). In this example, the loop repeats 1000 times (number having value of 1 to 1000). After the loop is completed, Line 15 prints the result with a proper description. TRY: 1. Modify the above program to sum all the numbers from 9 to 888. (Ans: 394680.) 2. Modify the above program to sum all the odd numbers between 1 to 1000. (Hint: Change the post-processing statement to "number = number + 2". Ans: 250000) 3. Modify the above program to sum all the numbers between 1 to 1000 that are divisible by 7. (Hint: Modify the initialization and post-processing statements. Ans: 71071.) 4. Modify the above program to find the sum of the square of all the numbers from 1 to 100, i.e. 1*1 + 2*2 + 3*3 +... (Ans: 338350.) 5. Modify the above program (called RunningNumberProduct) to compute the product of all the numbers from 1 to 10. (Hint: Use a variable called product instead of sum and initialize product to 1. Ans: 3628800.) Conditional What if you want to sum all the odd numbers and also all the even numbers between 1 and 1000? There are many ways to do this. You could declare two variables: sumOdd and sumEven. You can then use a conditional statement to check whether the number is odd or even, and accumulate the number into the respective sums. The program is as follows: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 23 /* * Sum the odd numbers and the even numbers from a lowerbound to an upperbound */ public class OddEvenSum { // Save as "OddEvenSum.java" public static void main(String[] args) { int lowerbound = 1; int upperbound = 1000; int sumOdd = 0; // For accumulating odd numbers, init to 0 int sumEven = 0; // For accumulating even numbers, init to 0 for (int number = lowerbound; number <= upperbound; number++) { if (number % 2 == 0) { // Even sumEven += number; // Same as sumEven = sumEven + number } else { // Odd sumOdd += number; // Same as sumOdd = sumOdd + number } } // Print the result System.out.println("The sum of odd numbers from " + lowerbound + " to " + upperbound + " is " + sumOdd); System.out.println("The sum of even numbers from " + lowerbound + " to " + upperbound + " is " + sumEven); System.out.println("The difference between the two sums is " + (sumOdd - sumEven)); } } The sum of odd numbers from 1 to 1000 is 250000 The sum of even numbers from 1 to 1000 is 250500 The difference between the two sums is -500 Lines 8 and 9 declare two int variables named sumOdd and sumEven and initialize them to 0, for accumulating the odd and even numbers respectively. Lines 11-15 contain a conditional statement. The conditional statement can take one the following forms: if-then, if-then-else. // if-then syntax if ( condition ) { true-body ; } // Example if (mark >= 50) {
System.out.println("Congratulation!");
}
// if-then-else syntax
if ( condition ) {
true-body ;
} else {
false-body ;
}
// Example
if (mark >= 50) {
System.out.println("Congratulation!");
} else {
System.out.println("Try Harder!");
}
For a if-then statement, the true-body is executed if the test condition is true. Otherwise, nothing is done and the execution continues to the next statement.
For a if-then-else statement, the true-body is executed if the condition is true; otherwise, the false-body is executed. Execution is then continued to the next statement.
The following flow chart illustrates the if-then and if-then-else statements.
if-then if-then-else
In our program, we use the remainder (or modulo) operator (%) to compute the remainder of number divides by 2. We then compare the remainder with 0 to test for even number.
There are six comparison operators:
* equal to (==)
* not equal to (!=)
* greater than (>)
* less than (<) * greater than or equal to (>=)
* less than or equal to (<=) Take note that the comparison operator for equality is a double-equal sign (==); whereas a single-equal sign (=) is the assignment operator. Combining Simple Conditions Suppose that you want to check whether a number x is between 1 and 100 (inclusive), i.e., 1 <= x <= 100. There are two simple conditions here, (x >= 1) AND (x <= 100). In programming, you cannot write 1 <= x <= 100, but need to write (x >= 1) && (x <= 100), where "&&" denotes the "AND" operator. Similarly, suppose that you want to check whether a number x is divisible by 2 OR by 3, you have to write (x % 2 == 0) || (x % 3 == 0) where "||" denotes the "OR" operator. There are three so-called logical operators that operate on the boolean conditions: * AND (&&) * OR (||) * NOT (!) For examples: // Return true if x is between 0 and 100 (inclusive) (x >= 0) && (x <= 100) // AND (&&) // Incorrect to use 0 <= x <= 100 // Return true if x is outside 0 and 100 (inclusive) (x < 0) || (x > 100) // OR (||)
!((x >= 0) && (x <= 100)) // NOT (!), AND (&&) // Return true if "year" is a leap year // A year is a leap year if it is divisible by 4 but not by 100, or it is divisible by 400. ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0) TRY: 1. Write a program to sum all the integers between 1 and 1000, that are divisible by 13, 15 or 17, but not by 30. 2. Write a program to print all the leap years between AD1 and AD2010, and also print the number of leap years. Type double and Floating-Point Numbers Recall that a variable in Java has a name and a type, and can hold a value of only that particular type. We have so far used a type called int. A int variable holds an integer, such as 123 and -456; it cannot hold a real number, such as 12.34. In programming, real numbers such as 3.1416, -55.66 are called floating-point numbers, and belong to a type called double. For example, 1 2 3 4 5 6 7 8 9 10 11 public class CircleOperation { // Saved as "CircleOperation.java" public static void main(String[] args) { double radius = 1.2; // Type double for floating-point numbers double pi = 3.1416; double area; area = radius * radius * pi; System.out.println("The radius is " + radius); System.out.println("The area is " + area); System.out.println("The perimeter is " + (2.0 * pi * radius)); } } The radius is 1.2 The area is 4.523904 The perimeter is 7.53984 Mixing int and double, and Type Casting Although you can use a double to keep an integer value (e.g., double count = 5.0), you should use an int for integer, as int is far more efficient than double (e.g., in terms of running times, storage, among others). At times, you may need both int and double in your program. For example, keeping the sum from 1 to 1000 as int, and their average as double. You need to be extremely careful when different types are mixed. It is important to note that: * Arithmetic operations ('+', '-', '*', '/') of two int's produce an int; while arithmetic operations of two double's produce a double. Hence, 1/2 → 0 and 1.0/2.0 → 0.5. * Arithmetic operations of an int and a double produce a double. Hence, 1.0/2 → 0.5 and 1/2.0 → 0.5. You can assign an integer value to a double variable. The integer value will be converted to a double value automatically, e.g., 3 → 3.0. For example, int i = 3; double d; d = i; // 3 → 3.0, d = 3.0 d = 88; // 88 → 88.0, d = 88.0 double nought = 0; // 0 → 0.0; there is a subtle difference between int 0 and double 0.0 However, you CANNOT assign a double value directly to an int variable. This is because the fractional part could be lost, and the compiler signals an error in case that you were not aware. For example, double d = 5.5; int i; i = d; // Compilation Error i = 6.6; // Compilation Error To assign an double value to an int variable, you need to explicitly invoke a type-casting operation to truncate the fractional part, as follows: double d = 5.5; int i; i = (int) d; // Type-cast the value of double d, which returns an int value, // assign the resultant int value to int i. // The value stored in d is not affected. i = (int) 3.1416; // i = 3 Take note that type-casting operator, in the form of (int) or (double), applies to one operand immediately after the operator (i.e., unary operator). Type-casting is an operation, like increment or addition, which operates on a operand and return a value (in the specified type), e.g., (int)3.1416 takes a double value of 3.1416 and returns 3 (of type int); (double)5 takes an int value of 5 and returns 5.0 (of type double). Try the following program and explain the outputs produced. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 /* * Find the sum and average from a lowerbound to an upperbound */ public class TypeCastingTest { // Save as "TypeCastingTest.java" public static void main(String[] args) { int lowerbound = 1; int upperbound = 1000; int sum = 0; // sum is "int" double average; // average is "double" // Compute the sum (in "int") for (int number = lowerbound; number <= upperbound; number++) { sum = sum + number; } System.out.println("The sum from " + lowerbound + " to " + upperbound + " is " + sum); // Compute the average (in "double") average = sum/1000; System.out.println("Average 1 is " + average); average = (double)sum/1000; System.out.println("Average 2 is " + average); average = sum/1000.0; System.out.println("Average 3 is " + average); average = (double)(sum/1000); System.out.println("Average 4 is " + average); } } The sum is 500500 Average 1 is 500.0 <== incorrect Average 2 is 500.5 Average 3 is 500.5 Average 4 is 500.0 <== incorrect The first average is incorrect, as int/int produces an int (of 500), which is converted to double (of 500.0) to be stored in average (of double). For the second average, the value of sum (of int) is first converted to double. Subsequently, double/int produces a double. For the third average, int/double produces double. For the fourth average, int/int produces an int (of 500), which is casted to double (of 500.0) and assigned to average (of double). TRY: 1. Write a program called HarmonicSeriesSum to compute the sum of a harmonic series 1 + 1/2 + 1/3 + 1/4 + .... + 1/n, where n = 1000. Keep the sum in a double variable, and take note that 1/2 gives 0 but 1.0/2 gives 0.5. Try computing the sum for n=1000, 5000, 10000, 50000, 100000. Hints: public class HarmonicSeriesSum { // Saved as "HarmonicSeriesSum.java" public static void main (String[] args) { int numTerms = 1000; double sum = 0.0; // For accumulating sum in double for (int denominator = 1; denominator <= numTerms ; denominator++) { // Beware that int/int gives int ...... } // Print the sum ...... } } The sum is 7.484470860550343 2. Modify the above program (called GeometricSeriesSum) to compute the sum of this series: 1 + 1/2 + 1/4 + 1/8 + .... (for 1000 terms). Hints: Use post-processing statement of denominator = denominator*2. Summary I have presented the basics for you to get start in programming. To learn programming, you need to understand the syntaxes and features involved in the programming language that you chosen, and you have to practice, practice and practice, on as many problems as you could. REFERENCES & RESOURCES * "New to Java Program Center" @ http://www.oracle.com/technetwork/topics/newtojava/overview/index.html, Sun Microsystems (now Oracle). * "The Java tutorials - Getting Started" @ http://download.oracle.com/javase/tutorial/ Sun Microsystems (now Oracle). * Y. Daniel Liang, "Introduction to Java Programming", latest edition. * Deitel & Deitel, "Java, How to Program", latest edition. * Bruce Eckel, "Thinking in Java", latest edition. Latest version tested: JDK 1.6 Last modified: September, 2010 Feedback, comments, corrections, and errata can be sent to Chua Hock-Chuan (ehchua@ntu.edu.sg) | HOME What is Fibonacci Sequence? A series of whole numbers in which each number is the sum of the two preceding numbers. Beginning with 0 and 1, the sequence of Fibonacci numbers would be 0,1,1, 2, 3, 5, 8, 13, 21, 34, etc. using the formula n = n(-1) + n(-2), where the n(-1) means “the last number before n in the series” and n(-2) refers to “the second last one before n in the series. Example: The Fibonacci sequence starts with the numbers 0 and 1. The next number is the sum of these and subsequent numbers are the sum of the preceding pair. so we get 0,1,1,2,3,5.... write a java program to display the first 20 fibonacci numbers using for loop statement soln using FOR.LOOP. public class JavaFibonacciSeriesExample { public static void main(String[] args) { int limit = 20; long[] series = new long[limit]; series[0] = 0; series[1] = 1; for(int i=2; i < limit; i++){ series[i] = series[i-1] + series[i-2]; } System.out.println("Fibonacci Series upto " + limit); for(int i=0; i< limit; i++){ System.out.print(series[i] + " "); } } } Fibonacci Series upto 20 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 yet another insignificant programming notes... | HOME Java Programming Java Basics - Exercises Exercises on Flow Controls Exercises on Conditional (Decision) Exercise (if-else): Write a program called CheckMark which prints "PASS" if the int variable "mark" is more than or equal to 50; or prints "FAIL" otherwise. Hints: public class CheckMark { // saved as "CheckMark.java" public static void main(String[] args) { int mark = 49; // set the value of mark here! System.out.println("The mark is " + mark); if ( ...... ) { System.out.println( ...... ); } else { System.out.println( ...... ); } } } Exercise (if-else): Write a program called CheckNumber which prints "Odd Number" if the int variable “number” is odd, or “Even Number” otherwise. Hints: public class CheckNumber { // saved as "CheckNumber.java" public static void main(String[] args) { int number = 49; // set the value of number here! System.out.println("The number is " + number); if ( ...... ) { System.out.println( ...... ); } else { System.out.println( ...... ); } } } Exercise (nested-if, switch-case): Write a program called PrintWord which prints "ONE", "TWO",... , "NINE", "OTHER" if the int variable "number" is 1, 2,... , 9 or other, respectively. Use (a) a "nested-if" statement; (b) a "switch-case" statement. Hints: public class PrintWord { // saved as "PrintWord.java" public static void main(String[] args) { int number = 5; // nested-if if (number == 1) { System.out.println("ONE"); } else if (......) { ...... } else if (......) { ...... } else { ...... } // switch-case switch(number) { case 1: System.out.println("ONE"); break; case 2: ...... ...... default: System.out.println("OTHER"); } } } Exercises on Loop (Iteration) Exercise (Loop): Write a program called SumAndAverage to produce the sum of 1, 2, 3, ..., to 100. Also compute and display the average. The output shall look like: The sum is 5050 The average is 50.5 Hints: public class SumAndAverage { // saved as "SumAndAverage.java" public static void main (String[] args) { int sum = 0; // store the accumulated sum double average; // average in double int lowerbound = 100; // the lower bound to sum int upperbound = 100; // the upper bound to sum for (int number = lowerbound; number <= upperbound; number++) { // for loop sum += number; // same as "sum = sum + number" } // Compute average in double. Beware that int/int produces int. ...... // Print sum and average. ...... } } Try: 1. Modify the program to use a "while-do" loop instead of "for" loop. int number = 1; int sum = 0; while (number <= upperbound) { sum += number; number++; } 2. Modify the program to use a "do-while" loop. int number = 1; int sum = 0; do { sum += number; number++; } while (number <= upperbound); 3. Modify the program to sum from 111 to 8989, and compute the average. Introduce an int variable called count to count the numbers in the specified range. int count = 0; for (...; ...; ...) { ...... count++; } 4. Modify the program to sum only the odd numbers from 1 to 100, and compute the average. 5. Modify the program to sum those numbers from 1 to 100 that is divisible by 7, and compute the average. 6. Modify the program to find the "sum of the squares" of all the numbers from 1 to 100, i.e. 1*1 + 2*2 + 3*3 + ... + 100*100. Exercise (Loop): Write a program called Product1toN to compute the 10). Try computing the...32product of integers 1 to 10 (i.e., 1 product from 1 to 11, 1 to 12, 1 to 13 and 1 to 14. Write down the product obtained and explain the results. Hints: Declares an int variable called product (to accumulate the product) and initialize to 1. Exercise (Loop): Write a program called HarmonicSum to compute the sum of a harmonic series, as shown below, where n=50000. The program shall compute the sum from left-to-right as well as from the right-to-left. Obtain the difference between these two sums and explain the difference. Which sum is more accurate? Hints: public class HarmonicSum { // saved as "HarmonicSum.java" public static void main (String[] args) { int maxDenominator = 50000; double sumL2R = 0.0; // sum from left-to-right double sumR2L = 0.0; // sum from right-to-left // for-loop for summing from left-to-right for (int denominator = 1; denominator <= maxDenominator; denominator++) { ...... // Beware that int/int gives int. } // for-loop for summing from right-to-left ...... // Find the difference and display ...... } } Exercise (Loop & Condition): Write a program called ComputePI to compute the value of π, using the following series expansion. You have to decide on the termination criterion used in the computation (such as the number of terms used or the magnitude of an additional term). Is this series suitable for computing π? JDK maintains the value of π in a double constant called Math.PI. Compare the values obtained, in terms of the ratio between the value computed and the Math.PI, in percents. Hint: Add to sum if the denominator modulus 4 is 1, and subtract from sum if it is 3. double sum = 0; int maxDenom = 10000000; for (int denom = 1; ..... ; denom = denom + 2) { if (denom % 4 == 1) { sum += ......; } else if (denom % 4 == 3) { sum -= ......; } else { System.out.println("The computer has gone crazy?!"); } } Exercise (Loop & Condition): Write a program called CozaLozaWoza which prints the number 1 to 110, 11 numbers per line. The program shall print "Coza" in place of the numbers which are multiples of 3, "Loza" for multiples of 5, "Woza" for multiples of 7, "CozaLoza" for multiples of 3 and 5, and so on. The output shall look like: 1 2 Coza 4 Loza Coza Woza 8 Coza Loza 11 Coza 13 Woza CozaLoza 16 17 Coza 19 Loza CozaWoza 22 23 Coza Loza 26 Coza Woza 29 CozaLoza 31 32 Coza ...... Hints: public class CozaLozaWoza { // saved as "CozaLozaWoza.java" public static void main(String[] args) { int lowerbound = 1; int upperbound = 110; for (int number = lowerbound; number <= upperbound; number++) { // Print "Coza" if number is divisible by 3 if (......) { System.out.print("Coza"); } // Print "Loza" if number is divisible by 5 if (......) { System.out.print(.....); } // Print "Woza" if number is divisible by 7 ...... // Print the number if it is not divisible by 3, 5 and 7 if (......) { ...... } // Print a space ...... // Print a newline if number is divisible by 11 if (......) { System.out.println(); } } } } Exercise (Loop): Write a program called Fibonacci to display the first 20 Fibonacci numbers F(n), where F(n)=F(n–1)+F(n–2) and F(1)=F(2)=1. Also compute their average. The output shall look like: The first 20 Fibonacci numbers are: 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 The average is 885.5 Hints: public class Fibonacci { public static void main (String args[]) { int n = 3; // the index n for F(n), starting from n=3 int fn; // F(n) to be computed int fnMinus1 = 1; // F(n-1), init to F(2) int fnMinus2 = 1; // F(n-2), init to F(1) int nMax = 20; // maximum n, inclusive int sum = fnMinus1 + fnMinus2; double average; System.out.println("The first " + nMax + " Fibonacci numbers are:"); ...... while (n <= nMax) { // Compute F(n), print it and add to sum ...... // Adjust the index n and shift the numbers ...... } // Compute and display the average (=sum/nMax) ...... } } Tribonacci numbers are a sequence of numbers T(n) similar to Fibonacci numbers, except that a number is formed by adding the three previous numbers, i.e., T(n)=T(n-1)+T(n-2)+T(n-3), T(1)=1, T(2)=1 and T(3)=2. Write a program called Tribonacci to produce the first twenty Tribonacci numbers. Exercises on Nested-Loop Exercise (nested-loop): Write a program called SquareBoard that displays the following 5x5 pattern using two nested for-loops. # # # # # # # # # # # # # # # # # # # # # # # # # Your program should use only two output statements, one each of the followings: System.out.print("# "); // print "# ", without newline System.out.println(); // print a newline Hints: public class SquareBoard { // saved as "SquareBoard.java" public static void main (String[] args) { int size = 5; // size of the board for (int row = 1; ......; ......) { for (int col = 1; ......; ......) { ...... } ...... } } } Exercise (nested-loop): Write a program called CheckerBoard that displays the following 7x7 checkerboard pattern using two nested for-loops. # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # Your program should use only three output statements, one each of the followings: System.out.print("# "); // print "# ", without newline System.out.print(" "); // print a space, without newline System.out.println(); // print a newline Hints: public class CheckerBoard { // saved as "CheckerBoard.java" public static void main (String[] args) { int size = 7; // size of the board for (int row = 1; ......; ......) { // Use modulus 2 to find alternate lines if ((row % 2) == 0) { // row 2, 4, 6, 8 ...... } for (int col = 1; ......; ......) { ...... } ...... } } } Exercise (nested-loop): Write a program called TimeTable to produce the multiplication table of 1 to 9 as shown using two nested for-loops: * | 1 2 3 4 5 6 7 8 9 ------------------------------- 1 | 1 2 3 4 5 6 7 8 9 2 | 2 4 6 8 10 12 14 16 18 3 | 3 6 9 12 15 18 21 24 27 4 | 4 8 12 16 20 24 28 32 36 5 | 5 10 15 20 25 30 35 40 45 6 | 6 12 18 24 30 36 42 48 54 7 | 7 14 21 28 35 42 49 56 63 8 | 8 16 24 32 40 48 56 64 72 9 | 9 18 27 36 45 54 63 72 81 Modify the program to print the multiplication table of 1 to 12. Exercises on Input Exercise (Keyboard Input): Write a program called KeyboardInput to prompt user for an int, a double, and a String. The output shall look like (the inputs are shown in bold): Enter an integer: 12 Enter a floating point number: 33.44 Enter your name: Peter Hi! Peter, the sum of 12 and 33.44 is 45.44 Hints: import java.util.Scanner; // needed to use Scanner for input public class KeyboardInput { public static void main(String[] args) { int num1; double num2; String name; double sum; // Setup a Scanner called in to scan the keyboard (System.in) Scanner in = new Scanner(System.in); System.out.print("Enter an integer: "); num1 = in.nextInt(); // use nextInt() to read int System.out.print("Enter a floating point number: "); num2 = in.nextDouble(); // use nextDouble() to read double System.out.print("Enter your name: "); name = in.next(); // use next() to read String // Display ...... } } Exercise (File Input): Write a program called FileInput to read an int, a double, and a String form a text file called "in.txt", and produce the following output: The integer read is 12 The floating point number read is 33.44 The String read is "Peter" Hi! Peter, the sum of 12 and 33.44 is 45.44 You need to create a text file called "in.txt" (in Eclipse, right-click on the "project" ⇒ "New" ⇒ "File") with the following contents: 12 33.44 Peter import java.util.Scanner; // Needed to use Scanner for input import java.io.File; // Needed to use File import java.io.FileNotFoundException; // Needed for file operation public class FileInput { public static void main(String[] args) throws FileNotFoundException { // Needed for file operation int num1; double num2; String name; double sum; // Setup a Scanner to read from a text file Scanner in = new Scanner(new File("in.txt")); num1 = in.nextInt(); // use nextInt() to read int num2 = in.nextDouble(); // use nextDouble() to read double name = in.next(); // use next() to read String // Display ...... } } Exercise (User Input): Write a program called CircleComputation, which prompts user for a radius and compute the area and perimeter of a circle. The output shall look like: Enter the radius: 1.2 The area is 4.5239 The perimeter is 7.5398223686155035 Hints: π is kept in a constant called Math.PI. Exercise (User Input & String Operations): Write a program called ReverseString, which prompts user for a String, and prints the reverse of the String. The output shall look like: Enter a String: abcdef The reverse of String "abcdef" is "fedcba". Hints: import java.util.Scanner; public class ReverseString { public static void main(String[] args) { String inStr; // input String int inStrLen; // length of the input String Scanner in = new Scanner(System.in); System.out.print("Enter a String: "); inStr = in.next(); // use next() to read String inStrLen = inStr.length(); // Use inStr.charAt(index) to extract character at 'index' from inStr ...... } } For a String called inStr, you can use inStr.length() to retrieve the length of the String; and inStr.charAt(index) to retrieve the char at the index position, where index begins with 0. Exercise (User Input & String Operations): On your phone keypad, the alphabets are mapped to digits as follows: ABC(2), DEF(3), GHI(4), JKL(5), MNO(6), PQRS(7), TUV(8), WXYZ(9). Write a program called PhoneKeyPad, which prompts user for a string (case insensitive), and converts to a sequence of digits. Use a nested-if in this exercise. Modify your program to use an array for table look-up later. Hints: You can use in.next().toLowerCase() to read a string and convert it to lowercase to reduce your cases. Exercise (Palindrome): A word that reads the same backward as forward is called a palindrome, e.g., "mom", "dad", "racecar", "madam", and "Radar" (case-insensitive). Write a program called TestPalindromicWord, that prompts user for a word and prints ""xxx" is|is not a palindrome". Hints: Read in a word and convert to lowercase via in.next().toLowercase(). A phrase that reads the same backward as forward is also called a palindrome, e.g., "Madam, I'm Adam", "A man, a plan, a canal - Panama!" (ignoring punctuation and capitalization). Modify your program (called TestPalindromicPhrase) to test palindromic phrase. Hints: Read in the lowercase phrase via in.nextLine().toLowercase(). Maintain two indexes, forwardIndex and backwardIndex, used to scan the phrase forward and backward. Exercise (Bin2Dec): Write a program called Bin2Dec to convert a binary string into its equivalent decimal number. Your output shall look like: Enter a Binary string: 1011 The equivalent decimal number for binary "1011" is 11 Enter a Binary string: 1234 Error: Invalid Binary String "1234" Hints: For a n-bit binary number bn-1bn-2...b1b0, bi∈{0,1}, the equivalent decimal number is bn-1×2n-1+bn-2×2n-2+ ...+b1×21+b0×20. import java.util.Scanner; public class Bin2Dec { public static void main(String[] args) { String binStr; // input binary string int binStrLen; // length of the input string int dec = 0; // equivalent decimal number char binChar; // each individual char in the binary string Scanner in = new Scanner(System.in); // Read input binary string ...... // Convert binary string into Decimal ...... } } You can use JDK method Math.pow(x, y) to compute the x raises to the power of y. This method takes two doubles as argument and returns a double. You may have to cast the result back to int. To convert a char (of digit '0' to '9') to int, simply subtract by '0', e.g., '5'-'0'→5. Exercise (Hex2Dec): Write a program called HexToDec to convert a hexadecimal string into its equivalent decimal number. Your output shall look like: Enter a Hexadecimal string: 1a The equivalent decimal number for hexadecimal "1a" is 26 Enter a Hexadecimal string: 1y3 Error: Invalid Hexadecimal String "1y3" Hints: For a n-digit hexadecimal number hn-1hn-2...h1h0, hi∈{0,…,9,A,…,F}, the equivalent decimal number is hn-1×16n-1+hn-2×16n-2+ ...+h1×161+h0×160. You do not need a big nested-if statement of 16 cases (or 22 with upper and lower letters). Extract the individual character from the hexadecimal string, says c. If char c is between '0' to '9', you can get the integer offset via c-'0'. If c is between 'a' to 'f' or 'A' to 'F', the integer offset is c-'a'+10 or c-'A'+10. String hexStr; char hexChar; ...... hexChar = hexStr.charAt(i); ...... if (hexChar >= '0' && hexChar <= '9') { ... (hexChar-'0') ... ... } else if (hexChar >= 'a' && hexChar <= 'f') { // lowercase ... (hexChar-'a'+10) ... ... } else if (hexChar >= 'A' && hexChar <= 'F') { // uppercase ... (hexChar-'A'+10) ... ... } else { System.out.println("Error: Invalid hexadecimal string"); System.exit(1); // quit the program } Exercises on Array Exercise (Array): Write a program called GradesAverage, which reads in n grades (of int between 0 and 100) and displays the average. You should keep the grades in an int[] (an array of int). Your output shall look like: Enter the number of students: 3 Enter the grade for student 1: 55 Enter the grade for student 2: 108 Invalid grade, try again... Enter the grade for student 2: 56 Enter the grade for student 3: 57 The average is 56.0 Exercise (Array): Write a program called Hex2Bin to convert a hexadecimal string into its equivalent binary string. The output shall look like: Enter a Hexadecimal string: 1abc The equivalent binary for hexadecimal "1abc" is 0001 1010 1011 1100 Hints: Use an array of 16 binary Strings corresponding to hexadecimal number '0' to 'F', as follows: String[] hexBits = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"} Exercises on Command-line Arguments Exercise (Command-line arguments): Write a Java program called Arithmetic that takes three command-line arguments: two integers followed by an arithmetic operator (+, -, * or /). The program shall perform the corresponding operation on the two integers and print the result. For example: > java Arithmetic 3 2 +
3+2=5
> java Arithmetic 3 2 -
3-2=1
> java Arithmetic 3 2 /
3/2=1
Hints:
The method main(String[] args) has a parameter: "an array of String", which is often (but not necessary) named args. This parameter captures the command-line arguments supplied by the user when the program is invoked. For example, if a user invokes:
> java Arithmetic 12345 4567 +
The three command-line arguments "12345", "4567" and "+" will be captured in a String array and passed into the main() method as parameter args. That is,
args is {"12345", "4567", "+"}; // args is a String array
args.length is 3; // length of the array
args[0] is "12345"; // 1st element of the String array
args[1] is "4567"; // 2nd element of the String array
args[2] is "+"; // 3rd element of the String array
args[0].length() is 5; // length of 1st String element
args[1].length() is 4; // length of the 2nd String element
args[2].length() is 1; // length of the 3rd String element
public class Arithmetic {
public static void main (String[] args) {
int operand1, operand2;
char theOperator;
// Check if there are 3 command-line arguments in the
// String array args[] by using length variable of array.
if (args.length != 3) {
System.err.println("Usage: java Arithmetic int1 int2 op");
return;
}
// Convert the 3 Strings args[0], args[1], args[2] to int and char.
// Use the Integer.parseInt(aStr) to convert a String to an int.
operand1 = Integer.parseInt(args[0]);
operand2 = ......
// Get the operator, assumed to be the first character of
// the 3rd string. Use method charAt() of String.
theOperator = args[2].charAt(0);
System.out.print(args[0] + args[2] + args[1] + "=");
switch(theOperator) {
case ('-'):
System.out.println(operand1 – operand2); break;
case ('+'): ......
case ('*'): ......
case ('/'): ......
default:
System.err.println("\nError: invalid operator!");
}
}
}
Notes:
* To provide command-line arguments, use the "cmd" shell to run your program in the form "java ClassName arg1 arg2 ....".
* To provide command-line arguments in Eclipse, right click the source code ⇒ "Run As" ⇒ "Run Configurations..." ⇒ Select "Main" and choose the proper main class ⇒ Select "Arguments" ⇒ Enter the command-line arguments, e.g., "3 2 +" in "Program Arguments".
* To provide command-line arguments in Netbeans, right click the "Project" name ⇒ "Set Configuration" ⇒ "Customize..." ⇒ Select categories "Run" ⇒ Enter the command-line arguments, e.g., "3 2 +" in the "Arguments" box (but make sure you select the proper Main class).
Question: Try "java Arithmetic 2 4 *" (in CMD shell and Eclipse/Netbeans) and explain the result obtained. How to resolve this problem?
Exercise (Command-line arguments): Write a Java program called SumDigits to sum up the individual digits of a positive integer, given in the command line. The output shall look like:
> java SumDigits 12345
The sum of digits = 1 + 2 + 3 + 4 + 5 = 15
Exercises on Method
Exercise (Method): Write a program called GradesStatistics, which reads in n grades (of int between 0 and 100, inclusive) and displays the average, minimum, maximum, and standard deviation. Your program shall check for valid input. You should keep the grades in an int[] and use a method for each of the computations. Your output shall look like:
Enter the number of students: 4
Enter the grade for student 1: 50
Enter the grade for student 2: 51
Enter the grade for student 3: 56
Enter the grade for student 4: 53
The average is 52.5
The minimum is 50
The maximum is 56
The standard deviation is 2.29128784747792
Hints: The formula for calculating standard deviation is:
public class GradesStatistics {
public static int[] grades; // Declare an int[], to be allocated later
// main() method
public static void main(String[] args) {
readGrades();
System.out.println("The average is " + average());
System.out.println("The minimum is " + min());
System.out.println("The maximum is " + max());
System.out.println("The standard deviation is " + stdDev());
}
// Prompt user for the number of students and allocate the "grades" array.
// Then, prompt user for grade, check for valid grade, and store in "grades".
public static void readGrades() { ....... }
// Return the average value of int[] grades
public static double average() { ...... }
// Return the maximum value of int[] grades
public static int max() { ...... }
// Return the minimum value of int[] grades
public static int min() { ....... }
// Return the standard deviation of the int[] grades
public static double stdDev() { ....... }
}
Exercise (Method): Write a program called GradesHistogram, which reads in n grades (of int between 0 and 100, inclusive) from a text file called "grades.in" and displays the histogram. The file has the following format:
numStduents:int
grade1:int grade2:int .... gradeN:int
For example:
15
49 50 51 59 0 5 9 10 15 19 50 55 89 99 100
The output shall consist of a horizontal histogram and a vertical histogram as follows:
0 - 9: ***
10 - 19: ***
20 - 29:
30 - 39:
40 - 49: *
50 - 59: *****
60 - 69:
70 - 79:
80 - 89: *
90 -100: **
*
*
* * *
* * * *
* * * * * *
0-9 10-19 20-29 30-39 40-49 50-59 60-69 70-79 80-89 90-100
Hints:
public class GradesHistogram {
public static int[] grades;
// Declare an int array of grades, to be allocated later
public static int[] bins = new int[10];
// Declare and allocate an int array for histogram bins.
// 10 bins for 0-9, 10-19,...., 90-100
public static void main(String[] args) {
readGrades("grades.in");
computeHistogram();
printHistogramHorizontal();
printHistogramVertical();
}
// Read the grades from "filename", store in "grades" array.
// Assume that the inputs are valid.
public static void readGrades(String filename) { ...... }
// Based on "grades" array, populate the "bins" array.
public static void computeHistogram() { ....... }
// Print histogram based on the "bins" array.
public static void printHistogramHorizontal() { ...... }
// Print histogram based on the "bins" array.
public static void printHistogramVertical() { ...... }
}
Comparing Two Numbers
This is a very simple example of Java that teaches you the method of comparing two numbers and finding out the greater one. First of all, name a class "Comparing" and take two numbers in this class. Here we have taken a=24 and b=25, now we have to find out whether a=b, a>b or b>a. To find out this apply if and else condition one by one. Now apply the condition "if (a=b)", if this satisfies then type that both are equal in the system class. If this doesn't satisfy, then check whether a>b by applying the "else if" condition and type the message "a is greater than b" in the system class. Again this doesn't satisfy then 'else' condition as shown in the example will show that b is greater than a.
Now compile and run the program and you will find the desired output. If you are getting any error then check the whole program thoroughly and surely you will get correct result. By compiling and running this exact program, you will find that b is greater than a.
class Comparing{
public static void main(String[] args) {
int a=24, b=25;
if (a == b){
System.out.println("Both are equal");
}
else if(a>b){
System.out.println("a is greater than b");
}
else{
System.out.println("b is greater than a");
}
}
}
Determining the largest number
Posted on: June 1, 2007 at 12:00 AM
This example of Java programming will teach you the coding for determining the largest number amongst three.
Determining the largest number
This example of Java programming will teach you the coding for determining the largest number amongst three. Here we have taken three integers as x = 500, y = 70 and z = 3000. After defining these three integers under the class "largernumber" apply "if" and "else" conditions that can help you in finding the largest value one by one.
First check if "x>y". If this satisfies then check whether x>z or not. Again if this satisfies then write in the system class that "x is greater". Again the term "else" comes when "x" is not greater than "z". So check again, if "z" is greater than "y" or not. If this satisfies then type in the system class as "z is greater" otherwise (in the else condition) "y" is greater. Now check whether "y" is greater than "z" or not.
If "x" is not greater than "y" as per the first condition, then the condition "else" comes and now you have to check if "y>z" or not. If this satisfies then the output comes as "y is greater".
Don't get confuse and analyze every condition one by one and follow this example.
Here is the code of program:
class largernumber{
public static void main(String[] args) {
int x=500, y=70, z=3000;
if (x>y){
if (x>z){
System.out.println("x is greater");
}
else{
if(z>y){
System.out.println("z is greater");
}
else{
System.out.println("y is greater");
}
}
}
else{
if (y>z){
System.out.println("y is greater");
}
}
}
}
Write a program to list all even numbers between two numbers
Posted on: June 2, 2007 at 12:00 AM
Here you will learn to write a program for listing out all the even numbers between two numbers.
Write a program to list all even numbers between two numbers
Java Even Numbers - Even Numbers Example in Java:
Here you will learn to write a program for listing out all the even numbers between two numbers. For this first create a class named AllEvenNum under the java.io package. Now use the try/catch exception to avoid any kind of input error. After this create a buffer class in which all the input data are stored and modified. Then give message as to "Enter number" in the System method.
As we have to find out all the even numbers between 1 and the input number, define an integer variable 'num'. Now apply ParseInt method that parses the string character into decimal integer. Again apply for loop in which define an integer i=1 and i<= num also with an increment operator. Then apply the if condition that i/2=0 i.e. to find even numbers which are divided by the integer 2. In the end apply the catch exception.
Now and compile and run the program, and enter your desired number to get all even numbers between 1 and this numbers.
Here is the code of the program:
import java.io.*;
class AllEvenNum{
public static void main(String[] args) {
try{
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter number : ");
int num = Integer.parseInt(br1.readLine());
System.out.println("Even Numbers:");
for (int i=1;i <=num ; i++){
if(i%2==0 ){
System.out.print(i+",");
}
}
}
catch(Exception e){}
}
}
Write a program to calculate area and perimeter of a circle
Posted on: June 4, 2007 at 12:00 AM
In this section, you will learn to calculate the area and perimeter of a circle.
Write a program to calculate area and perimeter of a circle
The given example will teach you the method for preparing a program to calculate the area and perimeter of a circle. First of all name a class as "CircleArea" under Java I/O package and define and integer r=o, which is the radius of the circle. Now use try exception to handle errors and other exceptional events. As we have to input the value of radius here create a buffered class with an object as 'br1'. This create a buffering character input stream that uses a default sized input buffer. The InputStreamReader here works as a translator that converts byte stream to character stream. Now type message that "Enter radius of circle" in the System.out.println method.
Now use the parseInt() method of the Integer class in order to convert from external numeric format to internal format. Now create the Math class in which all the mathematical functions are defined. This Math class can be imported from the java.lang.* package. Write the program for both the cases: radius and perimeter.
Before ending the program use the Catch mechanism that detects and catch user input errors. In the end compile and run the program and enter your desired value as radius for calculating the radius and perimeter of the circle.
Here is the code of the program:
import java.io.*;
class CircleArea{
public static void main(String[] args){
int r=0;
try{
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Radius of Circle : ");
r = Integer.parseInt(br1.readLine());
double area = java.lang.Math.PI*r*r;
System.out.println("Area of Circle : "+area);
double perimeter =2*java.lang.Math.PI*r ;
System.out.println("Perimeter of Circle : "+perimeter);
}
catch(Exception e){
System.out.println("Error : "+e);
}
}
}
Write a program to calculate factorial of any given number
Posted on: June 4, 2007 at 12:00 AM
This tutorial will teach you the methods for writing program to calculate factorial of any given number.
Factorial Examples - Java Factorial Example to calculate factorial of any given number
This Java programming tutorial will teach you the methods for writing program to calculate factorial of any given number. First of all define a class "Factorial" under the Java I/O package. Java I/O package has a input stream and a output stream in which input stream is used for reading the stream and memory allocating and the output stream is used for writing bytes. As in this program we are going to insert certain instruction by creating buffer reader class, it is necessary to use 'try' and 'catch' block for catching and handling exceptions during execution of the program.
Here, we have to create a buffer for the string class that can be used to instantiate a changeable object for storing and processing a string of character. The strings length and content change as soon as any object is inserted, replaced or removed from the StringBuffer object.
Now create a buffer object that inherits properties from the string object class. Now create an InputStreamReader that reads bytes and decodes them into character by using certain 'charset'. Now use the ParseInt method for converting the parses the string argument to a decimal integer and define 'a' as an integer. Take an integer variable as fact=1 and insert the message in the System method.
Now applying for loop with conditions as integer i=1(intializer), i<=a and i++ as increment operator. So output result will be like fact=fact*i.
Here is the code of the program:
import java.io.*;
class Factorial{
public static void main(String[] args) {
try{
BufferedReader object = new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter the number");
int a= Integer.parseInt(object.readLine());
int fact= 1;
System.out.println("Factorial of " +a+ ":");
for (int i= 1; i<=a; i++){
fact=fact*i;
}
System.out.println(fact);
}
catch (Exception e){}
}
}
Palindrome Number Example in Java
Posted on: June 4, 2007 at 12:00 AM
In this section, you will learn about the palindrome number and how to determine any number is palindrome or not.
Palindrome Number Example in Java
In this section, you will learn about the palindrome number and how to determine any number is palindrome or not. First of all we are going to read about the palindrome number. This is the number that the actual number and after reversing this, in both cases the number is same that is called palindrome number otherwise not. Brief description below:
Description of program:
With the help of this program, we are going to determine whether the given number is palindrome or not. To achieve the desired result, firstly we have to define a class named "Palindrome". After that we will ask the user to enter any integer type number and then we will reverse it. After reversing the number we will check whether the given number is palindrome or not. If the given number is larger, then it will display a message "Out of range!".
Here is the code of this program
import java.io.*;
public class Palindrome {
public static void main(String [] args){
try{
BufferedReader object = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("Enter number");
int num= Integer.parseInt(object.readLine());
int n = num;
int rev=0;
System.out.println("Number: ");
System.out.println(" "+ num);
for (int i=0; i<=num; i++){
int r=num%10;
num=num/10;
rev=rev*10+r;
i=0;
}
System.out.println("After reversing the number: "+ " ");
System.out.println(" "+ rev);
if(n == rev){
System.out.print("Number is palindrome!");
}
else{
System.out.println("Number is not palindrome!");
}
}
catch(Exception e){
System.out.println("Out of range!");
}
}
}
Write a program for calculating area and perimeter of a rectangle
Posted on: February 11, 2008 at 12:00 AM
If you are a newbie in Java programming then our tutorials and examples will be helpful in understanding Java programming in the most simplest way.
Write a program for calculating area and perimeter of a rectangle
If you are a newbie in Java programming then our tutorials and examples will be helpful in understanding Java programming in the most simplest way. Here after reading this lesson, you will be able to write program for calculating the area and perimeter of a rectangle.
First of all create a class named RecArea under Java.io package. Now define two integer variable 'l' and 'w'. As the program will be based on keyboard numerical input, it is important for every programmer to use correct data without any mistake. In this case the exception methods like try/catch mechanism helps in detecting user input errors. So before starting the functional code, enclosed it with try clause so that any error in the statement causes the execution of the catch clauses.
Now create an abstract buffer class which is the super class of all classes and represents a stream of input bytes. The InputSreamReader reads the character stream and stores it in the buffer class. Now use parseInt for both length and width of the rectangle. This is an instance of class method and is used to convert a string to an integer. Define the area as l*w and perimeter as 2*(l+w) and in the end use the catch exception.
Now compile and run the program and input the value as you see the message and get the ultimate result. If you find any kind of error, then check the whole program again.
Here is the code of the program:
import java.io.*;
class RecArea
{
public static void main(String[] args)
{
int l=0;
int w=0;
try{
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter length of rectangle : ");
l = Integer.parseInt(br1.readLine());
System.out.println("Enter width of rectangle : ");
w = Integer.parseInt(br1.readLine());
int area = l*w;
System.out.println("Area of Rectangle : "+area);
int perimiter = 2*(l+w);
System.out.println("Perimeter: " + perimiter);
}catch(Exception e){System.out.println("Error : "+e);}
}
}
Write a program to construct a triangle with the ?*?
Posted on: June 4, 2007 at 12:00 AM
In this section, you will learn how to constructing a shape of triangle by using "*".
Write a program to construct a triangle with the ?*?
This lesson in Java programming will teach you the coding for constructing a shape of triangle by using '*'. First of all make a class named 'triangle' under the Java I/O package and as we have to use the Buffer class, the application of all try and catch block is important for avoiding any kind of error. After creating BufferedReader object and input stream reader define an integer 'a' and apply parseInt method for the conversion of string into integer.
Now apply the for loop and define an integer 'i' and it should be either less than or equal to the integer "a" (the input number). Again define another integer type variable "j" in another for loop. Here in the second for loop "j" the number of times we have to print *.
Now compile and run the program and insert any number on your command window and surely you will get a triangle shape with star *. You can take any other object instead of *.
Here is the code of the program:
import java.io.*;
class triangle{
public static void main(String[] args) {
try{
BufferedReader object = new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter the number");
int a= Integer.parseInt(object.readLine());
for (int i=1; i for (int j=1; j<=i;j++ ){
System.out.print("*");
}
System.out.println("");
}
}
catch(Exception e){}
}
}
Checking whether a year is leap or not
Posted on: February 11, 2008 at 12:00 AM
This tutorial is going to teach you the coding for checking whether a year is a leap year or not.
Checking whether a year is leap or not
This tutorial is going to teach you the coding for checking whether a year is a leap year or not. Here, we have taken the year 2000. So define an integer n=2000 in the class "Leapyear" and now apply "if else" condition. As we know leap year is divided by the integer 4 and so applying if condition as n/4=0, then "n" is a leap year. Now in the System.out.println write the message that the year is a leap year. Again applying "else" condition the output will be that the year is not a leap year.
Here is the code of program:
class Leapyear
{
public static void main(String[] args)
{
int n=2000;
if (n%4==0){
System.out.println("The given year is a leap year");
}
else{
System.out.println("This is not a leap year");
}
}
}
Listing out leap years between certain period
Posted on: February 11, 2008 at 12:00 AM
The programming lesson will teach you the coding for finding and listing out the leap years between two years.
Listing out leap years between certain period
The programming lesson will teach you the coding for finding and listing out the leap years between two years. In the following example we have to find out the leap years between 1990 and 2006. First define the two years under a class "leapyears". Let i = 2006 and n=1990. Now with the help of for loop method initialize the year as n=1990 and n<=i. Also apply the increment statement in the loop as we have to check one by one.
As we know a leap year is divisible by 4, define an integer l=n%4. So if 'n' is divisible by 4 or l=0, then the particular year can be a leap year. For checking this, apply the if statement and if this satisfies then, the year will be a leap year. For listing out each year write "+n" in the System.out.println.
Now compile and run the program in the command window and see the result. If you find any error, check the whole program and find out the
Here is the code of the program:
class leapyears
{
public static void main(String[] args)
{
int i=2006;
int n;
for (n=1990; n<=i ; n++){
int l=n%4;
if (l==0){
System.out.println("leap year: "+n);
}
}
}
}
Preparing table of a number by using loop
Posted on: February 11, 2008 at 12:00 AM
This tutorial will teach you the methods of preparing the table of a given number by using loop condition.
Preparing table of a number by using loop
This tutorial will teach you the methods of preparing the table of a given number by using loop condition. As we know the loop statements are used to repeat a statement or process multiple times according to a specified condition. Loop checks certain condition and if it finds the condition is valuable then all the statements written under loop are executed.
Here we will take a number a=25 of which we have to prepare a table. Define the integer a=25 and b=1 as the initial point. Now apply "while" condition of loop and confine b<=10 as we have to make a table of 25. Again define another integer as c=a*b, this will be the result when we multiply 'a' with 'b'. Here we have to multiply 'a' with 'b' up to 10 times like a*1, a*2....................a*9, a*10. So make define b=b+1 as increment operator.
Now compile and run the program on the command window.
Here is the code of the prorgram:
class PreparingTable{
public static void main(String[] args) {
int a=25, b=1;
System.out.println("the table of "+a+"= ");
while(b<=10){
int c = a*b;
System.out.println(c);
b = b+1;
}
}
}
Prime Number in Java
Posted on: June 4, 2007 at 12:00 AM
In this section, you will learn how to get prime number between 1 to given number.
Prime Number in Java
This Java programming tutorial, we will be read how to get prime number between 1 to given number. First of all we have to define a class "PrimeNumber". Java I/O package has a input stream and a output stream in which input stream is used for reading the stream and memory allocating and the output stream used for writing bytes. As in this program we are going to insert certain instruction by creating buffer reader class. Here we have to create a buffer for the string class that can be used to instantiate a changeable object for storing and processing a string of character. Now use the ParseInt method for converting the parses the string argument and define 'num' as an integer.
Now applying in this program we use two 'for' loop. For loop will start from 1 to entered number. And another loop will start and divide it from 2 to less than those number. If number is divided by any number that means it is not prime otherwise prime number.
Here is the code of the Program
import java.io.*;
class PrimeNumber {
public static void main(String[] args) throws Exception{
int i;
BufferedReader bf = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("Enter number:");
int num = Integer.parseInt(bf.readLine());
System.out.println("Prime number: ");
for (i=1; i < num; i++ ){
int j;
for (j=2; j int n = i%j;
if (n==0){
break;
}
}
if(i == j){
System.out.print(" "+i);
}
}
}
}
OOPs and Its Concepts in Java
Posted on: November 21, 2006 at 12:00 AM
Object Oriented Programming or OOP is the technique to create programs based on the real world.
OOPs and Its Concepts in Java
Brief Introduction to OOP
Object Oriented Programming or OOP is the technique to create programs based on the real world. Unlike procedural programming, here in the OOP programming model programs are organized around objects and data rather than actions and logic. Objects represent some concepts or things and like any other objects in the real Objects in programming language have certain behavior, properties, type, and identity. In OOP based language the principal aim is to find out the objects to manipulate and their relation between each other. OOP offers greater flexibility and compatibility and is popular in developing larger application. Another important work in OOP is to classify objects into different types according to their properties and behavior. So OOP based software application development includes the analysis of the problem, preparing a solution, coding and finally its maintenance.
Java is a object oriented programming and to understand the functionality of OOP in Java, we first need to understand several fundamentals related to objects. These include class, method, inheritance, encapsulation, abstraction, polymorphism etc.
Class - It is the central point of OOP and that contains data and codes with behavior. In Java everything happens within class and it describes a set of objects with common behavior. The class definition describes all the properties, behavior, and identity of objects present within that class. As far as types of classes are concerned, there are predefined classes in languages like C++ and Pascal. But in Java one can define his/her own types with data and code.
Object - Objects are the basic unit of object orientation with behavior, identity. As we mentioned above, these are part of a class but are not the same. An object is expressed by the variable and methods within the objects. Again these variables and methods are distinguished from each other as instant variables, instant methods and class variable and class methods.
Methods - We know that a class can define both attributes and behaviors. Again attributes are defined by variables and behaviors are represented by methods. In other words, methods define the abilities of an object.
Inheritance - This is the mechanism of organizing and structuring software program. Though objects are distinguished from each other by some additional features but there are objects that share certain things common. In object oriented programming classes can inherit some common behavior and state from others. Inheritance in OOP allows to define a general class and later to organize some other classes simply adding some details with the old class definition. This saves work as the special class inherits all the properties of the old general class and as a programmer you only require the new features. This helps in a better data analysis, accurate coding and reduces development time.
Abstraction - The process of abstraction in Java is used to hide certain details and only show the essential features of the object. In other words, it deals with the outside view of an object (interface).
Encapsulation - This is an important programming concept that assists in separating an object's state from its behavior. This helps in hiding an object's data describing its state from any further modification by external component. In Java there are four different terms used for hiding data constructs and these are public, private, protected and package. As we know an object can associated with data with predefined classes and in any application an object can know about the data it needs to know about. So any unnecessary data are not required by an object can be hidden by this process. It can also be termed as information hiding that prohibits outsiders in seeing the inside of an object in which abstraction is implemented.
Polymorphism - It describes the ability of the object in belonging to different types with specific behavior of each type. So by using this, one object can be treated like another and in this way it can create and define multiple level of interface. Here the programmers need not have to know the exact type of object in advance and this is being implemented at runtime.
Related Tags for OOPs and I
Java Exception - Exception Handling in Java
Posted on: June 5, 2007 at 12:00 AM
In this section, you will learn to the exception handling.
Java Exception - Exception Handling in Java
Exception, that means exceptional errors. Actually exceptions are used for handling errors in programs that occurs during the program execution. During the program execution if any error occurs and you want to print your own message or the system message about the error then you write the part of the program which generate the error in the try{} block and catch the errors using catch() block. Exception turns the direction of normal flow of the program control and send to the related catch() block. Error that occurs during the program execution generate a specific object which has the information about the errors occurred in the program.
In the following example code you will see that how the exception handling can be done in java program. This example reads two integer numbers for the variables a and b. If you enter any other character except number ( 0 - 9 ) then the error is caught by NumberFormatException object. After that ex.getMessage() prints the information about the error occurring causes.
Code of the program :
import java.io.*;
public class exceptionHandle{
public static void main(String[] args) throws Exception{
try{
int a,b;
BufferedReader in =
new BufferedReader(new InputStreamReader(System.in));
a = Integer.parseInt(in.readLine());
b = Integer.parseInt(in.readLine());
}
catch(NumberFormatException ex){
System.out.println(ex.getMessage()
+ " is not a numeric value.");
System.exit(0);
}
}
}
Java - Identifier and primitive datatype in java
Posted on: June 4, 2007 at 12:00 AM
In this example you will learn what is identifier and primitive data type of a identifier. This tutorials will teach you how to use these identifier in you java programming.
Java - Identifier and Primitive Data Types in java
In this example you will learn what is identifier and primitive data types of a identifier. This tutorials will teach you how to use these identifier in you java programming. Identifier is is a simple variable name which is defined as the value container. The type of value stored by identifier is defined by the special java keyword is termed as primitive data type.
In the given example there are some identifiers have been used like byteident, shortident, intident, longident, charident, stringident, floatident, doubleident. And there are some primitive data types of used identifiers have been also used in the program like byte, short, int, long, float, double, char and String.
All the data type has it's own capacity to keep the maximum value. Which have been mentioned below :
Primitive Data Types
Keyword Description Size/Format
Integers
byte Byte-length integer 8-bit two's complement
short Short integer 16-bit two's complement
int Integer 32-bit two's complement
long Long integer 64-bit two's complement
Real numbers
float Single-precision floating point 32-bit IEEE 754
double Double-precision floating point 64-bit IEEE 754
Other types
char A single character 16-bit Unicode character
boolean A boolean value (true or false) true or false
Source: http://java.sun.com/docs/books/tutorial/java/nutsandbolts/datatypes.html
Code of the Program :
public class identifierandpdatatype{
public static void main(String[] args){
byte byteident = 3;
short shortident=100;
int intident = 10;
long longident = 40000;
char charident = 'a';
String stringident = "chandan";
float floatident = 12.0045f;
double doubleident = 2333333.000000000033343343434f;
System.out.println(byteident + " is the value of identifire
named 'byteident' which primitive data type is byte.");
System.out.println(shortident + " is the value of
identifire named 'shortident' which primitive data type is short.");
System.out.println(intident + " is the value
of identifire named 'intident' which primitive data type is int.");
System.out.println(longident + " is the value
of identifire named 'longident' which primitive data type is long.");
System.out.println(charident + " is the value
of identifire named 'charident' which primitive data type is char.");
System.out.println(stringident + " is the value
of identifire named 'stringident' which primitive data type is string.");
System.out.println(floatident + " is the value
of identifire named 'floatident' which primitive data type is float.");
System.out.println(doubleident + " is the value
of identifire named 'doubleident' which primitive data type is double.");
}
}
Java - Variable, Constant and Literal in Java
Posted on: June 4, 2007 at 12:00 AM
In this example you will see that how you can use variables, constants and literals in your program easily.
Java - Variable, Constant and Literal in Java
In this example you will see that how you can use variables, constants and literals in your program easily.
Variable : You can assign the values to the variable once it has been declared. The values of the variable can be changed anywhere in the program if the variable is accessible in that scope. In this example we have used the variable intvariable to illustrate this.
Constants: Constants are declared using the final keyword. The values of the constant can't be changed once its declared.
Literal : literal is an explicit number or string constant used in Java programs. This specifies the syntax of your declaration of different types of values and operations. That mean literal is totally based on the syntax. Whenever you want to show the message with java special symbols then you have to use the literals. For example to show the message "Directory of this file : c:\code\varconstltr.java" then you can write as shown below
System.out.println("Directory of this file : c:\\code\\varconstltr.java");
There are three type of literals : Numeric Literals, Char type Literals, String Literals as follows.
Code of the Program :
public class varconstltr{
public static final int constint=5;
public static void main(String[] args){
int intvariable;
for (int i = 0;i <= 10;i++){
intvariable = i;
System.out.println("All the values are : \n intvariable = "
+ intvariable + "\nconstint = " + constint);
}
System.out.println("Directory of this file : c:\\code\\varconstltr.java");
}
}
Java Read File Line by Line - Java Tutorial
Posted on: June 4, 2007 at 12:00 AM
In the section of Java Tutorial you will learn how to write java program to read file line by line. We will use the DataInputStream class to Read text File Line by Line.
Java Read File Line by Line - Java Tutorial
In the section of Java Tutorial you will learn how to write java program to read file line by line. We will use the DataInputStream class to Read text File Line by Line.
Class DataInputStream
A data input stream is use to read primitive Java data types from an underlying input stream in a machine-independent way. An application uses a data output stream to write data that can later be read by a data input stream.
Data input streams and data output streams represent Unicode strings in a format that is a slight modification of UTF-8. (For more information, see X/Open Company Ltd., "File System Safe UCS Transformation Format (FSS_UTF)", X/Open Preliminary Specification, Document Number: P316. This information also appears in ISO/IEC 10646, Annex P.) Note that in the following tables, the most significant bit appears in the far left-hand column.
BufferedReader
Read text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.
The buffer size may be specified, or the default size may be used. The default is large enough for most purposes.
In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream. It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders. For example,
BufferedReader in
= new BufferedReader(new FileReader("foo.in"));
will buffer the input from the specified file. Without buffering, each invocation of read() or readLine() could cause bytes to be read from the file, converted into characters, and then returned, which can be very inefficient.
Programs that use DataInputStreams for textual input can be localized by replacing each DataInputStream with an appropriate BufferedReader.
Here is the code of java program to Read text File Line by Line:
import java.io.*;
class FileRead
{
public static void main(String args[])
{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("textfile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
Java - Copying one file to another
Posted on: June 4, 2007 at 12:00 AM
In this section, you will learn how to copy contents from one file to another file.
Java - Copying one file to another
This example illustrates how to copy contents from one file to another file. This topic is related to the I/O (input/output) of java.io package.
In this example we are using File class of java.io package. The File class is an abstract representation of file and directory pathnames. This class is an abstract, system-independent view of hierarchical pathnames. An abstract pathname has two components:
1. An optional system-dependent prefix string,
such as a disk-drive specifier, "/" for the UNIX root directory, or "\\" for a Win32 UNC pathname, and
2. A sequence of zero or more string names.
Explanation
This program copies one file to another file. We will be declaring a function called copyfile which copies the contents from one specified file to another specified file.
copyfile(String srFile, String dtFile)
The function copyfile(String srFile, String dtFile) takes both file name as parameter. The function creates a new File instance for the file name passed as parameter
File f1 = new File(srFile);
File f2 = new File(dtFile);
and creates another InputStream instance for the input object and OutputStream instance for the output object passed as parameter
InputStream in = new FileInputStream(f1);
OutputStream out = new FileOutputStream(f2);
and then create a byte type buffer for buffering the contents of one file and write to another specified file from the first one specified file.
// For creating a byte type buffer
byte[] buf = new byte[1024];
// For writing to another specified file from buffer buf
out.write(buf, 0, len);
Code of the Program :
import java.io.*;
public class CopyFile{
private static void copyfile(String srFile, String dtFile){
try{
File f1 = new File(srFile);
File f2 = new File(dtFile);
InputStream in = new FileInputStream(f1);
//For Append the file.
// OutputStream out = new FileOutputStream(f2,true);
//For Overwrite the file.
OutputStream out = new FileOutputStream(f2);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0){
out.write(buf, 0, len);
}
in.close();
out.close();
System.out.println("File copied.");
}
catch(FileNotFoundException ex){
System.out.println(ex.getMessage() + " in the specified directory.");
System.exit(0);
}
catch(IOException e){
System.out.println(e.getMessage());
}
}
public static void main(String[] args){
switch(args.length){
case 0: System.out.println("File has not mentioned.");
System.exit(0);
case 1: System.out.println("Destination file has not mentioned.");
System.exit(0);
case 2: copyfile(args[0],args[1]);
System.exit(0);
default : System.out.println("Multiple files are not allow.");
System.exit(0);
}
}
}
Java Write To File - Java Tutorial
Posted on: June 5, 2007 at 12:00 AM
In the section of Java Tutorial you will learn how to write java program to write to a file.
Java Write To File - Java Tutorial
In the section of Java Tutorial you will learn how to write java program to write to a file. We will use the class FileWriter and BufferedWriter to write to a file.
Class FileWriter
The FileWriter is a class used for writing character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable. To specify these values yourself, construct an OutputStreamWriter on a FileOutputStream.
BufferedWriter
The BufferWriter class is used to write text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.
Here is the code of java program to write text to a file:
import java.io.*;
class FileWrite
{
public static void main(String args[])
{
try{
// Create file
FileWriter fstream = new FileWriter("out.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write("Hello Java");
//Close the output stream
out.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
Java Create Directory - Java Tutorial
Posted on: June 4, 2007 at 12:00 AM
In the section of Java Tutorial you will learn how to create directory using java program.
Java Create Directory - Java Tutorial
In the section of Java Tutorial you will learn how to create directory using java program. This program also explains the process of creating all non-existent ancestor directories automatically. We will use the class File class to crate the directory.
Class File
The File class an abstract representation of file and directory pathnames. File class is used to interact with the files system.
Here is the code for creating directory and all non-existing ancestor directories:
import java.io.*;
class CreateDirectory
{
public static void main(String args[])
{
try{
String strDirectoy ="test";
String strManyDirectories="dir1/dir2/dir3";
// Create one directory
boolean success = (
new File(strDirectoy)).mkdir();
if (success) {
System.out.println("Directory: "
+ strDirectoy + " created");
}
// Create multiple directories
success = (new File(strManyDirectories)).mkdirs();
if (success) {
System.out.println("Directories: "
+ strManyDirectories + " created");
}
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
Java - Deleting the file or Directory
Posted on: June 4, 2007 at 12:00 AM
This example illustrates how to delete the specified file or directory after checking weather the file exists or not.
Java - Deleting the file or Directory
This example illustrates how to delete the specified file or directory after checking weather the file exists or not. This topic is related to the I/O (input/output) of java.io package.
In this example we are using File class of java.io package. The File class is an abstract representation of file and directory pathnames.
Explanation
This program deletes the specified file if that exists. We will be declaring a function called deletefile which deletes the specified directory or file.
deletefile(String file)
The function deletefile(String file) takes file name as parameter. The function creates a new File instance for the file name passed as parameter
File f1 = new File(file);
and delete the file using delete function f1.delete(); which return the Boolean value (true/false). It returns true if and only if the file or directory is successfully deleted; false otherwise.
delete()
Deletes the file or directory denoted by this abstract pathname. If this pathname denotes a directory, then the directory must be empty in order to be deleted.
Returns:
true if and only if the file or directory is successfully deleted; false otherwise
Code of the Program :
import java.io.*;
public class DeleteFile{
private static void deletefile(String file){
File f1 = new File(file);
boolean success = f1.delete();
if (!success){
System.out.println("Deletion failed.");
System.exit(0);
}else{
System.out.println("File deleted.");
}
}
public static void main(String[] args){
switch(args.length){
case 0: System.out.println("File has not mentioned.");
System.exit(0);
case 1: deletefile(args[0]);
System.exit(0);
default : System.out.println("Multiple files are not allow.");
System.exit(0);
}
}
}
Java Directory - Directory and File Listing Example in Java
Posted on: June 4, 2007 at 12:00 AM
In this section,you will learn how to list files and folders present in the specified directory.
Java Directory - Directory and File Listing Example in Java
This example illustrates how to list files and folders present in the specified directory. This topic is related to the I/O (input/output) of java.io package.
In this example we are using File class of java.io package. The File class is an abstract representation of file and directory pathnames. This class is an abstract, system-independent view of hierarchical pathnames. An abstract pathname has two components:
1. An optional system-dependent prefix string,
such as a disk-drive specifier, "/" for the UNIX root directory, or "\\" for a Win32 UNC pathname, and
2. A sequence of zero or more string names.
Explanation
This program list the file of the specified directory. We will be declaring a function called dirlist which lists the contents present in the specified directory.
dirlist(String fname)
The function dirlist(String fname) takes directory name as parameter. The function creates a new File instance for the directory name passed as parameter
File dir = new File(fname);
and retrieves the list of all the files and folders present in the directory by calling list() method on it.
String[] chld = dir.list();
Then it prints the name of files and folders present in the directory.
Code of the Program :
import java.io.*;
public class DirListing{
private static void dirlist(String fname){
File dir = new File(fname);
String[] chld = dir.list();
if(chld == null){
System.out.println("Specified directory does not exist or is not a directory.");
System.exit(0);
}else{
for(int i = 0; i < chld.length; i++){
String fileName = chld[i];
System.out.println(fileName);
}
}
}
public static void main(String[] args){
switch(args.length){
case 0: System.out.println("Directory has not mentioned.");
System.exit(0);
case 1: dirlist(args[0]);
System.exit(0);
default : System.out.println("Multiple files are not allow.");
System.exit(0);
}
}
}
Java - Applet Hello World
Posted on: June 4, 2007 at 12:00 AM
This example introduces you with the Applet in Java. You will learn how to develop applet code and run in the browser.
Java - Applet Hello World
This example introduces you with the Applet in Java. You will learn how to develop applet code and run in the browser.
Applet is a program provided by java which is designed for execution within the web browser. Applets are mostly used for a small internet and intranet applications because of small size and it's compatibility among almost all web browsers. Applets are also very secure. For example, Applets can be used to serve animated graphics on the web.
This example creates a simple applet that displays Hello World message.
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class HelloWorldApplet extends Applet{
public static void main(String[] args){
Frame frame = new Frame("Roseindia.net");
frame.setSize(400,200);
Applet app = new HelloWorldApplet();
frame.add(app);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public void paint(Graphics g){
g.drawString("Hello World!",200,100);
}
}
Compiling Applets:
javac HelloWorldApplet.java
Running Applet from console:
java HelloWorldApplet
Running Applet from Web browser:
Running applet in browser is very easy job, create an html file with the following code:
The Applet tag in html is used to embed an applet in the web page.