(adsbygoogle = window.adsbygoogle || []).push({});
l
l
l
l
l
l
l
l
I will be adding more please be patient
l
l
l
l
l
l
l
Introduction
Hello NGU, Well I found some old notes that I had while I was learning java in school. So I thought I would post some of them here for people that are trying learn java and want understand how certain things work and not just copying and pasting code. I have also have not seen a lot of java based threads on NGU so I hope this will help.
What is Java ?
Java is a programming language and computing platform first released by Sun Microsystems in 1995. It is the underlying technology that powers state-of-the-art programs including utilities, games, and business applications. Java runs on more than 850 million personal computers worldwide, and on billions of devices worldwide, including mobile and TV devices.
- (Sun Microsystems)
Why do we need Java?
There are lots of applications and websites that won't work unless you have Java installed, and more are created every day. Java is fast, secure, and reliable. From laptops to datacenters, game consoles to scientific supercomputers, cell phones to the Internet, Java is everywhere!
- (Sun Microsystems)
Help me out NGU community
Java has many components to it like any other programing language, it would be impossible for me to post everything so if I am missing something that you think is very important to
beginners please,help me out and send me a brief definition and I will post it up and give you
FULL CREDIT.
[multipage=Java Classes/Good Programming Style]
Java Classes/Good Programming
Java Classes
A Java program consists of one or more classes. Each class has a name and must be saved:
- In a separate file with the same name as the class and
- With the file extension .java
For example, a class called MyFirstClass must be saved as MyFirstClass.java.
Java applications must have a main method. (i.e. public static void main (String [] agrs)
Java packages are a group of classes that can help you write programs.
- java.lang — basic language functionality and fundamental types
- java.util — collection data structure classes
- java.io — file operations
- java.math — multiprecision arithmetics
- java.nio — the New I/O framework for Java
- java.net — networking operations, sockets, DNS lookups, ...
- java.security — key generation, encryption and decryption
- java.sql — Java Database Connectivity (JDBC) to access databases
- java.awt — basic hierarchy of packages for native GUI components
- javax.swing — hierarchy of packages for platform-independent rich GUI components
- java.applet — classes for creating an applet
Format of a Java Program
- declare packages used
- declare the name of the class (TitleCase without spaces)
- declare methods
- declare variables
You cannot run a Java class unless it contains a main method.
Good Programming Style
Create a header at the beginning of each program which contains
- your name
- the date
- a brief description of the program
Use comments (i.e. // here is my comment)
Use informative variable names (firstLetterLowerCase without spaces, case sensitive)
Indent
Line up brackets
A Sample JAVA Application
// Name: NGU
// Date: 09/17/2009
// Description: This program outputs Hello, World!
class Greeting
{
public static void main (String [] agrs)
{
// output Hello, World!
System.out.println (“Hello, World!”
;
}
}
References
You must login or register to view this content.
[multipage=Java Output Basics]
Java Output Basics
Println V.S Print
There are 2 methods that can be used to display output: println and print.
For example:
System.out.println(“123456789”
;
System.out.print(“Hello”
;
System.out.println(“
o you see a difference?”
;
The main difference is quite simple println prints on a new line, where as print prints on the same line.
Strings and Numbers (int, double etc)
Java interprets any symbols inside a set of quotation marks (“ ”

as a string/group of characters.
In Java, a whole number is referred to as an int and a decimal number is referred to as a double. To perform mathematical calculations in java you can use the println/print method.
Java follows the rules of BEDMAS:
1st Brackets (…

2nd Division/Multiplication / *
3rd Addition/Subtraction + -
Output Strings and Numbers (at the same time)
You can use the + (plus) operator to display strings and numbers in the same output statement.
For example:
| Code |
Output |
| System.out.println(“The value of 7 x 4 is ” + 7*4); |
The value of 7 x 4 is 28 |
System.out.println(“The value of 7 x 4 is ” + “7*4” ; |
The value of 7 x 4 is 7 * 4 |
| System.out.println(7 + 7); |
14 |
Note: The + sign between two numbers will act as addition.
[multipage=Java Formating Output]
Java Formating Output
Escape Sequence
An escape sequence is a backslash (\) followed by a symbol that together represent a character. Escape sequences are used to display special characters.
More info at:
You must login or register to view this content.
| Escape Sequence |
Description |
Sample Code |
Output |
| \n |
Insert a newline in the text at this point. |
System.out.println(“First line\nnext line.” ); |
First line next line |
| \t |
Insert a tab in the text at this point. |
System.out.println(“Hey\tbob!” ; |
HeyLLLLLbob! |
| \” |
Insert a double quotation in the text at this point. |
System.out.println(“Jason says, \”Hello!\”” ; |
Jason says, “Hello!” |
| \’ |
Insert a single quotation in the text at this point. |
System.out.println(“Someone\’s pen.” ; |
Someone’s pen. |
| \\ |
Insert a slash in the text at this point. |
System.out.println(“This is a \\” ; |
This is a \ |
Formatting Output
You can use format() method to format the display/output.
For example:
System.out.format(“%-8s%8s”, “HELLO”, “WORLD”
;
Output
HELLO WORLD
%[alignment][width]s is a specifier. % indicates the start of a specifier. [alignment] indicates right alignment (nothing) or left alignment (-). [width] indicates the number of character to use for output. “s” indicates that the corresponding argument is a string. Use “d” for integers.
Find out more at: You must login or register to view this content.
Field Width
A field width indicates the number of character positions reserved for outputting an item. You can use field widths to format your output. You may use a System.out.format () with the combination of % to achieve that purpose.
EXAMPLE 1:
System.out.format(“My name is %10s.“, “Cherie”
;
Output: My name is ^^^^Cherie.
EXAMPLE 2:
System.out.format(“%-10s %10s %10s\n“, “Item”, “Quantity”, “Price($)”
;
System.out.format(“%-10s%10d%10.2f\n”, “Book”, 2, 12.3);
System.out.format(“%-10s%10d%10.2f\n”, “Pen”, 12, 5.36);
System.out.format(“%-10s%10d%10.2f\n”, “Gift”, 1, 31);
Note:
s – to display a string
d – to display an integer
f – to display a float
Output:
Item^^^^^^|^^Quantity|^^Price($)
Book^^^^^^|^^^^^^^^^2|^^^^^12.30
Pen^^^^^^^|^^^^^^^^12|^^^^^^5.36
Gift^^^^^^|^^^^^^^^^1|^^^^^31.00
NOTICE: A negative number of spaces (e.g. %-10s) are
left-justified (spaces at the end) and an unsigned (or positive) number of spaces (%10d) are
right justified (spaces at the beginning).
Rounding Decimals
To round decimal numbers, specify the field width then use a period (.) followed by a number representing the number of decimal places you want to output. You can use 0 as a default field size.
System.out.format(“Test 1 %8.2f%%”, 0.257);
Output: Test 1 ^^^^0.26%
[multipage=Java Data Types and Variables]
Java Data Types and Variables
Data Types
| Data Type |
Category |
Bits |
Description of data |
| byte |
Integers |
8 |
A whole number in the range of -128 ~ 127 |
| short |
Integers |
16 |
A whole number in the range of -32,768 ~ +32,767 |
| int |
Integers |
32 |
A whole number in the range of -2,147,483,648 ~ +2,147,483,647 |
| long |
Integers |
64 |
A whole number in the range of -263 /-3.4 x 1038 ~ +263/3.4 x 1038 -1 |
| float |
Real numbers |
32 |
A decimal number in the range of -1.8 x 10 308 ~ +1.8 x 10 308 |
| double |
Real numbers |
64 |
A real number with a decimal number |
| boolean |
Boolean |
1 |
Either the value true or the value false |
| char |
Character |
16 |
A single character, eg. ‘a’, ‘4’, ‘#’ |
| String |
Character(s) |
(N/A) |
A group of one or more characters in double quotes |
Variables
Java programs are usually interactive and require input from the user. This input must be stored in computer memory. In Java, this process is achieved by declaring variables.
Naming Rules - Rules that must be followed
- Case sensitive (i.e. myString is different from mystring)
- Cannot start with a digit
- Can only contain a letter of the alphabet, a digit, the underscore character or a Unicode currency symbol ($)
- Cannot contain spaces
- Cannot be a reserved word (or keyword) (e.g. String, int, etc)
Naming Conventions - Guidelines that should be followed
- Should start with lowercase letters. Uppercase letters and underscores can be used to make the meaning clearer (e.g. timeAtStart ortime_at_start).
- Currency symbols should be avoided.
- Names should be meaningful.
Declaring Variables
A variable must be declared before it is used. A declaration takes the form:
<data_type> <variable_name/identifier>
Examples:
String myString;
int myInt1, myInt2;
double myDouble;
boolean myBoolean;
Declaring Variables
String myString;
myString = “Java is FUN!”;
System.out.println (myString);
int myInt1, myInt2;
myInt1 = 3;
myInt2 = 4;
System.out.println (myInt1 + myInt2);
[multipage=Java Input]
Java Input
Input
An application is more flexible when values can be read from an input stream. An input stream is the sequence of characters received from an input device, such as a keyboard. For example, as a user types data, the data goes into the input stream. To process data in the input stream, Java includes the Scanner class with methods for reading integers, floating point numbers, and strings.
To use the Scanner class, we need to import the class from java.util.Scanner. It can be done as follow:
import java.util.Scanner; //import the Scanner class from util package
or
import java.util.*; //import the entire util package includes Scanner class
Remember to put the import statement before any class definitions.
String Input : next() method
Scanner input = new Scanner(System.in); //initiate a Scanner object that getting input stream //from a keyboard
String myString; //variable declaration
System.out.print (“Enter a String: ”
; //prompting the user for input
myString = input.next (); //storing the user’s input in the variable myString
System.out.println (“You entered: ”+ myString); //outputting what the user input
The next() method only reads one string without spaces (eg. “Hello”

. If there is a string contains a space (e.g. “Hello world”

, nextLine() will be used to read the string.
Integer Input: nextInt() method
Scanner input = new Scanner(System.in); //initiate a Scanner object that getting input stream //from a keyboard
int myInt; //variable declaration
System.out.print (“Enter an integer: ”
; //prompting the user for input
myInt = input.nextInt(); //storing the user’s input in the variable myInt
System.out.println (“You entered: ”+ myInt); //outputting what the user input
Real(decimal numbers) Input: nextDouble() method
Scanner input = new Scanner(System.in); //initiate a Scanner object that getting input stream //from a keyboard
double myDouble; //variable declaration
System.out.print (“Enter a real number: ”
; //prompting the user for input
myDouble = input.nextDouble(); //storing the user’s input in the variable myDouble
System.out.println (“You entered: ”+ myDouble);//outputting what the user input
A Simple Program
/**
* NameAndAge.java
* NGU
* 01/14/2009
* Description: This program prompts the user for their name and age and displays a message
*/
import java.util.Scanner;
class NameAndAge
{
public static void main (String [] agrs)
{
//declaring variables
Scanner input = new Scanner(System.in); //initiate a Scanner
//object that gets input stream from a keyboard
String name;
int age;
// prompting user for name
System.out.print ("Please enter your name: ");
name = input.next();
// prompting user for age
System.out.print ("Please enter your age: ");
age = input.nextInt();
// displaying message
System.out.print (name + ", you are " + age + " years old!"); }
}
[multipage=Java Casting and Arithmetic]
Java Data Types and Variables
Casting
Casting - to convert the data type of an expression into another data type (e.g. convert char to int).
Automatic Type Conversion (no data is lost):
- occurs when the compiler automatically converts one data type to another.
These conversions are called widening conversions.
Widening conversions allow data to be represented as a data type with a greater range. For example, a byte can also be represented as a short without any loss of information.
The following are widening conversions permitted by Java:
| From |
To |
| byte |
short, char, int, long, float, double |
| short |
char, int, long, float, double |
| char |
int, long, float, double |
| int |
long, float, double |
| long |
Float, double |
| float |
double |
Example: Converting an int to a double
int intNum;
double doubleNum;
intNum = 5;
doubleNum = intNum;
Explicit Type Conversion (data is lost):
- occurs when the programmer forces a conversion.
To convert type1 data into type2 data, put the type1 keyword in brackets in front of the type2 data.
These conversions are called
narrowing conversions.
Narrowing conversions allow data to be represented as a data type with a lesser range. These conversions are not permitted by Java. Sometimes, it is “safe” and necessary to make a narrowing conversion. In these cases, a cast needs to be performed.
Example: Converting an double to an int
int intNum;
double doubleNum;
doubleNum = 5.0;
intNum = (int) doubleNum;
Mixing Data Types
In general, operations on values of the same type produce results of that type. In particular, the division of two integers results in an integer value – any remainder is ignored (rounds down).
5/3 = 1
When integer and floating point numbers are mixed in an expression, the result is a floating point number.
integer + floating point = floating point
Example 1
int i = 5;
int j = 2;
double k = 2.0;
double result;
result = i / j; //integer division, result = 2
result = i / k; //real division, result = 2.5
result = (double)i/(double)j; //real division, result = 2.5
Example 2
int i = 2;
double d = 3.7;
double y;
y = i / d; //i is implicitly cast; y is assigned 2.0 x 3.7
Example 3
int i = 2;
double d = 3.7;
double y;
y = (double)i * d; //better code; y is assigned 2.0x 3.7
Basic Arithmetic Operations
Addition: +
Subtraction: -
Multiplication: *
Division: /
Mathematical operations follow the rules of BEDMAS.
Modulo (%)
The mod operator (%) gives the remainder. It has the same precedence as multiplication and division.
5%3 = 2
[multipage=Java Debugging]
Java Debugging
Types of Errors
Syntax errors (compile time errors)
- easiest to detect
- mistakes in following the rules of a programming language (e.g. missing a semicolon etc)
- detected by the Java compiler
- program will not execute
Logic errors
- mistakes in the logic of the program
- program does not perform its intended task
- hard to detect
Runtime errors
- mistakes could be caused by logic errors
- invalid input from users (E.g. prompt for an integer but user input a String)
- program will halt when it happens
Avoiding Errors
- Use meaningful identifiers (variables, classes, methods etc.)
- Indent your statements
- Use internal comments appropriately – comments are supposed to assist readers in understanding a program’s actions
- Use blank lines to separate sections of your programs
- Use constants
Debugging Syntax errors
- Start the correction process by reading and fixing the first error message – a single error can cause the production of many error messages
- Read the error message very carefully to see what the compiler is trying to tell you. Once you have corrected an error, try to remember the message that it produced.
- If you get an error message that directs you to one location and you cannot find anything wring on that line, look at the previous line to see if something there is the
- cause of the error.
- Compare your program with the syntax of a working program.
Debugging Logic Errors
- Print out the intermediate values of variables
- Test the program in sections
- Use simple test values
[multipage=Java JOptionPane]
Java JOptionPane
JOptionPane
JOptionPane allows us to provide basic dialog windows in the program. To use it, we need to import javax.swing.JOptionPane.
Reference:
You must login or register to view this content.
Tutorial:
You must login or register to view this content.
Message Dialog
Option 1: Brings up a dialog that displays a message using a default icon determined by the messageType parameter.
Syntax
showMessageDialog(Component parentComponent, Object message, String title, int messageType)
Example
JOptionPane.showMessageDialog(null, “Hello”, “Greeting”, JOptionPane.INFORMATION_MESSAGE);
Option 2: Brings up a dialog displaying a message, specifying all parameters.
Syntax
showMessageDialog(Component parentComponent, Object message, String title, int messageType, Icon icon)
Example
ImageIcon icon = new ImageIcon(“funny.gif”
;
JOptionPane.showMessageDialog(null, “Hello”, “Greeting”, JOptionPane.INFORMATION_MESSAGE, icon);
Note: To use ImageIcon, you need to import javax.swing.ImageIcon before the class. Try to use .gif format image.
Input Dialog
Shows a question-message dialog requesting input from the user.
Syntax
showInputDialog(Object message)
Example
String input;
int a;
double b;
input = JOptionPane.showInputDialog(“Enter an Integer”
;
a = Integer.parseInt(input); //convert input(a string) into an integer
input = JOptionPane.showInputDialog(“Enter a decimal value”
;
b = Double.parseDouble(input); //convert input(a string) into a double
[multipage=Java If and else]
Java Data Types and Variables
Conditional Control or Selection
- statements are used in programming when a decision needs to be made.
Relational Operators
== Equals (important to use
two; one equal sign will be an assignment statement)
!= not equal to
> greater than
< less than
>= greater than or equal to
<= less than or equal to
Only primitive data types
can be compared in relational expressions.
Boolean Expressions
The condition of an if statement must be a boolean expression. A boolean expression has one of two outcomes:true or false.
Examples:
| Boolean expressions |
Value |
| 10 == 4 |
true / false |
| 10 != 8 |
true / false |
| ‘B’ <A’ |
true / false |
| 5 <= 5 |
true / false |
| -10 > -25 |
true / false |
| 3.14 >= 2.0 |
true / false |
if Statements
- if statements are used when you want to execute code only if a certain condition is met.
if
Syntax:
if ([U]condition/boolean expressions[/U])
{
//body of if clause
}
Example
//The following statements will display “SURPISE!” when users enter 1.
int number;
System.out.print(“Enter ‘1’ for a surprise.”
;
number = input.nextInt();
if (number == 1)
{
System.out.println(“SURPRISE!”
;
}
Application
/* application name
* name
* date
* description: This program will “Surprise” users when they enter a number less than 10.
*/
import java.util.Scanner;
public class IfExercise
{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
int number;
System.out.println(“Enter a number less than 10 for a surprise.”
;
number = input.nextInt();
if(number < 10)
{
System.out.println(“Surprise”
;
System.out.println(“Another Surprise!”
;
}
}
}
if..else
Syntax:
if..else statements are used when you have to make a decision between two choices.
if (condition)
{
//body of if clause
}
else
{
//body of else clause
}
Example
/*The following statements will display “ice will melt at this temp” if users enter the *temperate greater than 0, otherwise it will display “water will freeze at this temp”.
*/
double temp;
System.out.print(“Enter a temperature: ”
;
temp = input.nextDouble();
if ( temp > 0)
{
System.out.println(“ice will melt at this temp”
;
}
else
{
System.out.println(“water will freeze at this temp”
;
}
Nested Statements
- An if-else statement can contain another if-else or if statement
Example
//The following code gives a hint when the user does not guess the correct number.
final int SECRET_NUM = 7;
int guess;
System.out.print(“Guess a number: ”
;
guess = input.nextInt();
if (guess == SECRET_NUM) //correct
{
System.out.println("You guessed it!");
}
else
{
if (guess < SEC_NUM) //too low
{
System.out.println("Too low.");
}
else //too high
{
System.out.println("Too high.");
}
}
[multipage=Java Boolean Operators]
Boolean Operators
Boolean operators can be used to combine two or more conditions in an if statement.
Boolean Operators
&&
And (true only if both values are true)
||
Or (true if ether Boolean value is true)
!
Not (switches the value of a Boolean expression from true to false or vice versa)
Truth Tables
AND and OR
| Exp1 |
Exp2 |
AND (&& |
OR (||) |
| True |
True |
True |
True |
| True |
False |
False |
True |
| False |
True |
False |
True |
| False |
False |
False |
False |
NOT
| Expression |
NOT (!) |
| True |
False |
| False |
True |
Examples
//OR example: The following code requires users to guess a number between 1 and 10.
final int SECRET_NUM = 7;
int guess;
System.out.print(“Guess a number between 1 and 10:”
;
guess = input.nextInt();
if (guess>10 || guess<0 ) //invalid guess
{
System.out.println("Invalid guess!");
}
else if (guess == SECRET_NUM) //correct
{
System.out.println("You guessed it!");
}
else
{
if (guess < SEC_NUM) //too low
{
System.out.println("Too low.");
}
else //too high
{
System.out.println("Too high.");
}
}
- Can’t be greater than 10 AND less than 0 = a number can’t be both at the same time (you only have one guess)
- Make sure your boolean operator is comparing two things (right: guess>0 [guess compared with zero) (syntax error: <0 [what’s less than zero?])
//AND example : The following code determines if a person qualify to vote in the Ontario Provincial Election
if (______________________________) //eligible voter
{
System.out.println("You can vote.");
}
else //not eligible
{
System.out.println("Sorry, you can’t vote here. You are either underage or not an citizen.");
}
- only if both need to be true/false, use AND
- Ensure that the boolean variable has a value in it (true/false) >> then you won’t need to compare it (eg. if (age>=18 && citizen) [citizen is a boolean, so it’s either true or false, and it’s not comparing with anything]
- Compare two things need two equal signs (==); one equal sign just assigns a variable
//NOT example : The following code determine if a person qualify to get a driver’s
if (!age<16 ) //eligible driver
{
System.out.println("You can get a driver’s licence.");
}
else //not eligible
{
System.out.println("Sorry, you are underage.");
}
- (continued later) !NonOntarion example...
Short circuit evaluation
Java uses short-circuit evaluation for determining the result of a compound Boolean expression. In short-circuit evaluation, the left operand is evaluated first. If the result of the entire expression can be determine by the value of the left operand, then no other operands will be evaluated.
Example
In (x < 10 || x > 20), if x is less than 10, the second operand will not be evaluated.
In (x > 5 && x < 20), if x is less than 5, the second operand will not be evaluated.
- If first statement is already true, then the next statement will not even be looked at
- False and Ampersand (&&
automatically create a false statement
- True and Or (||) automatically create a true statement
Order of Operations
NOT (!) is evaluated before AND (&&

, OR (||) is evaluated last.
Example
!5 < 6 || 2 > 4 && 3 < 6 evaluates to false because !5 < 6 is performed first, then 2 > 4 && 3 < 6, and then false || false. Parentheses, (), can be used to change the order of operations.
- Use brackets to make another boolean operator go first