Professional Documents
Culture Documents
Summary
Summary
Step 1 Editor: Type in our instructions/statements according to rules of Java Language. File from editor
is called a source file and will have extension .java
Step 2 Compiler: Use compiler to translate the statements in source file to bytecode (which are portable
not dependent on hardware platform). File from compiler is called bytecode file and will have extension
.class. Use command javac ProgramName.java
Step 3 Loader: Use class loader to load bytecode files into memory (includes all the .class files that you
have written/produced and those provided by Java that you are using command> java ProgramName to
invoke Loader, Verification, Execution
Step 4 Bytecode verification: Use bytecode verifier to ensure bytecodes are valid and do not violate
Java’s security restrictions.
Step 5 Execution: Use JVM (Java Virtual Machine) to execute program’s bytecodes (to perform the
actions specified by your program)
Advantages of Java
Disadvantages of Java
Everything in Java is case sensitive…even filenames! Javamain is not same as JavaMain is not
same as javamain
Statements end in ;
Comments ignored by java compiler:
// means ignore to end of line
/* means ignore until you hit */ we can use this inside statement like if(/* asasa*/ a>b)
/** special comment used to generate documentation until */
Blocks are bounded by { }
Must have one and only one… public static void main (String [] args ) { }. This is where Java starts
executing!
Java programs consist of classes
One class per file (per .java)
Name of file should be exactly the name of class (Java is case-sensitive)
The name of a class should start with a capital letter
We will put all class files for a single program in one directory. Which will be called a workspace.
Java ignores spaces except between special operators like >= or //
Import statements must be first
public class ClassName { ……. }
Variables
Memory is a list of ordered fixed-sized cells, each cell has a “address” relative to the top of the list –
hence “relative address”. We can allocate memory cells to hold our data….and give these cells an
English-name instead of keeping track of the address these allocated cells are called variables.
General format:
Primitive Data Types (Numbers, characters and Booleans which are stored in fastest available memory.
Primitive data type names are all lowercase. String is not a primitive, it is an object). Primitive data types
cannot be assigned null values. Default value of primitive data type is 0.
boolean 1 bit - hold true or false value. Default value is false and 1 bit. Range is n/a.
int 32 bits – holds integer values only – all values are signed (first bit is used for sign)
Default value is 0 and Range is -2,147,483,648 to +2,147,483,647
Also,
DataType Rules:
Default datatype without explicit casting is int. Converting from int to String as well as
converting from String to int is not allowed in java. ( int a = (int) “123”; //error)
The datatype of the result of an operation is the datatype of the “largest” operand.
Loosely char < short < int < long < float < double.
Reference types
Example:
The static “parse” method that reads a String and returns the corresponding primitive type. For
example:
byte b = Byte.parseByte("16");
int n = Integer.parseInt( "42" );
long l = Long.parseLong( "99999999999" );
float f = Float.parseFloat( "4.2" );
double d = Double.parseDouble( "99.99999999" );
boolean b = Boolean.parseBoolean("true");
Variable Names
Beginning with a letter, the dollar sign "$", or the underscore character "_". The convention, however, is
to always begin your variable names with a letter, not "$" or "_". Additionally, the dollar sign character,
by convention, is never used at all. You may find some situations where auto-generated names will
contain the dollar sign, but your variable names should always avoid using it. A similar convention exists
for the underscore character; while it's technically legal to begin your variable's name with "_", this
practice is discouraged. White space is not permitted.
If your variable stores a constant value, such as static final int NUM_GEARS = 6, the convention changes
slightly, capitalizing every letter and separating subsequent words with the underscore character. By
convention, the underscore character is never used elsewhere.
String name;
name = “Howard”;
name = input.nextLine();
NOTE: You must return the results of nextLine to String. To then get a particular char out of the input,
write
() = += -= *= /= %=
/*% ++ -- (post)
Modulus Operator - %
% Returns remainder value of (integer) division and has same precedence as division and multiplication.
21 % 5 1
Pre/Post Operators ++ --
int x = 4, y = 10, z;
y = y + 1; 11
z = x + y; 15
x = x + 1; 5
By default, Java allows implicit (automatic) conversion from smaller data type to larger data type
Conversions from larger to smaller will generate syntax errors unless you explicitly type cast.
Define the Problem (Most important step, try some samples to try to understand, define inputs
and outputs)
Outline the Solution into an Algorithm by answering WHAT STEPS are needed.
Order steps and make it more specific
WHAT STEPS are needed within each of these more general steps
Continue refining each of these steps until you can no longer break down steps
Express Algorithm as Program Development Language (PDL)*Test the Algorithm for correctness
(test plan) *
PDL is a generic programming language that will help us transition from “word”
algorithm to the logic that will be needed in a program
it allows us to work with logic without having to deal with a specific language’s syntax
rules.
Keywords (subset):
•Start/Stop
•Input/Output
•Assignment
•Math Operation
•+ - * / MOD
Test Plan
test invalid range - for each boundary condition …test one before, the boundary, and one after
test invalid – should not accept, like chars for ints, or -50 or 200 for a valid range of 0 to 100
test valid - should accept
Calculations
Outputs
test display is correct and formatted properly (indicate specifically what this is in test plan)
FINALLY
NOTE:
Data Modeling
Start by asking what data do I need to work with……what are its properties…..what actions do I need to
perform on it.
Classes
You need to define a class – which will have no memory attached to it ….then declare objects (variables)
of that class that have the memory.
private members – by convention, they will hold the data elements themselves.
This is how we achieve abstraction – a class can be used by a programmer without knowing the data
that is kept, and just knows what actions there are.
Writing methods
…..code….
Return-data-type – A return type may be a primitive type like int, float, double, a reference type
(it can be object also) or void type(returns nothing).
Method-name – must be unique, same rules as variables (letters, digits, can’t start with digit)
Parameter list – data passed into the method each separated by spaces
Objects
We use member operator (.) to access the members of the class. We will only be able to access the
public members on an object, not the private members.
We can execute the methods with the member operator. (Remember the methods are public)
time1.display();
Assignment of obj2 to obj1 makes obj2 a reference to obj1. Therefore, any change in obj1 will be
reflected in obj2 also.
ClassName obj2=obj1;
Why we use classes?
Initializing Objects
A constructor (make a new Object of a Class) is used to initialize objects. But, A private
constructor cannot be used to initialize an object outside the class that it is defined within
because it is no longer visible to the external class. When a constructor is marked as private, the
only way to create a new object of that class from some external class is using a method that
creates a new object.
A constructor is a method that is declared inside the class; it will have the identical name to the
class; it will have no return data type (not even void…); and it will automatically be executed
when an object is declared.
There can be multiple constructors in a class…they each must have a different parameter list.
This is called function overloading….functions with same name, different parameter lists. The
order of argument is important parameter for determining method overloading. As the order of
attributes are different, the methods are overloaded.
Class object
This class (public class Person) is the blue print for the concept of Person. If the class name is consists of
multiple words each new word will start with a capital letter as well, no special characters.
Class or in this case person is also a data type. A realized Person is called an instance.
<code>Person shawn = new Person();</code>
shawn object in this case is an instance of class Person.
A class will hold any and all details relating to Person. These details could include:
Instance variables: These are data such as fName and lName. Always private and to be used
within the instance. Instance variables can be initialized in few ways:
o Inline initialization: manning right after the definition a value is assigned to them.
ex: private String fName = "shawn";
ex: private int age = 18;
o Constructor initialization: in this case the constructor will initialize the variables based
on your specification. Have in mind if you don't provide a constructor or do not
specifically initialize the variables in your constructor, they will be assigned the default
value for that type. like null for Objects and 0 for primitives.
o Method initialization: In this case you will initialize the variable when it is used for the
first time. It can be inside of any method at any point in life time of the instance. In this
case till a value is assigned to the variable the default value of the type is used for the
object.
Instance methods: These are methods such as display(). They can be private or public.
Instance constructors: Each class can have multiple constructors. Each constructor represents a
different way of creating an instance of given class. If there are no constructors provided by
developer a default constructor is generated (not visible) for the class. Default constructor does
nothing and takes no arguments it simply allows the instantiation of a Class. If we wanted to
initialize the variable to some value regardless of user, we could write no argument constructor.
In Java, if we write our own copy constructor or parameterized constructor, then compiler
doesn’t create the default constructor. We can also pass the job of initialization to another
constructor.
this( p.fName, p.lName, p.age);
If we use the line above it must always be the first line. In this case keyword "this" with
parenthesis in front of it referees to other available constructors. Target constructor is
determined based on number of arguments and their types.
Conditionals
AND operator is && and OR operator ||
The AND operator (&&) is lower than Boolean operators in the order of precedence chart…..it is above
the assignment operators. The OR operator (||) is lower than Boolean operators in the order of
precedence chart…..it is above the assignment operators and below the AND operator (&&)
Precedence Table - updated
++ -- (pre) ! -
()
/*%
+-
< >= <=
== !=
&&
||
= += -= *= /= %=
++ -- (post)
IF Statement
Syntax of if statement
if (boolean expression)
{
statement(s);
}
else {
statement(s);
}
Common Errors:
missing brackets ( ) around boolean expression
if/else keywords must be in lower case
missing braces { } around body – note that Java will assume only one statement in this case
missing semicolon at end of each statement inside the braces
int num = 23;
if (num >= 24)
System.out.println ("num is greater than 23"); //There is no braces so this is one line If statements.
else System.out.println ("num is 23 or less"); // if it is true, first statement will run. If not second
Note: If we put; after if (num >= 24); we can not use else. There will be syntax error.
Nested if means one if statement inside another if statement (usually repeated).
in && operation conditions are evaluated from left to right and if a false is found the rest of the
conditions will not be evaluated. So if there is an logical error like divide by 0 will not catch.
if( !isEven && !isDivisableByThree){ System.out.print( "Fizz");
in || operation conditions are evaluated from left to right and if a true is found the rest of the conditions
will not be evaluated.
Switch Statement
Can only use switch in very specific situations:
Testing one expression type (byte, short, char, int or String)
Testing for equality (can’t test for range of values)
Basic syntax switch (expression){ ….}
Watch end bracket – it’s often forgotten…
Use case keyword and value for equality tests
case value :
Stringing cases together results in OR operation
Use break keyword to exit statement (switch, if, or loop) and continue at next statement after switch.
Without break, the statement executes all statements from that point on.
switch (grade) {
case ‘A’: case ‘a’:
System.out.println ( “Well done – you did the best!!”);
break;
case ‘F’: case ‘f’:
System.out.println (“Oh Oh – you failed”);
break;
case ‘b’: case ‘B’:
System.out.println (“You did well”);
break;
default: System.out.println (“You made it!”);
}
Printf
\b \t \n \f \r \\ \” \’
\t for tab, \n for new line, \b to format boolean values. If the result is true it shows true
otherwise false.
\b backspace
\f next line first character starts to the right of current line last character
\r carriage return like new line \n
Using % and conversion-characters
s – formats strings
d – formats decimal integers
f – formats the floating-point numbers
t– formats date/time values (“%tT”) for time like 14:45:00 and (“%tD”) for date like 11/29/2019
Width Specifier, Aligning, Fill with Zeros
Empty spaces to the left of the first character can be filled with zeroes as shown below:
System.out.printf("'%010.2f'%n", 2.28); // output will be '0000002.28'
System.out.printf("'%10.2f'%n", 2.28); // output will be ' 2.28'
System.out.printf("'%-10.2f'%n", 2.28); // output will be '2.28 '
toString Method
Returns a string representation of the object. By overriding the toString() method of the Object class, we
can return values of the object, so we don't need to write much code.
public class Callee { public class Caller {
private String name; public static void main(String[] args) {
private int id; Callee callee=new Callee();
public Callee() System.out.println(callee.getString());
{ System.out.println(callee);
name="Howard"; }
id=6502; }
}
public String getString() Output:
{ Howard Id=6502
return name+" Id="+id; Callee@15db9742
}
}
The second line of output is not string representation of the object. If we use toString() then
public class Callee { public Callee()
private String name; {
private int id; name="Howard";
id=6502; System.out.println(callee.toString());
} System.out.println(callee);
public String toString() }
{
return name+" Id="+id; Output:
} Howard Id=6502
} Howard Id=6502
In the first example System.out.println(callee); prints the hashcode values of the objects but I want to
print the values of these objects. Since java compiler internally calls toString() method, overriding this
method will return the specified values.