Loops
The most basic of all looping statements in Java is while. The while statement creates a type of loop that’s called a while loop, which is simply a loop that executes continuously as long as some conditional expression evaluates to true. while loops are useful in all sorts of programming situations, so you use while loops a lot.
The while statement
The basic format of the while statement is like this:
while (expression)
statement
The while statement begins by evaluating the expression. If the expression is true, statement is executed. Then, the expression is evaluated again, and the whole process repeats. If the expression is false, statement is not executed, and the while loop ends.
Note that the statement part of the while loop can either be a single statement or a block of statements contained in a pair of braces. Loops that have just one statement aren’t very useful, so nearly all the while loops you code use a block of statements. (Well, okay, sometimes loops with a single statement are useful. It isn’t unheard of. Just not all that common.)
A counting loop
Here’s a simple program that uses a while loop to print the even numbers from 2 through 20:
public class EvenCounter
{
public static void main(String[] args)
{
int number = 2;
while (number <= 20)
{
System.out.print(number + “ “);
number += 2;
}
System.out.println();
}
}
If you run this program, the following output is displayed:
2 4 6 8 10 12 14 16 18 20
The conditional expression in this program’s while statement is number <= 20. That means the loop repeats as long as the value of number is less than or equal to 20. The body of the loop consists of two statements. The first prints the value of number followed by a space to separate this number from the next one. Then, the second statement adds 2 to number.
The Famous for Loop
In addition to while and do-while loops, Java offers one more kind of loop: the for loop.
The basic principle behind a for loop is that the loop itself maintains a counter variable — that is, a variable whose value is increased each time the body of the loop is executed. For example, if you want a loop that counts from 1 to 10, you’d use a counter variable that starts with a value of 1 and is increased by 1 each time through the loop. Then, you’d use a test to end the loop when the counter variable reaches 10. The for loop lets you set this up all in one convenient statement.
People who majored in Computer Science call the counter variable an iterator.
They do so because they think we don’t know what it means. But we know perfectly well that the iterator is where you put your beer to keep it cold.
The for loop follows this basic format:
for (initialization-expression; test-expression; countexpression)
statement;
The three expressions in the parentheses following the keyword for control how the for loop works. The following paragraphs explain what these three expressions do:
✦ The initialization expression is executed before the loop begins. Usually, you use this expression to initialize the counter variable. If you haven’t declared the counter variable before the for statement, you can declare it here too.
✦ The test expression is evaluated each time the loop is executed to determine whether the loop should keep looping. Usually, this expression tests the counter variable to make sure it is still less than or equal to the value you want to count to. The loop keeps executing as long as this expression evaluates to true. When the test expression evaluates to false, the loop ends.
✦ The count expression is evaluated each time the loop executes. Its job is usually to increment the counter variable.
Here’s a simple for loop that displays the numbers 1 to 10:
public class CountToTen
{
public static void main(String[] args)
{
for (int i = 1; i <= 10; i++)
System.out.println(i);
}
}
This for loop apart has the following pieces:
✦ The initialization expression is int i = 1. This expression declares a variable named i of type int and assigns it an initial value of 1.
✦ The test expression is i <= 10. As a result, the loop continues to execute as long as i is less than or equal to 10.
✦ The count expression is i++. As a result, each time the loop executes, the variable i is incremented.
✦ The body of the loop is the single statement System.out. println(i). As a result, each time the loop executes, the value of the i variable is printed.
If Statements
The if statement is one of the most important statements in any programming language, and Java is no exception. The following sections describe the ins and outs of using the various forms of Java’s powerful if statement.
Simple if statements
In its most basic form, an if statement lets you execute a single statement or a block of statements only if a boolean expression evaluates to true. The basic form of the if statement is this:
if (boolean-expression)
statement
Note that the boolean expression must be enclosed in parentheses. Also, if you use only a single statement, it must end with a semicolon. But the statement can also be a statement block enclosed by braces. In that case, each statement within the block needs a semicolon, but the block itself doesn’t.
Here’s an example of a typical if statement:
double commissionRate = 0.0;
if (salesTotal > 10000.0)
commissionRate = 0.05;
In this example, a variable named commissionRate is initialized to 0.0, and then set to 0.05 if salesTotal is greater than 10,000.
Here’s an example that uses a block rather than a single statement:
double commissionRate = 0.0;
if (salesTotal > 10000.0)
{
commissionRate = 0.05;
commission = salesTotal * commissionRate;
}
In this example, the two statements within the braces are executed if salesTotal is greater than 10000.0. Otherwise, neither statement is executed.
Logical Operators
! Not Returns true if the operand to the right evaluates to
false. Returns false If the operand to the right is true.
& And Returns true if both of the operands evaluate to true.
Both operands are evaluated before the And operator is applied.
I Or Returns true if at least one of the operands evaluates to true.
Both operands are evaluated before the Or operator is applied.
&& Conditional And Same as &, but if the operand on the left returns false,
returns false without evaluating the operand on the right.
II Conditional Or Same as I, but if the operand on the left returns true, returns true without evaluating the operand on the right.
Relational Operators
== Returns true if the expression on the left evaluates to the same value as the right expression.
!= Returns true if the expression on the left does not evaluate to the same value as
the expression on the right.
< Returns true if the expression on the left evaluates to a value that is less than the value of the expression on the right.
<= Returns true if the expression on the left evaluates to a value that is less than or equal to the expression on the right. > Returns true if the expression on the left evaluates to a
value that is greater than the value of the expression on the right.
>= Returns true if the expression on the left evaluates to a
value that is greater than or equal to the expression on the right.
Mathematical Functions
double d = Math.toRadians(27); // Convert 27 degrees to radians
d = Math.cos(d); // Take the cosine
d = Math.sqrt(d); // Take the square root
d = Math.log(d); // Take the natural logarithm
d = Math.exp(d); // Do the inverse: e to the power d
d = Math.pow(10, d); // Raise 10 to this power
d = Math.atan(d); // Compute the arc tangent
d = Math.toDegrees(d); // Convert back to degrees
double up = Math.ceil(d); // Round to ceiling
double down = Math.floor(d); // Round to floor
long nearest = Math.round(d); // Round to nearest
Converting String Input to Numbers Example
Name: Payroll.java
Output: Prints out total salary to the console using JOptionPane and System.out methods
Date: November 23, 2008
Author: Mr. P
*************************************************/
import javax.swing.*;
public class Payroll{ public static void main(String [] args)
{
int numOfHours;
String numOfHours_str;
double hourlyWage, totalSalary;
String hourlyWage_str;
numOfHours_str = JOptionPane.showInputDialog ("How many hours did you work this week?");
numOfHours = Integer.parseInt (numOfHours_str);
hourlyWage_str = JOptionPane.showInputDialog ("What is your hourly wage?");
hourlyWage = Double.parseDouble (hourlyWage_str);
totalSalary = numOfHours * hourlyWage;
JOptionPane.showMessageDialog (null,"Your total salary for this week is: $" +totalSalary);
System.out.println("Your total salary for this week is: $" +totalSalary);
}
}
String Literals
Because strings are such a fundamental data type, Java allows you to include text literally in programs by placing it between double-quote (") characters.
For example:
String name = "David";
System.out.println("Hello, " + name);
The Java Swing Classes
Java’s Swing classes create graphical objects on a computer screen. The objects can include buttons, icons, text fields, check boxes, and other good things that make windows so useful.
The name “Swing” isn’t an acronym. When the people at Sun Microsystems were first creating the code for these classes, one of the developers named it “Swing” because swing music was enjoying a nostalgic revival. And yes, in addition to String and Swing, the standard Java API has a Spring class.
Dialog Boxes
A dialog box is a small graphical window that displays a message to the user or requests input. You can quickly display dialog boxes with the JOptionPane class.
Message Dialog – A dialog box that displays a message; an OK button is also displayed.
Input Dialog – A dialog box that prompts the user for input and provides a text field where input is typed; and OK button and Cancel button are also displayed.
To display message dialogs the showMessageDialog method is used. The following statement calls that method:
JOptionPane.showMessageDialog(null, “Hello Class”);
Example:
String name;
name = JOptionPane.showInputDialog(“Enter your name”);
Converting String Input to Numbers
The JOptionPane class does not have different methods for reading values of different data types. The showInputDialog method always returns the user’s input as String, even if the user enters numeric data. For example if the user enters the number 72 into an input dialog, the showInputDialog method will return the string “72”. This can be a problem if you wish to use the user’s input in a math operation because you can not perform math on strings. In such a case, you must convert the input to a numeric value. To convert a string value to a numeric value, you use one of the methods listed below.
Examples:
1)
int number;
String str;
str = JOptionPane.showInputDialog(“Enter a number.”);
number = Integer.parseInt (str);
2)
double price;
String str;
str = JOptionPane.showInputDialog(“Enter the retail price.”);
price = Double.parseDouble (str);
_____________________________________________________
Group Presentations
November 26th, and 27th, 2008.
Be prepared.
_____________________________________________
Parts Of Program
Name: PartsOfProgram.java
Output: Prints out results of adding two numbers.
Demonstrates different parts of a program.
Author: Mr.P
Date: November 17th, 2008
*********************************************************/
public class PartsOfProgram //Key words (public, class)
{
public static void main (String [] args)
{
int a,b.result; //Programmer defined variables (a,b,result)
a = 10;
b = 20;
result = a + b; //Operators (+, =)
System.out.println ("The result is: " +result);
}
}
______________________________________________
Homework Assignment
1.Open an Gmail account from http://www.google.com/,
2. Using the google account's username and password sign up for blog @ http://www.blogger.com/,
3. Create your new blog for our java class,
4. Send your blog address to Mr.P,
5. Post 5 examples of each primitive data types:
int, double, char, boolean.
6. Post a message to the World embedded in a java program.
____________________________________________________
Variables in Java
Allowing you to use variables that you haven’t explicitly declared might seem like a good idea at first glance. But it’s a common source of bugs that result from misspelled variable names. Java requires that you explicitly declare variables so that if you misspell a variable name, the compiler can detect your mistake and display a compiler error.
The basic form of a variable declaration is this:
type name;
Here are some examples:
int x;
String lastName;
double radius;
In these examples, variables named x, lastName, and radius, are declared. The x variable holds integer values, the lastName variable holds String values, and the radius variable holds double values. int variables can hold whole numbers (like 5, 1,340, and -34), double variables can hold numbers with fractional parts (like 0.5, 99.97, or 3.1415), and String variables can hold text values (like “Hello, World!” or “Jason P. Finch”).
Notice that variable declarations end with a semicolon. That’s because the variable declaration is itself a type of statement.
In short, a variable name can be any combination of letters and numerals, but must start with a letter. Most programmers prefer to start variable names with lowercase letters, and capitalize the first letter of individual words within the name. For example, firstName and salesTaxRate are typical variable names.
Initializing Variables
In Java, local variables are not given initial default values. The compiler checks to make sure that you have assigned a value before you use a local variable.
Examples of Code
/*******************************************************
Name: HelloWorld.java
Output: Prints out "Hello, world!" to the console
Date: May 3, 2006
*******************************************************/
public class HelloWorld
{
public static void main(String [] args)
{
System.out.println("Hello, World!");
}
}
/*******************************************************
Name: PartsOfProgram.java
Output: Prints out result of adding two numbers.
Demonstrates different parts of a program.
Date: May 8, 2006
*******************************************************/
public class PartsOfProgram //Key words(public, class)
{
public static void main (String [] args)
{
int a,b,result; //Programmer-defined variables(a,b,result)
a = 10;
b = 5;
result = a + b; //Operators (+,=)
System.out.println("The result is : "+result); //Punctuation (;)
}
}
__________________________________________
Primitive Data Types in Java
The integer types in Java are byte, short, int, and long. All integral types represent signed numbers;
Example of Primitive int
Code fragment defining, using int variables:
int secondsPerMinute = 60;
int minutesPerHour = 60;
int hoursPerDay =24;
int daysPerWeek =7;
int secondsPerWeek = secondsPerMinute *
minutesPerHour * hoursPerDay * daysPerWeek;
JOptionPane.showMessageDialog(null,
"There are " + secondsPerWeek +
" seconds per week");
int Operation Examples
int i = 5;
int j = 7;
int sumij = i + j; // 12
int diffij = i - j; // -2
int prodij = i * j; // 35
int divij = i / j; // 0
int remij = i % j; // 5
int divji = j / i; // 1
int remji = j % i; // 2
Double Types
Example of Primitive double
Code fragment:
double lbsPerKg = 2.205;
double mPerInch = 0.0254;
double height = 70.5;
double weight = 183.;
double heightMetres = height * mPerInch ;
double bmi = (weight / lbsPerKg) /
(heightMetres * heightMetres); // body mass index
System.out.println("Your body mass index is " + bmi);
double Operation Examples
double x = 5.e20; // 5.e20 = 5 * 1020
double y = 7.0e20;
double sumxy = x + y; // 1.2e21
double diffxy = x - y; // -2.0e20
double prodxy = x * y; // 3.5e41
double divxy = x / y; // .7142857142857143
double remxy = x % y; // 5.0e20
double divxy = y / x; // 1.4
double remxy = y % x; // 2.0e20
The Boolean Type
The Boolean type represents truth values. This type has only two possible values, representing the two Boolean states: on or off, yes or no, true or false. Java reserves the words true and false to represent these two Boolean values.
Example of Primitive boolean
boolean canBeCaught = true;
boolean canBeThrown = false;
What am I?
boolean goesAroundTheWorld = true;
boolean staysInACorner = true;
What am I?
The char Type
The char type represents Unicode characters.
Example of char type
char c = 'A';
________________________________________
Java
Java is an object-oriented programming (OOP) language.
The Java programming language is the language in which Java applications, applets, servlets, and components are written. When a Java program is compiled, it is converted to byte codes that are the portable machine language of a CPU architecture known as the Java Virtual Machine (also called the Java VM or JVM). The JVM can be implemented directly in hardware, but it is usually implemented in the form of a software program that interprets and executes byte codes.
… but it exists only in software!
This Java Virtual Machine takes Java Byte Code instructions one by one. Translates them into machine language for the given platform. Executes the machine language and produces desired results.
The Java Virtual Machine is different for every computer that is, there is one that generates PC
instructions, one that generates Mac instructions, and so on.
It has to be a different virtual machine for each platform as every machine has a different
machine language.
Most web browsers come with the Java Virtual Machine.
Processing Java - Summary
- This Java source code is run through a Java compiler
- The Java compiler doesn’t produce machine language,
but instead produces generic Java Byte Code,
-Java Byte Code is then interpreted by the Java Virtual Machine to produce desired results.
What Is Cyberethics?
Retrieved on November 10th, 2008 from http://higheredbcs.wiley.com/legacy/college/tavani/0471249661/presentation/ch01.ppt
_______________________________________________________
Please click here to send me an e-mail.
_______________________________________________________
Cyberethics
_______________________________________________________
Classroom Project:
The class will be divide into groups of four.
Each group must choose a relevant topic that discusses the ethical behaviour of computing and present on the nature of the topic, the issues students face as they deal with the topic, and the ways in which the topic can be addressed.
Multimedia displays are encouraged.
Each group will present to the class.
Topics to consider:
- Computer crime
- Computer hacking
- Plagiarizing code
- Software piracy
- Virus distribution
- Willful distraction of data
- Environmental issues
- Video-game violence
Requirements:
- Each group will present to the class (10 minutes allowed for presentation, 5 minutes Q&A).
- Each person in the group neds to take responsibility for presenting some portion of the presentation.
- Each group is required to provide a one page handout, available to all students, with a synopsis of the topic presented.
- Each group is required to conduct some background research on the topic.
- Conduct some background research on your topic. Be able to outline the highlights of the subject in terms of:
- Topics significance. Why do you think this is an important issue in the first place? Include peersonal opinions as well as research-supported ideas/statistics.
- The issue that need to be considered (ethical, legal). Think about how the issue has been defined.
- How the topic directly affects students.
Possible ways of presenting the content:
- Microsoft PowerPoint presentation
- Pamphlets
- Collages
- Media articles
- Legal documents
- Lists of resources
_______________________________________________________
Project Groups and Topics
Group 1: Alex, Marcel, Angelus - Video Game Violence
Group 2: Stephanie, Miguel, Connor - Plagiarizing Code
Group 3: Jason, Jessica, Ian - Environmental Issues
Group 4: Matt, Tyler H., Crystal, Mark S. - Software Privacy
Group 5: Kyle C., James, Ben - Computer Hacking
Group 6: Adrian, Blake, Austin, Tyler T. - Data Theft
Group 7: Fiona, Tayler, Srdjan - Computer Crime
Group 8: Dylan, Kyle L., Adam - Virus Distribution
_______________________________________________________