02-Fundamentals of JAVA - Writing Simple Programs
02-Fundamentals of JAVA - Writing Simple Programs
Fundamentals of Java
Writing Simple Programs
ZEYAD ALI [email protected]
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
First Java Program
First Program in Java: Printing a Line of Text
First Program in Java: Printing a Line of Text
Commenting Your Programs
• // Fig. 2.1: Welcome1.java
• // indicates that the line is a comment.
• Used to document programs and improve their readability.
• Compiler ignores comments.
• A comment that begins with // is an end-of-line comment
• Traditional comment, can be spread over several lines as in
• /* This is a traditional comment. It
can be split over multiple lines */
• This type of comment begins with /* and ends with */.
• All text between the delimiters is ignored by the compiler.
First Program in Java: Printing a Line of Text
Using Blank Lines
• Blank lines, space characters and tabs
• Make programs easier to read.
• Together, they’re known as white space (or whitespace).
• White space is ignored by the compiler.
• Used to document programs and improve their readability.
First Program in Java: Printing a Line of Text
Declaring a class
• Class declaration
Class Body
• A left brace, {, begins the body of every class declaration.
• A corresponding right brace, }, must end each class declaration.
First Program in Java: Printing a Line of Text
System.out object
• Standard output object.
• Allows a Java application to display information in the command window from which it executes.
System.out.println method
• Displays (or prints) a line of text in the command window.
• The string in the parentheses the argument to the method.
• Positions the output cursor at the beginning of the next line in the
command window.
• Most statements end with a semicolon.
First Program in Java: Printing a Line of Text
Compiling Your First Java Application
• To compile the program, type
javac Welcome1.java
• If the program contains no compilation errors, preceding command creates
a.class file (known as the class file) containing the platform-independent
Java bytecodes that represent the application.
• When we use the java command to execute the application on a given
platform, these bytecodes will be translated by the JVM into instructions
that are understood by the underlying operating system.
First Program in Java: Printing a Line of Text
Executing the Welcome1 Application
• To execute this program in a command window, change to the directory
containing Welcome1.java
• C:\examples\ch02\fig02_01 on Microsoft Windows or
• ~/Documents/examples/ch02/fig02_01 on Linux/macOS.
0x003
Output
Identifiers
• Identifiers are programmer-defined names for:
• Classes , variables , methods
• Identifiers may not be any of the Java reserved keywords.
• Identifiers must follow certain rules, it may only contain:
• letters a–z or A–Z,
• the digits 0–9,
• underscores (_), or
• the dollar sign ($)
• The first character may not be a digit.
• Identifiers are case sensitive.
• itemsOrdered is not the same as itemsordered.
• Identifiers cannot include spaces.
Variable Names
• Variable names should be descriptive.
• Descriptive names allow the code to be more readable; therefore, the code
is more maintainable.
• Which of the following is more descriptive?
double tr = 0.0725;
double salesTaxRate = 0.0725;
• Java programs should be self-documenting.
Java Naming Conventions
• Variable names should begin with a lower case letter and then switch to
title case thereafter:
• Ex: int caTaxRate
• Class names should be all title case.
• Ex: public class BigLittle
• More Java naming conventions can be found at:
• http://java.sun.com/docs/codeconv/html/CodeConventions.doc8.html
Primitive Data Types
Primitive Data Types
• Primitive data types are built into the Java language and are not derived
from classes. There are 8 Java primitive data types.
Variable Declarations
• Variable Declarations take the following form:
• DataType VariableName;
byte inches;
short month;
int speed;
long timeStamp;
float salesCommission;
double distance;
Integer Data Types
• byte, short, int, and long are all integer data types.
• They can hold whole numbers such as 5, 10, 23, 89, etc.
• Integer data types cannot hold numbers that have a decimal point in them.
Floating Point Data Types
• Data types that allow fractional values are called floating-point numbers.
• 1.7 and -45.316 are floating-point numbers.
• In Java there are two data types that can represent floating-point numbers.
• float - also called single precision (7 decimal points).
• double - also called double precision (15 decimal points).
• They can hold whole numbers such as 5, 10, 23, 89, etc.
• Integer data types cannot hold numbers that have a decimal point in them.
Floating Point Literals
• When floating point numbers are embedded into Java source code they are
called floating point literals.
• The default type for floating point literals is double.
• 29.75, 1.76, and 31.51 are double data types.
• A double value is not compatible with a float variable because of its size
and precision.
float number;
number = 23.5; // Error!
• A double can be forced into a float by appending the letter F or f to the
literal.
float number;
number = 23.5F; // This will work.
Scientific and E Notation
• Floating-point literals can be represented in scientific notation.
47,281.97 == 4.728197 x 104.
• Java uses E notation to represent values in scientific notation.
4.728197X104 == 4.728197E4.
0000000001000001 0000000001000011
Variable Assignment and Initialization
• In order to store a value in a variable, an assignment statement must be
used. The assignment operator is the equal (=) sign.
• Left side of the assignment operator must be a variable name.
• Right side must be either a literal or expression that evaluates to a
type that is compatible with the type of the variable.
Trying to use uninitialized variables will generate a Syntax Error when the code is compiled.
Arithmetic Operations
Arithmetic Operators
• Finding a Character in a String: The indexOf() method returns the index (the position) of the first
occurrence of a specified text in a string (including whitespace):
// Numerical input
int age = myObj.nextInt(); // integer input
double salary = myObj.nextDouble(); //double input
String name;
name = JOptionPane.showInputDialog("Enter your name.");
• The argument passed to the method is the message to display.
• If the user clicks on the OK button, name references the string entered by
the user. If the user clicks on the Cancel button, name references null.
The System.exit Method
• A program that uses JOptionPane does not automatically stop executing when
the end of the main method is reached.
• Java generates a thread, which is a process running in the computer, when a
JOptionPane is created.
• If the System.exit method is not called, this thread continues to execute.
• The System.exit method requires an integer argument: System.exit(0);
• This argument is an exit code that is passed back to the operating system.
• This code is usually ignored, however, it can be used outside the program to
indicate whether the program ended successfully or as the result of a
failure.
• The value 0 traditionally indicates that the program ended successfully.
Converting a String to a Number
• The JOptionPane’s showInputDialog method always returns the user's input as
a String
• A String containing a number, such as “127.89, can be converted to a numeric
data type.
• Each of the numeric wrapper classes, (covered in Chapter 10) has a method
that converts a string to a number.
• The Integer class has a method that converts a string to an int,
• The Double class has a method that converts a string to a double, and etc.
• These methods are known as parse methods because their names begin with the
word “parse.”
The Parse Methods
// Store 1 in bVar.
byte bVar = Byte.parseByte("1");
// Store 10 in sVar.
short sVar = Short.parseShort("10");
Reading doubles:
double price;
String str;
str = JOptionPane.showInputDialog(
"Enter the retail price.");
price = Double.parseDouble(str);
Example-6: Payroll Calculation Using Dialogs
package simple;
import javax.swing.JOptionPane;
public class InputOutputDialog {