Creating Your First Java Classes
- Features of the Java Programming Language
- Java Program Types
- Saving a Java Class
- Compiling a Java Class
- Running a Java Class
- Modifying a Java Class
Explanations to week content
Adding Comments to a Java Class
There are three types of comments in Java:
Line comments
Starts with two forward slashes ( // ) and continue to the end of the current line. A line comment can appear on a line by itself or at the end (and to the right) of a line following executable code.
e.g
//I am a comment
System.out.println(“This is my first java class”); //A method to output to the screen
Block comments
Starts with a forward slash and an asterisk ( /* ) and end with an asterisk and a forward slash ( */ ). Can be written on multiple lines so far as the comments are between the two starts (/* */)
e.g
/* I am a comment */
System.out.println(“This is my first java class”); /* A method to output to the screen*/
Javadoc comments
Begins with a forward slash and two asterisks ( /** ) and end with an asterisk and a forward slash ( */ ); they are used to generate documentation with a program named javadoc.
Using Constants and Variables
You can categorize data items as constant or variable.A data item is constant when its value cannot be changed while a program is running; a data item is variable when its value might change.
Variable is a named memory location that you can use to store a value. A variable can hold only one value at a time, but the value it holds can change.
Whether a data item is variable or constant, in Java it always has a data type. An item’s data type describes the type of data that can be stored there, how much memory the item occupies, and what types of operations can be performed on the data. Java provides for eight primitive types of data. A primitive type is a simple data type.
Keyword | Description |
---|---|
byte | Byte-length integer |
short | Short integer |
int | Integer |
long | Long integer |
float | Single-precision floating point |
double | Double-precision floating point |
char | A single character |
boolean | A Boolean value (true or false) |
Declaring Variables
A variable declaration is a statement that reserves a named memory location and includes the following:
Variable names:
Variable names conventionally begin with lowercase letters to distinguish them from class Names.
Beginning an identifier with a lowercase letter and capitalizing subsequent words within the identifier is a style known as camel casing. An identifier such as lastName resembles a camel because of the uppercase “hump” in the middle.
Syntax:
Data type variableName;
Explanation:
State the datatype of the variable, leave a space,write the name of the variable and end with a semi colon (;).
Examples:
int myAge;
float salary;
double salary;
Assignment Operator
The = sign is used to assign value to the variables either at declaration or later on.
Examples at declaration:
int myAge = 40;
float salary = 2400;
Assignment After Declaration Examples
int myAge;
myAge = 40;
float salary;
salary = 2400;
If you attempt to display a variable that has not been assigned a value, or use it as part of a
calculation, you receive an error message stating that the variable might not have been
initialized. Java protects you from inadvertently using the unknown value (known as a garbage value) that is stored in an uninitialized variable.
You can declare multiple variables of the same datatype.
Syntax:
datatype variables separated by commas;
Examples
float height, weight;
float height=170, weight = 60;
A named constant can be assigned a value only once,and then it can never be changed.
Usually you initialize a named constant when you declare it; if you do not initialize the constant at declaration, it is known as a blank final,and you can assign a value later. You can assign a value to a final variable only once, and you must assign a value before the variable is used.
Although it is not a requirement, named constants conventionally are given identifiers
using all uppercase letters, using underscores as needed to separate words.
For example, each of the following defines a named constant:
final int NUMBER_OF_DEPARTMENTS = 20;
final double PI = 3.14159;
final double TAX_RATE = 0.015;
final double HOURLY_RATE = 8;
final double ACCELERATION_DUE_TO_GRAVITY = 10;
final string COMPANY = "Kuulchat Media";
Using named constants makes your programs easier to read and understand instead of writing the actual value. For example if anyone sees HOURLY_RATE in your code, the person will surely know that value is for Hourly rate but what if you just write the value 8? Hardly will the person understand what the 8 is for.
The Scope of Variables and Constants
A data item’s scope is the area in which it is visible to a program and in which you can refer to it using its simple identifier. A variable or constant is in scope from the point it is declared until the end of the block of code in which the declaration lies.
Variables which are declared in the curly bracket ({}) of a class can be accessed any where in that class. This type of variable is known as Global variable.
Variables which are declared in a method can only be accessed within the method it is being declared. This type of variable is known as Local variable.
Data Types
The Integer Data Type
In Java, you can use variables of types byte, short,int, and long to store (or hold) integers; an integer is a whole number without decimal places.
The int data type is the most commonly used integer type. A variable of type int can hold any whole number value from –2,147,483,648 to+2,147,483,647. When you assign a value to an int variable, you do not type any commas or periods; you type only digits and an optional plus or minus sign to indicate a positive or negative integer.
The types byte, short, and long are all variations of the integer type. The byte and short types occupy less memory and can hold only smaller values; the long type occupies more memory and can hold larger values.
Type | Minimum Value | Maximum Value | Size in Bytes |
---|---|---|---|
byte | −128 | 127 | 1 |
short | −32,768 | 32,767 | 2 |
int | −2,147,483,648 | 2,147,483,647 | 4 |
long | −9,223,372,036,854,775,808 | 9,223,372,036,854,775,807 | 8 |
It is important to choose appropriate types for the variables you will use in an application. If you attempt to assign a value that is too large for the data type of the variable, the compiler issues an error message and the application does not execute. If you choose a data type that is larger than you need, you waste memory.
Using the boolean Data Type
Boolean logic is based on true-or-false comparisons.Whereas an int variable can hold millions of different values (at different times), a boolean variable can hold only one of two values—true or false.
Examples:
boolean isLastDayOfTheMonth = false;
boolean gameStarted = true;
Floating-Point Data Types
A floating-point number contains decimal positions.Java supports two floating-point data
types: float and double.
A float data type can hold floating-point values of up to six or seven significant digits of accuracy. A double data type requires more memory than a float, and can hold 14 or 15 significant digits of accuracy.
A programmer might choose to store a value as a float instead of a double to save memory.
However, if high levels of accuracy are needed, such as in graphics-intensive software, the programmer might choose to use a double optin for high accuracy over saved memory.
Type | Minimum | Maximum | Size in Bytes |
---|---|---|---|
float | –3.4 * 1038 | 3.4 * 1038 | 4 |
double | –1.7 * 10308 | 1.7 * 10308 | 8 |
Working with the char Data Type
You use the char data type to hold any single character. You place constant character values
within single quotation marks because the computer stores characters and integers
differently. For example, the following are typical character declarations:
char middleInitial = 'M';
char gradeInChemistry = 'A';
char aStar = '*';
char genderInitial = 'F';
A variable of type char can hold only one character. To store a string of characters, such as a person’s name, you must use a data structure called a String. In Java, String is a built-in class that provides you with the means for storing and manipulating character strings. Unlike single characters, which use single quotation marks, string values are written between double quotation marks.
Examples:
String firstName = “Godwin”;
String lastName = “Ashong”;
Performing Arithmetic
Operator | Description | Example |
---|---|---|
+ | Addition | 1+2 = 3 |
- | Subtraction | 1-2 = -1 |
* | Multiplication | 1*2 = 2 |
/ | Division | ½ = 0.5 |
% | Remainder (Modulus) | 5%2 = 1 |
Using the Scanner Class for Keyboard Input
In week 1, you learned about how to display text to the screen using System.out. To get input from a user, you also need to use System.in, which refers to the standard input device (normally the keyboard).
You can use the print() and println() methods to display many data types; for example,
you can use them to display a double, int, or String.The System.in object is not as flexible;
it is designed to read only bytes. That’s a problem, because you often want to accept data of
other types. Fortunately, the designers of Java have created a class named Scanner that makes System.in more flexible.
To create a Scanner object and connect it to the System.in object, you write a statement
similar to the following:
Scanner inputDevice = new Scanner(System.in);
Scanner inputDevice declares an object of the class Scanner with a name chosen by you the programmer.
The portion of the statement to the right of the assignment operator, new Scanner(System.in), creates a Scanner object that is connected to the System.in property.
Use any of these methods below of the Scanner class to retrieve your appropriate data types
Method | Description |
---|---|
nextDouble() | Retrieves input as a double |
nextInt() | Retrieves input as an int |
nextLine() | Retrieves the next line of data and returns it as a String |
next() | Retrieves the next complete token as a String |
To use the Scanner class you will need to import it.
Add this line of code before the class name:
import java.util.Scanner;
Display Text / Data to screen
Joining String
You can join two strings using the + operator.Remember to include empty spaces at the appropriate places in the string be ingjoined.
Examples:
String firstName = “Godwin”;
String lastName = “Ashong”;
String fullName = firstName+lastName;
When fullName variable is displayed, the output willbe GodwinAshong.
In order to leave a space between the first name and the last name, you will need to add a string containing an empty space (barspace) before adding the lastName variable.
Thus fullName can be correctly written as:
fullName = firstName+” “+lastName;
This will output Godwin Ashong when displayed.
You can also join the value of other data types to String variable to form one string.
Example:
int age = 20;
To display Your age is 20 years, the code below could be written
System.out.println(“Your age is “+age+” years”);
NOTE: space is left after the is so that the value of the age will not join the s and another space is also left before the years so that the value of the age will not join the y.Thus so it will not be displayed as Your age is20years.
APPLICATION OF CONCEPTS
Write a program which ask an employee name and the total hours worked in the month. Your program should calculate the salary of the employee and the net income after tax is taken out.
Hourly rate is Ghc 8.00
Tax is 10% of salary
Your Software Application Should Output Similar To This:
************************************
SALARY CALCULATOR
************************************
Enter your name: Godwin Ashong
Enter your staff ID: 2012345
Enter your hours: 2
***********************************
SALARY INFORMATION
***********************************
Employee: Godwin Ashong
Staff ID: 2012345
Working Hours: 2
Hourly Rate: Ghc 8.00
Tax : 10% of salary
Gross Salary : Ghc 16.00
Tax : Ghc 1.6
Net Salary : Ghc 14.4
SAMPLE CODE
//import the Scanner class
import java.util.Scanner;
public class main {
final static int HOURLY_RATE = 8;
final static double TAX_RATE = 10;
public static void main(String[] args) {
// TODO Auto-generated method stub
// Declare variables
String name;
String id;
double hrs,gross_salary,tax,net_salary;
// Display The Application Out
System.out.println("***************************");
System.out.println(" SALARY CALCULATOR ");
System.out.println("***************************");
//Get input from users
Scanner inputDevice = new Scanner(System.in);
//Inform the user to enter his/her name
System.out.println("Enter your name:");
//Get the name of the employee
name = inputDevice.nextLine();
//Consumes the enter key
inputDevice.nextLine();
//Inform user to enter staff id
System.out.println("Enter your staff ID");
//Get the staff id from the keyboard
id = inputDevice.nextLine();
//Consumes the enter key
inputDevice.nextLine();
//Inform the user to enter working hours
System.out.println("Enter your working hours");
hrs = inputDevice.nextDouble();
//Consumes the enter key
inputDevice.nextLine();
//Now do the caclulations
gross_salary = hrs * HOURLY_RATE;
tax = (TAX_RATE/100)*gross_salary;
net_salary = gross_salary - tax;
//Display The Results
System.out.println("***************************");
System.out.println(" SALARY INFORMATION ");
System.out.println("***************************");
System.out.println("Employee : "+name);
System.out.println("Staff ID : "+id);
System.out.println("Working Hours : "+hrs);
System.out.println("Hourly Rate : Ghc"+HOURLY_RATE);
System.out.println("Tax : "+TAX_RATE+"% Of Salary");
System.out.println("Gross Salary : Ghc "+gross_salary);
System.out.println("Tax : Ghc "+tax);
System.out.println("Net Salary : "+net_salary);
}
}
ASSIGNMENT
1.
Write a program that ask a user to enter the radius of a circle. Your program should calculate the circumference and area of the circle and display the result.
2.
Write a program that converts a degree Celsius temperature into a Fahrenheit. The program should ask the user to enter the degree temperature and the Fahrenheit temperature is displayed.
Your program design should look like this:
***********************************************************
DEGREE TO FAHRENHEIT CALCULATOR
***********************************************************
Enter the degree temperature: 35
Temperature in Fahrenheit : 95
Formula : Fahrenheit = (9/5) x degree Celsius + 32;
Francis Ashley
1440 days
Godwin Ashong
The employee was the same as the staff.
The id was taken using the sample code above shown below:
And the staff information was shown using the sample code above shown below:
1440 days
Godwin Ashong
If you meant it wasn't part of the question, then I just added it to the solution for further explanation. Too much of fish doesn't spoil the soup.
1440 days