Advance Computer Programming
By
Hasnat Ali
JAVA
Elementary Programming
Contents
To obtain input from the console using the Scanner class
To obtain input using the JOptionPane input dialog boxes
To use identifiers to name variables, constants, methods, and
classes
To use constants to store permanent data
To declare Java primitive data types: byte, short, int, long, float,
double, and char
To use Java operators to write numeric expressions
To use short hand operators
To cast value of one type to another type
To represent a string using the String type
Input Methods
Here are two ways of obtaining input.
Using the Scanner class (console input)
Using JOptionPane input dialogs
Reading Input from Console
Create a Scanner object
Scanner input = new Scanner(System.in);
Use the methods next(), nextLine(), nextByte(), nextShort(),
nextInt(), nextLong(), nextFloat(), nextDouble(), or
nextBoolean() to obtain to a string, byte, short, int, long, float,
double, or boolean value. For example,
System.out.print("Enter a double value: ");
Scanner input = new Scanner(System.in);
double d = input.nextDouble();
Char c = input.next().charAt(0);
Reading Input from Console
import java.util.Scanner; // Scanner is in java.util
public class TestScanner {
public static void main(String args[]) {
// Create a Scanner
Scanner input = new Scanner(System.in);
// Prompt the user to enter a double value
System.out.print("Enter a double value: ");
double doubleValue = input.nextDouble();
System.out.println("Entered value is "+ doubleValue);
// Prompt the user to enter a string
System.out.print("Enter a string without space: ");
String string = input.next();
System.out.println("You entered the string " + string);
}
}
Reading Input from Input Dialog Box
String input = JOptionPane.showInputDialog("Enter an input");
Reading Input from Input Dialog Box
String string = JOptionPane.showInputDialog(null, “Prompting Message”,
“Dialog Title”, JOptionPane.QUESTION_MESSAGE);
Reading Input from GUI (using JOptionPane)
import javax.swing.JOptionPane;
public class Test {
public static void main(String args[]) {
// Obtain input
String val = JOptionPane.showInputDialog(null, “Enter Value”);
// Converting into integer
int intValue = Integer.parseInt(val);
// calculating square
int square = intValue * intValue;
String output = “The Square = ” + square;
JOptionPane.showMessageDialog(null, output);
}
}
Two ways to invoke the Method
There are several ways to use the showInputDialog method. For the time
being, you only need to know two ways to invoke it.
One is to use a statement as shown in the example:
JOptionPane.showInputDialog(null, x, y, JOptionPane.QUESTION_MESSAGE);
where x is a string for the prompting message, and y is a string for the
title of the input dialog box.
The other is to use a statement like this:
JOptionPane.showInputDialog(x);
where x is a string for the prompting message.
Converting String to Integer/Double
To convert a string into an int value, you can use the static
parseInt method in the Integer class as follows:
int intValue = Integer.parseInt(intString);
where intString is a numeric string such as “123”.
To convert a string into a double value, you can use the
static parseDouble method in the Double class as follows:
double doubleValue =Double.parseDouble(doubleString);
where doubleString is a numeric string such as “123.45”.
GUI Displaying Text
import javax.swing.JOptionPane;
public class Welcome {
public static void main(String[] args) {
// Display Welcome to Java! in a message dialog box
JOptionPane.showMessageDialog(null,"Welcome to Java!");
}
}
GUI Displaying Text
import javax.swing.JOptionPane;
public class Test {
public static void main(String[] args) {
// Display Welcome to Java! in a message dialog box
JOptionPane.showMessageDialog(null,"Welcome to Java!",
"Display Message", JOptionPane.INFORMATION_MESSAGE);
}
}
GUI Displaying Text
import javax.swing.JOptionPane;
public class Test {
public static void main(String[] args) {
// Display Welcome to Java! in a message dialog box
JOptionPane.showMessageDialog(null,"Welcome to Java!", "Error
Display Message", JOptionPane.ERROR_MESSAGE);
}
}
Others to use
WARNING_MESSAGE
QUESTION_MESSAGE
PLAIN_MESSAGE
GUI Displaying Text
import javax.swing.JOptionPane;
public class Test {
public static void main(String[] args) {
double d = 7.0;
JOptionPane.showMessageDialog(null, "Value of d = " + d ,
"My Message", JOptionPane.INFORMATION_MESSAGE);
}
}
Identifier
An identifier is a sequence of characters that consist of
letters, digits, underscores ( _ ), and dollar signs ($).
It cannot start with a digit.
An identifier cannot be a reserved word.
An identifier cannot be true, false, or null.
An identifier can be of any length.
Constants
Syntax:
final datatype CONSTANTNAME = VALUE;
Example:
final double PI = 3.14159;
final int SIZE = 3;
Numerical Data Types
Numerical Data Types
Name Range Storage Size
byte –27 (-128) to 27–1 (127) 8-bit signed
short –215 (-32768) to 215–1 (32767) 16-bit signed
int –231 (-2147483648) to 231–1 (2147483647) 32-bit signed
long –263 to 263–1 64-bit signed
(i.e., -9223372036854775808
to 9223372036854775807)
float Negative range: 32-bit IEEE 754
-3.4028235E+38 to -1.4E-45
Positive range:
1.4E-45 to 3.4028235E+38
double Negative range: 64-bit IEEE 754
-1.7976931348623157E+308 to
-4.9E-324
Positive range:
4.9E-324 to 1.7976931348623157E+308
Numerical Operators
Name Meaning Example Result
+ Addition 34 + 1 35
- Subtraction 34.0 – 0.1 33.9
* Multiplication 300 * 30 9000
/ Division 1.0 / 2.0 0.5
% Remainder 20 % 3 2
Integer Division
5 / 2 yields an integer 2.
5.0 / 2 yields a double value 2.5
5 % 2 yields 1 (the remainder of the division)
Number Literals
A literal is a constant value that appears directly in
the program. For example, 34, 1,000,000, and 5.0 are
literals in the following statements:
int i = 34;
long x = 1000000;
double d = 5.0;
Integer Literals
An integer literal can be assigned to an integer variable as
long as it can fit into the variable. A compilation error would
occur if the literal were too large for the variable to hold.
For example, the statement byte b = 1000 would cause a
compilation error, because 1000 cannot be stored in a
variable of the byte type.
An integer literal is assumed to be of the int type, whose
value is between -231 (-2147483648) to 231–1 (2147483647).
To denote an integer literal of the long type, append it with
the letter L or l. L is preferred because l (lowercase L) can
easily be confused with 1 (the digit one).
Floating-point Literals
Floating-point literals are written with a decimal
point. By default, a floating-point literal is treated
as a double type value.
For example, 5.0 is considered a double value, not a
float value. You can make a number a float by
appending the letter f or F, and make a number a
double by appending the letter d or D. So, you can
use 100.2f or 100.2F for a float number, and 100.2d
or 100.2D for a double number.
Scientific Notation
Floating-point literals can also be specified in
scientific notation, for example, 1.23456e+2,
same as 1.23456e2, is equivalent to 123.456, and
1.23456e-2 is equivalent to 0.0123456.
E (or e) represents an exponent and it can be
either in lowercase or uppercase.
How to evaluate an expression?
Though Java has its own way to evaluate an expression
behind the scene, the result of a Java expression and its
corresponding arithmetic expression are the same.
3 + 4 * 4 + 5 * (4 + 3) - 1
(1) inside parentheses first
3 + 4 * 4 + 5 * 7 – 1
(2) multiplication
3 + 16 + 5 * 7 – 1
(3) multiplication
3 + 16 + 35 – 1
(4) addition
19 + 35 – 1
(5) addition
54 - 1
(6) subtraction
53
Shortcut Assignment Operators
Operator Example Equivalent
+= i += 8 i=i+8
-= f -= 8.0 f = f - 8.0
*= i *= 8 i=i*8
/= i /= 8 i=i/8
%= i %= 8 i=i%8
Increment and Decrement Operators
Operator Name Description
++var preincrement The expression (++var) increments var by 1 and evaluates
to the new value in var after the increment.
var++ postincrement The expression (var++) evaluates to the original value
in var and increments var by 1.
--var predecrement The expression (--var) decrements var by 1 and evaluates
to the new value in var after the decrement.
var-- postdecrement The expression (var--) evaluates to the original value
in var and decrements var by 1.
Type Casting
Implicit casting
double d = 3; (type widening)
Explicit casting
int i = (int)3.0; (type narrowing)
int i = (int)3.9; (Fraction part is truncated)
What is wrong? int x = 5 / 2.0;
range increases
byte, short, int, long, float, double
Character Data Type
Four hexadecimal digits.
char letter = 'A'; (ASCII)
char numChar = '4'; (ASCII)
char letter = '\u0041'; (Unicode)
char numChar = '\u0034'; (Unicode)
NOTE: The increment and decrement operators can also be
used on char variables to get the next or preceding Unicode
character. For example, the following statements display
character b.
char ch = 'a';
System.out.println(++ch);
Escape Sequence for Special Characters
Description Escape Sequence Unicode
Backspace \b \u0008
Tab \t \u0009
Linefeed \n \u000A
Carriage return \r \u000D
Backslash \\ \u005C
Single Quote \' \u0027
Double Quote \" \u0022
The String Type
The char type only represents one character. To represent
a string of characters, use the data type called String. For
example,
String message = "Welcome to Java";
String is actually a predefined class in the Java library just
like the System class.
The String type is not a primitive type. It is known as a
reference type. Any Java class can be used as a reference
type for a variable.
String Concatenation
// Three strings are concatenated
String s = "Welcome " + "to " + "Java";
// String Chapter is concatenated with number 2
String s = "Chapter" + 2;
// String Supplement is concatenated with character B
String s = "Supplement" + 'B';
For Each Loop
public class Test{
public static void main(String args[]) {
int arr[] = {11, 33, 88, 90};
for(int i : arr)
System.out.println(i);
}
}
public class Test{
public static void main(String args[]) {
String arr[] = {"aa", "bb", "cc"};
for(String i : arr)
System.out.println(i);
}
}
Arrays in Java
Declaring Array:
double nums[]; OR double[] nums;
Initializing/Instantiating Array:
double[] nums = { 2.0, 4.0, 6.0};
OR
double[] nums = new double[3];
nums[0] = 2.0;
nums[1] = 4.0;
nums[2] = 6.0;
OR
double[] nums = new double[] { 2.0, 4.0, 6.0};
Arrays in Java
Declaring Array:
String str[]; OR String[] str;
Initializing/Instantiating Array:
String[] names = { “John", “Jacob", “Joseph" };
OR
String[] names = new String[3];
names[0] = "John";
names[1] = "Jacob";
names[2] = “Joseph";
OR
String[] names = new String[] {“John", "Jacob", “Joseph" };
Multi-Dimensional Arrays in Java
Declaring Array:
int[ ][ ] aryNumbers = new int[2][3];
Initializing/Instantiating Array:
aryNumbers[0][0] = 10;
aryNumbers[0][1] = 12;
aryNumbers[0][2] = 43;
aryNumbers[1][0] = 11;
aryNumbers[1][1] = 22;
aryNumbers[1][2] = 1;
Multi-Dimensional Arrays in Java
Declaring Array:
int[ ][ ] aryNumbers = new int[6][5];
Initializing/Instantiating Array:
aryNumbers[0][0] = 10;
aryNumbers[0][1] = 12;
aryNumbers[0][2] = 43;
aryNumbers[0][3] = 11;
aryNumbers[0][4] = 22;
aryNumbers[1][3] = 1;
aryNumbers[1][4] = 33;
Multi-Dimensional Arrays in Java
Declaring Array:
double[][][] numbers = new double[1][2][4];
Initializing/Instantiating Array:
numbers[0][0][0] = 12.44;
numbers[0][0][1] = 525.38;
numbers[0][0][2] = -6.28;
numbers[0][0][3] = 2448.32;
numbers[0][1][0] = 632.04;
numbers[0][1][1] = -378.05;
numbers[0][1][2] = 48.14;
numbers[0][1][3] = 634.18;
Programming Style and Documentation
Appropriate Comments
Naming Conventions
Proper Indentation and Spacing Lines
Block Styles
Appropriate Comments
Include a summary at the beginning of the
program to explain what the program does, its
key features, its supporting data structures, and
any unique techniques it uses.
Include your name, class section, instructor,
date, and a brief description at the beginning of
the program.
Naming Convention
Choose meaningful and descriptive names
Variables and method names:
– Use lowercase. If the name consists of several
words, concatenate all in one, use lowercase
for the first word, and capitalize the first letter
of each subsequent word in the name.
– For example, the variables radius and area, and
the method computeArea.
Naming Convention
Class names:
– Capitalize the first letter of each word in the name.
For example, the class name ComputeArea.
Constants:
– Capitalize all letters in constants, and use underscores
to connect words. For example, the constant PI and
MAX_VALUE
Proper Indentation and Spacing
Indentation
– Indent two spaces
Spacing
– Use blank line to separate segments of the code
Block Styles
Use end-of-line style for braces.
Next-line public class Test
style {
public static void main(String[] args)
{
System.out.println("Block Styles");
}
}
End-of-line
style
public class Test {
public static void main(String[] args) {
System.out.println("Block Styles");
}
}