PROGRAMMING WITH JAVA
Java Basics I
By
Samuel K. Opoku
Computer Science Department
Kumasi Technical University
Video Link
[Link]
1
Contents
• Comments
• Creating Identifier
• Keyboard Input
• Input Dialog
COMMENTS
A comment is a bit of text that provides explanations of your code. Comments
are completely ignored by the compiler. Useful for documentation
Java has three basic types of comments: end-of-line, traditional, and
JavaDoc comments
This gives error why?
End-of-line comment: Traditional comment: /*
begins // and ends at the begins with /* and ends int x, y, z;
end of the line. You can */ and can span multiple y = 10;
place it at the end of any lines x = y + /* bad work */ 5;
line. Everything you type Eg 1: /*This is my hello */
after the // is ignored by program for the class*/
the compiler JavaDoc comments: are
Eg 2: sum = x + /*what a actually a special type of
Eg 1: strange comment! */ y; traditional comment that
Sum = x + y; //add 2 nos. you can use to
Note: Must be careful automatically create web
Eg 2: //add 2 nos. with nested comments of based documentation for
Sum = x+y; this type. your programs.
4
2
CREATING IDENTIFIERS
An identifier is a word that one makes up to refer to a Java programming
element by name. Although you can assign identifiers to many different types
of Java elements, they are most commonly used for the following elements:
Classes, methods, variables and fields, parameters
You must follow a few simple rules when you create identifiers:
• Identifiers are case sensitive. Thus SalesTax and salesTax are distinct.
• Identifiers can be made up of upper or lowercase letters, numerals, underscore
characters (_), and dollar signs ($).
• All identifiers must begin with a letter, underscore or a dollar sign. Thus, a15
is a valid identifier, but 13Unlucky is not because it begins with a numeral.
• An identifier cannot be the same as any of the Java keywords
Note: The Java language specification recommends that you avoid using dollar signs
in names you create. Instead, dollar signs are used by code generators to create
identifiers. Thus, avoiding dollar signs helps you avoid creating names that conflict
with generated names. 5
CLASS EXERCISE - IDENTIFIERS
Which of the following is a valid Java identifier:
lowScore
lowScore_
VOID
Main
2BaseHit
Score2
Not!
$cost
_123
A
extends
C:\Temp
x.y.z
6
3
JAVA NAMING CONVENTION
Keywords: All keywords are written in lowercase letters
Package: names always start with lowercase letters.
Example: [Link].*; //discuss more about it latter
Note:
Class: names always start with uppercase letters If a variable name is
Example: Hello composed of multiple
words, then the words are
concatenated together and
Method: names always start with lowercase letters all letters are lowercase
Example: println() except for the letters
that start successive
Variables: names always start with lowercase letters words. Underscore is
usually associated with
Example: sum, doorHeight, bodyTemperature constant definition
Constants: names are always written in uppercase letters with underscores
Example: PI, DOOR_HEIGHT, BODY_TEMPERATURE 7
JAVA ESCAPE SEQUENCE
An escape sequence is special two-character sequence representing
another character What will be the format of the output
Escape Sequence Meaning of the following?
1. [Link](“Hi\nKwame”);
\b Backspace
\n New line 2. [Link](“\”Hi!\t Sweetie\””);
\r Carriage return
3. [Link](“Hi);
\t Tab
\\ Backslash 4. [Link](“Kwame”)
\” Double quote
\’ Single quote 5. [Link](2+5);
6. [Link](“2”+5 );
Soln 1: Soln 3: Soln 4:
Soln 2: Soln 5: Soln 6:
Hi Error: No Error: No
“Hi Sweetie” 7 25
Kwame closing semi-colon (;) | |
|
| quote (”) at the end. 8
4
9
Keyboard Input
10
5
KEYBOARD DATA INPUT (1/6)
• The easy way to get data from console-based Java program is to use
the Scanner class. You can only the scanner class when you are
using JDK 1.5 or later.
• Before you can use the Scanner class in a program, you must
import it. To do that, you code an import statement at the beginning
of the program, before the class declaration as:
import [Link];
• Note that java and util are not capitalized, but Scanner is. If
you’re using other classes in the [Link] package, you can import
the entire package by coding the import statement like this:
import [Link].*;
11
KEYBOARD DATA INPUT (2/6)
• Declaring and Creating the Scanner object: Before you can use
the Scanner class to read input from the console, you must declare a
Scanner variable and create an instance of the Scanner class. I
recommend you create the Scanner variable as a class variable, and
create the Scanner object in the class variable initializer:
static Scanner sc = new Scanner([Link]);
• That way, you can use the sc variable in any method in the class.
• To create a Scanner object, you use the new keyword followed by a
call to the Scanner class constructor. Note that the Scanner class
requires a parameter that indicates the input stream that the
input comes from. We use [Link] here to specify standard
keyboard console input 12
6
KEYBOARD DATA INPUT (3/6)
• Getting input: To read an input value from the user, you can use one of
the methods of the Scanner class that are listed in the table below. As you
can see, the primitive data type has a separate method
• Because these methods read a value from the user and return the value,
you most often use them in statements that assign the value to a variable.
Example: int x = [Link]();
13
EXAMPLE: KEYBOARD DATA INPUT (4/6)
14
7
VARIABLES (1/2)
• A variable is the symbolic name for a memory location whose
contents can be modified during program execution
• In Java, you must explicitly declare all variables before using them
• The basic form of a variable declaration is:
type variableName;
• Examples:
int x;
String lastName; //String starts with upper case letter “S”
double radius;
15
VARIABLES (2/2)
• Declaring two or more variables in one statement. You can declare
two or more variables of the same type in a single statement, by
separating the variable names with commas.
Example: int x, y, z;
• Another form to declare a variable is to assign an initial to it. This is
called initialization
Examples:
int x = 5; //no decimal part
String lastName = “Osei”; //should always be in quote
double radius = 5.0 ; //requires decimal part
int x = 3, y = 5, z = 8;
16
8
CONSTANTS
• A constant is the symbolic name for a memory location whose value cannot be
changed once the program has initialized the location.
• A constant definition normally takes the following form:
final type name = expression ;
The final keyword should always precede constant definition
Examples:
final double KILOGRAMS_PER_POUND = 0.454;
final int MONTHS_IN_A_YEAR = 12;
final double PI = 3.142;
• Java allows several constants to be defined in a single statement by separating the
definitions with commas.
Example
final double DOOR_HEIGHT = 2.00, DOOR_WIDTH = 0.75; 17
MATHEMATICAL FUNCTIONS (1/2)
• The mathematical functions are used in a program by using the Math class.
The format for using the Math class is: [Link](argument)
• Example: To find the square root of 25. The following code is used:
[Link](25.0); // which returns 5.0 as answer
18
9
MATHEMATICAL FUNCTIONS (2/2)
19
20
10
ACCEPTING DATA WITH INPUT DIALOG (1/2)
• You need to import the JOptionPane API using the syntax shown below:
import [Link];
• The purpose of the import statement is to inform the compiler that the
program is using a class that is defined by the Java API called JOptionPane.
• Java API contains thousands of classes. Java groups them into manageable
groups called packages. The package that contains the JOptionPane class is
named [Link].
• You can import all the classes in the [Link] package by using the
syntax: import [Link].*;
• Note: You increase the size of your program when you import classes that
you do not need.
21
ACCEPTING DATA WITH INPUT DIALOG (2/2)
• Note: Many programs use the classes that are contained in the [Link]
package, you do not have to import that package. Instead, those classes are
automatically available to all programs. The System class is defined in the
[Link] package. As a result, you do not have to provide an import
statement to use this class.
• To use the input dialog (as shown below) in your program type the code:
String sInp = [Link](“Enter an integer:”);
• Note: The input dialog accepts String input only. You can however, parse
the String value to get either integer, double or float.
Example: int x = [Link](sInp);
22
11
DISPLAYING MESSAGE WITH MESSAGE DIALOG
• To display a message with JOptionPane, the following syntax is used:
[Link](container, message, title, icon);
Example: [Link](null, “Hello, World!”, “ Greeter”,
JOptionPane.INFORMATION_MESSAGE);
If you don’t want to import [Link] package, you are allow to use the
following for message dialog:
[Link](null, “Hello, World!”,
“Greeter”, JOptionPane.INFORMATION_MESSAGE);
Similar you can also use for following for input dialog
String sInp = [Link](“Enter
an integer:”); 23
Class Exercise
Write Java program to implement the following expression using the Scanner
Class for input and the JOptionPane class for output (comment your work as
practicably as required):
24
12
Class Exercise
Write Java program to implement the following expression using the Scanner
Class for input and the JOptionPane class for output (comment your work as
practicably as required):
25
What if we have a difficult User
• Introducing Validations:
1. Try catch – approach to handle user input errors
Let us go back to all the programs and fix them
2. Validating inputs: (Using if statement)
Work out with division by zero
Let us go back to questions 1-6 and modify them to accept
either negative numbers or positive numbers.
Let the user selects the category to work with.
NB: for programs involving divisions, use double or float
throughout (you can also achieve this by casting the
integer variables) 28
13
Class Exercise Continues
• Write a Java program to evaluate the following:
1. Determine whether a given positive number is
divisible by 2
2. Determine whether a given positive number is
divisible by 2 and 3
3. Determine whether 4 is a factor of a given positive
number
4. A program that determines whether a given
positive number is a prime number, even number
and/or odd number
29
30
14
Mid Semester Exam 1
• List will be provided to you
• Areas: This lecture note
• Rules:
1. You have 10 minutes to solve a programming
question with a computer
2. There are two marks involve: you either get 10 marks for
a good work done or 0 for otherwise
3. Your program should be free from (or be able to handle)
any kind of error (syntax, logical and runtime errors )
31
Assignment 1
• Develop a program called [Link] which is used
to calculate the surface area and volume of the following
figures: cube, cone, cylinder, sphere (Use Scanner class
throughout. Search the internet for the formulas)
• Rules:
1. The user determines the solid figure to work with
2. The user determines whether to find surface area or
volume
3. The user enters the parameters required like radius
and/or height
4. The program calculates and gives an answer
Deadline: TBA
32
15
HIT ANY KEY TO END DAY 2
33
16