Java Summary
Java Summary
In a Java program, you must declare a variable before it can be used. A variable declaration
has the following form:
**SYNTAX
**Data type: A data type specifies a set of values and their operations(e.g. int, double, long,
etc.)
% The technical term for a name in a programming language, such as the name of a variable, is
an identifier ,should not use the $ symbol in your identifiers-It is intended to identify code
generated by a machine
% The name of something in a Java program, such as a variable, class, or method, is called an
identifier
You can combine the declaration of a variable with an assignment statement that gives the
variable a value.
**SYNTAX
e.g.
public static final double PI = 3.14159;
% The word public says that there are no restrictions on where you can use the name PI.
% The word final means that the value 3.14159 is the final value assigned to PI or, to phrase it
another way, that the program is not allowed to change the value of PI.
**Assignment Compatibilities
e.g.
byte -> short -> int -> long -> float -> double -> char
% It is also legal to assign a value of type char to a variable of type int or to any of the numeric
types that follow int in our list of types
**TYPE CASTING
% Involves putting the type that you want to change into in front of the variable you wanna
change.
int points = (int)distance; // Legal although truncation and lost of data may
occur as result of you not following a certain hierarchy.
% Neither distance nor the value stored in distance is changed in any way. But the value stored
in points is the “int version” of the value stored in distance. If the value of distance is 25.36, the
value of (int)distance is 25. So points contains 25, but the value of distance is still
25.36(**truncation not rounded)
% This operand can be both used for division as well as integer division depending on whether
we are dividing an int and a double, or an int and int.
e.g. count += 1;
% decrement operator:
% n*(m++) ,
output = 12 // since the increment operator is after the value m , the expression n*m
is calculated first then m is incremented after
% Note that the string " " is not empty: It consists of one blank character.
%All objects of a class have the same methods
%Spaces, special symbols, and repeated characters are all counted when computing the length
of a string. For example, suppose we declare String variables as follows: String command = "Sit
Fido!"; String answer = "bow-wow";
**Methods
% It is important to note that each escape sequence represents one character, even though it is
written as two symbols. So the string ""Hi"" contains four characters—a quote, H, i, and another
quote—not six characters. This point is significant when you are dealing with index positions
**Java Comments
• Everything after the two symbols / / to the end of the line is a comment and is ignored by the
compiler.
• Anything written between the symbol pairs / and / is a comment and is ignored by the
compiler. • Anything written between the symbol pairs /* and / is a comment that is processed
by the documentation program javadoc but is ignored by the compiler.
{
double radius; //in inches
double area; //in square inches
Scanner keyboard = new Scanner(System.in);
radius = keyboard.nextDouble();
area = PI * radius * radius;
if (condition/Boolean expression)
// execute statement1
else
// execute statement2
% We can also use the if statement without the else statement (this in turn continues executing
the program).
if (Boolean expression)
execute statement1
execute statement2
in java we use **&& operator for joining to expressions instead of using an inequality sign.
e.g.
if ((pressure > min) && (pressure < max))
System.out.println("Pressure i OK.");
else
System.out.println("Warning: Pressure is out of range.");
e.g.
if ((salary > expenses) || (savings > expenses))
System.out.println("Solvent");
else
System.out.println("Bankrupt");
In Java we use equals method to equate two strings not == two equals signs
e.g.
if ("Hello".equalsIgnoreCase("hello"))
System.out.println("Equal");
OR
e.g.
import java.util.Scanner;
public class StringEqualityDemo
{ public static void main(String[] args)
{ String s1, s2;
System.out.println("Enter two lines of text:");
Scanner keyboard = new Scanner(System.in);
s1 = keyboard.nextLine();
s2 = keyboard.nextLine();
if (s1.equals(s2))
System.out.println("The two lines are equal.");
else System.out.println("The two lines are not equal.");
if (s2.equals(s1))
System.out.println("The two lines are equal.");
else System.out.println("The two lines are not equal.");
if (s1.equalsIgnoreCase(s2))
System.out.println( "But the lines are equal, ignoring case.");
else System.out.println( "Lines are not equal, even ignoring case.");
}
}
% When applied to two strings (or any two objects), the operator == tests whether they are
stored in the same memory location
e.g.
if (hoursWork <= 40)
pay = hoursWorked * payRate;
else
pay = 40 * payRate + 1.5 * payRate * (hoursWorked − 40);
% Most operating systems use 0 to indicate a normal termination of the program and 1 to
indicate an abnormal termination of the program (just the opposite of what most people would
guess). Thus, if your System.exit statement ends the program normally, the argument should be
0. In this case, normal means that the program did not violate any system or other important
constraints. It does not mean that the program did what you wanted it to do. So you would
almost always use 0 as the argument
% Highest
Precedence First: the unary operators +, , ++, , and!
Second: the binary arithmetic operators *, /, %
Third: the binary arithmetic operators +,
Fourth: the boolean operators <, >, <=, >=
Fifth: the boolean operators ==, !=
Sixth: the boolean operator &
Seventh: the boolean operator |
Eighth: the boolean operator &&
Ninth: the boolean operator ||
Lowest Precedence
**Short-Circuit Evaluation
For a boolean expression of the form Expr_A || Expr_B, if Expr_A is true, Java concludes that
the entire expression is true without evaluating Expr_B. Likewise, for an expression of the form
Expr_A && Expr_B, if Expr_A is false, Java concludes that the entire expression is false without
evaluating Expr_B.
e.g.
switch (Controlling_Expression)
{
case Case_Label:
Statement;
break;
case Case_Label:
Statement;
break;
default:
Statement;
break;}
EXAMPLE
int seatLocationCode;
switch (seatLocationCode)
{
case 1:
System.out.println("Orchestra.");
price = 40.00;
break;
case 2:
System.out.println("Mezzanine.");
price = 30.00;
break;
case 3:
System.out.println("Balcony.");
price = 15.00;
break;
default:
System.out.println("Unknown ticket code.");
break;
}
**Enumerations
e.g.
enum MovieRating {EXCELLENT, AVERAGE, BAD};
% to assign A to rating. Note that we must preface the value A with the name of the
enumeration and a dot. Assigning a value other than E, A, or B to rating will cause a syntax
error
The class JOptionPane in the package javax.swing defines the method show-ConfirmDialog.
You can use this method to create a dialog box to ask a yes-or-no question and get the user's
response.
**SYNTAX
The displayed dialog box is titled Title_String and contains the text Question_String and buttons
as indicated by Option. When Option is JOptionPane.YES_NO_OPTION,two buttons labeled
Yes and No are displayed. The method returns the int constant YES_OPTION if the user clicks
the Yes button, or NO_OPTION if the user clicks the No button.
**EXAMPLE
**JAVA_LOOP
while (Boolean_Expression)
Body
The Body may be either a simple statement or, more likely, a compound
statement consisting of a list of statements enclosed in braces {}.
e.g.
//Get next positive integer entered as input data
int next = 0;
while (next <= 0)
next = keyboard.nextInt(); //keyboard is a Scanner object
//Sum positive integers read until one is not positive
int total = 0;
int next = keyboard.nextInt();
while (next > 0)
{ total = total + next;
next = keyboard.nextInt();}
% do-while statement
% Is executed at least once
%The (do-while) loop unlike the (while loop) executes the body of statements first then follows
up by the control Boolean expression( And do not forget a semi-colon after the last Boolean
expression.
)
e.g.
do {
first_Staement
Last_Statement
}
while (expression)
After the first body is executed the do-while loop then acts like a normal
while loop.
e.g.2
import java.util.Scanner;
public class DoWhileDemo
{
public static void main(String[] args)
{ int count, number;
System.out.println("Enter a number”);
Scanner keyboard = new Scanner(System.in);
number = keyboard.nextInt();
count = 1;
do
{
System.out.print(count + ", ");
count++; }
while (count <= number);
System.out.println();
System.out.println("Buckle my shoe.”);
}
}
% The for-statement/loop
e.g
for (count = 1; count <= 3; count++)
Body
is equivalent to
count = 1;
while (count <= 3) {
Body count++;
}
e.g.2.
// Counting down
public class ForDemo
{
public static void main(String[] args)
{
int countDown;
for (countDown = 3; countDown >= 0; countDown−−) {
System.out.println(countDown);
System.out.println("and counting.”); }
System.out.println("Blastoff!”);
}
}
e.g.
for (int count = 0; count <= 10; count++)
// In this case count is local to the for loop and cannot be used
anywhere else.
The scope of the varaible count is thus the for loop.
A scope is where a variable can be used.
Classes
e.g.
// For a game of cards
enum Suit {CLUBS, DIAMONDS, HEARTS, SPADES}
for (Suit nextSuit : Suit.values())
System.out.println(nextSuit+" ");
System.out.println();
% The break statement ends the innermost part of the switch statement or the loop.
% A continue statement ends the current iteration and begins another one.
**Loop bugs
**Assertion in java
% Assertion checks in java involve asserting that a certain line of code is true or not.
you can turn assertion checking on and off by using the command line:
java −enableassertions YourProgram
configure the JUnit plug in for use with the version of JUnit that you have installed
open a source file in jGRASP and create a corresponding test file;
create test cases (test methods) in the test file for each of the methods in the source file
run the test file for a corresponding source file;
run all test files for a project
view the results of running the test files in the JUnit window
1. ) set a breakpoint in the test file at the statement where the source method is called
2. ) run the test file in debug mode. After the program stops at the breakpoint, step-in to the
source method
3. ) single-step, looking for the statement that is responsible for the failure
%Unit Testing: Testing one unit or component at a time (e.g., testing a class and its methods).
%Fault (or Defect): The underlying cause of the failure (a “bug” or “error” in your code).
%The purpose of testing is to identify failures so that the underlying faults (or defects)can be
removed.
%Debugging is the process of removing a fault. (Note that debugging occurs after a failure has
revealed the existence of a fault.)
**Arrays
Since index is an expression we can write a loop to read values into the array
temperature, as follows:
System.out.println("Enter 7 temperatures:")
for (int index; index<7; index++){
temperature[index] = keyboard.nextDouble();
}
Remember an array is an object meaning that you create an array the same way you
would create an object of a class type using the new operator.
e.g. int[] pressure = new int[100]; // creates 100 variables of type int (pressure[0],
pressure[1], pressure[2],..., pressure[n])
Alternative way to declare variables is:
You can also read in the length of an array instead of declaring it yourself
Always use singular form for an array name, instead of entries->use entry
instead of cars-> use car
You cannot change the size/length of an array once declared.
Always use a for loop or for-each statement to step through an array.
The array is created and holds ten references. In other words, there are ten addresses to
memory locations that can store SalesAssociate objects .Java uses special value null to
mark empty references.
To access an array we need to reference an object.
An indexed variable such as a[i] can be used anywhere you can use any other
variable of the base type of the array.
Thus it can be an argument to a method.
e.g.
double[] a = new double[3];
// Indexed variables such as a[3] and a[i] can thus be used as arguments
A parameter can also represent an entire array.
Array parameters do not specify array length.
e.g.
public static void ShowArray(char[] a)
e.g.
public static void main(String[] args){}
// args[0],args[1],..,args[i]
% If you want to test whether two arrays contain the same elements, must test whether each
element in one array equals the corresponding element in the other array.
%You can use the assignment operator = to give an array more than one name. You cannot use
it to copy the contents of one array to another, different array. Likewise, the equality operator ==
tests whether two array names reference the same memory address. It does not test whether
two different arrays contain the same values.
**Returning an array
Syntax
e.g.
public static Base_Type[] Method_Name(Parameter_List) {
Base_Type[] temp = new Base_Type[Array_Size];
Statements_To_Fill_Array return temp;
}
%A private instance variable that has an array type can be modified outside of its class, if a
public method in the class returns the array. This is the same problem we discussed in the
previous chapter, and it has analogous solutions.
Person
- Student
- Undergraduate
- Graduate
- Masters
- Doctoral
- Nondegree
- Employee
- Faculty
- Staff
A derived class extends a base class/ super class/ancestor/parent and inherits the base
class's public members.
In the example student extends Person:
We cannot directly access the instance variable name since it is private to Person class ,
but we can use public methods defined in Person class to change the name of the student
object.
A Demonstration of Inheritance Using Student
A method Overrides another method if both have the same name, return type and
parameter list
In a derived class, if you have a method with the same name, number of parameters and
types, and the same return type as a method already in the base class, this new definition
replaces the old definition of the method when objects of the derived class receive a call to
the method.
A method overloads another if they both have the same name and return type but different
parameter list
A final method cannot be overridden.
An entire class can be declared final, thus it cannot be used as a base class to derive any
other class.
A derived class can call public methods of the base class of which in turn calls a private
method when both methods are in the same class.
% An object of the derived class will inherit public and private instance variables of the base
class, but it cannot directly access the private instance variable.
A derived class does not inherit constructors from the base class
Constructors in the derived class invoke constructors in the base class
Any call to super/base class must be first within a constructor
without super/ omitting super a constructor invokes the default constructor in the base
class
public Student() {
super();
studentNumber = 0;//Indicating no number yet
}
public Student() {
studentNumber = 0;//Indicating no number yet
}
public Person() {
this("No name yet");
}
In this way, the default constructor calls the constructor public
Person(String initialName) {
name = initialName;
}
An object of the Undergraduate inherits the instance variables that are defined in Student
the derived class of Person and its base class Person.
You cannot use repeated supers, or supers in a chain format
An object can have several types due to inheritance, an object of type undergraduate is an
object of type Student and type Person.
An object of a descendant class can do the same things as an object of an ancestor class.
An object of a class can be referenced by name by a variable of any ancestor type.
% The keyword super: can be used to call a constructor from the super class
% The keyword super: Can also be used to invoke a method from the super class
**The class Object
**Polymorphism
Polymorphism allows you to make changes to the methods in the derived classes and
have those methods apply to the base class.
Consider the Person ,Student an d undergraduate classes
Lets say we we want to set up a committee that consists of 4 people who are either
students or employees.
1. We need to make an array of type Person to accommodate any class derived from it.
person[0].writeOutput();
3. The writeOutput method associated with the class used to create the object is used,
more precisely when an overridden method is invoked, its action is the one defined in
the class used to create the object using the new operator. This is called
**Dynamic/Late binding.
**Demo Polymorphism