You are on page 1of 17

Development Cycle for Java

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

 Portable “byte code” write once, run anywhere


 Standardized language
 Type safe language
 Secure environment (…compilers catch more errors)

Disadvantages of Java

 Can be slower than native machine


 Relatively young language, still undergoing changes

General Java Notes

 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:

datatype variableName = new datatype(initialvalue);

datatype var1 = initialvalue;

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.

char 16 bits – holds number representing Unicode char.

Default value is \u0000 and Range is \u0000 to \uFFFF (0 to 65,535)

char letter = ‘a’; letter = letter + 1; // now letter contains ‘b’

float 32 bits – holds decimal numbers and default value is 0.0F

Range is +/-1.4023E-45 to +/- 3.4028E+38

8 decimal places of accuracy

Never causes run-time exceptions, even in case of division by 0

Literal values include : 77.7f, 77.7F, POSITIVE_INFINITY, NEGATIVE_INFINITY, NaN(Not-a-


number)

double 64 bits – holds decimal numbers and default value is 0.0

Range is +/-4.94E-324 to +/- 1.7977E+308

17 decimal places of accuracy

Never causes run-time exceptions, even in case of division by 0

Literal values include : •77.7d, 77.7D, 77.7, POSITIVE_INFINITY, NEGATIVE_INFINITY,


NaN(Not-a-number)

boolean 1 bit - hold true or false value. Default value is false and 1 bit. Range is n/a.

boolean isOk = true; isOk = !isOk; // now isOk is false

boolean isEven = input % 2 == 0;

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

All arithmetic is performed as int

Need to watch for overflow of memory!

Also,

byte – 8 bit integer }…..careful though….all

short – 16 bit integer }…..arithmetic is done…signed

long – 64 bit integer }…..as int (32bits)…….signed

String – class type for many chars

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

Include array, class, interface and String

“point to” memory…..need to actually allocate the memory

need to use “new” with these…

Example:

Scanner input = new Scanner (System.in);

MyClass myobject = new MyClass(InitValue);

ClassName ObjectName = new ClassName (InitialValue);

Parsing Primitive Numbers

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.

• Must start with letter (num1 not like 1num)

• Can contain only letters, numbers and underscore

• Max length 64, want to realistically use at most 20 chars in name

• Must be unique, are case sensitive … so name1 is not same as NAME1

• Capitalize subsequent first letters of words…. itemList, totalCost

Inserting data into variable (memory) -

char letter = ‘a’; or

String name;

name = “Howard”;

Through Scanner (keyboard) “nextLine” method

name = input.nextLine();

NOTE: You must return the results of nextLine to String. To then get a particular char out of the input,
write

letter = name.charAt(0);….where 0 is position

Decimal data (DecimalFormat)

import java.text.DecimalFormat; //if program uses class

DecimalFormat form = new DecimalFormat("#0.00"); // unlimited before decimal, 2 after decimal

System.out.println ("Result is: " + form.format(result));

Order of Precedence Rules:

Brackets () Assignment Operator =

Division/Multiplication/Modulus / * % Shortform Operators += -= *= /= %=

Addition/Subtraction + - (same precedence as =)


++ -- (pre) +-

() = += -= *= /= %=

/*% ++ -- (post)

Modulus Operator - %

% Returns remainder value of (integer) division and has same precedence as division and multiplication.

21 % 5  1

Pre/Post Operators ++ --

Precedence: Can be imbedded into an expression or used in a statement on its own.

Can only be used with int datatypes.

int x = 4, y = 10, z;

z = x++ + ++ y; // this is really three statements

y = y + 1; 11

z = x + y; 15

x = x + 1; 5

By default, all arithmetic is int; and decimals are chopped!

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.

int total = 26;

float average = total / 10; //// int to float okay

short average = total / 10.0f; //// error

short average = (short)(total/10.0f) // okay

General Steps – Procedural

 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

•START {Name of Program} to indicate beginning

•END {Name of Program} to indicate ending

•Input/Output

•GET or READ to retrieve information

•PUT or PRINT or WRITE to display information

•Assignment

• for “is equal to”

•Math Operation

•+ - * / MOD

 Test the Algorithm for correctness*


 Run through the algorithm to see if it has any errors
 Try a couple of cases – like the examples you’ve been working with above
 Check for things like:
 Out of order statements
 Incorrect steps
 Missing information
 Boundary conditions
 Try to FIND ways to make algorithm fail
 Document in a thorough test plan all the cases you need to check.
 Code the Algorithm into Program (in Java for us)
 Run and debug the Program
 Install and Maintain the Program

*Order of these steps may be reversed

Benefits to this approach:

 Gives a strategy to solve most complex problems


 Will result in faster development time – due to fewer errors
 Will result in programs that are easier to maintain as they will be written better.

Test Plan

For each input

 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

 test every condition possible in calculations

Outputs

 test display is correct and formatted properly (indicate specifically what this is in test plan)

FINALLY

 look for ways to cause it to fail

Put in a table with three columns

 Description of the case to be tested


 Sample input values for this case
 Expected result with these input values

Object Oriented Design

 Analyze data and its requirements in the problem first


 THEN, write steps to solve the problem
 Will allow for much more reusable code and modularity of design…will explain this further at
end of lecture
 Determine the (abstract) objects we will be working with
 For each object, determine the properties associated with the object and the actions it can
perform
 To implement this, we define a class – the members of the class are the:
o properties (called data members or instance variables)
o actions or behaviors (called member functions or methods)
 Then, we create specific objects of that class to represent each instance of the class. (called
instantiation)

NOTE:

 There is often more than one way to solve a problem….


 Most important consideration is that whatever the solution is, it must be correct for EVERY case
 One solution can be evaluated as better than another…based on efficiency, less memory use,
more user friendly, etc.

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.

Two kinds of access modifiers for fields (data) or methods (actions):

 private can only be seen from inside the class


 public can be seen from inside and outside the class

private members – by convention, they will hold the data elements themselves.

public members – by convention, they will be the “actions” – ie functions.

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

Access-specifier return-data-type method-name (parameter list) {

…..code….

Access-specifier – public or private

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

Notes: in Java, non-static methods cannot be called in a static method.

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.

Time time1 = new Time();

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 obj1 = new ClassName();

ClassName obj2=obj1;
Why we use classes?

 Will save you time in the long run!!!


 Can organize data in logical fashion.
 No need to pass data in parameter lists…a copy of all data automatically belongs to each object
and the function uses that data when executing on a object.
 Can reuse code – simply by declaring an object of that data type…have access to all functions in
the class
 Data is protected…can only be accessed via the functions..can’t be corrupted outside the class.

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.

public class Time {


private int hours;
private int minutes;
private int seconds;
public Time ( ) { // default constructor Time time1=new Time()
hours = 0;
minutes = 0;
seconds= 0;
}
public Time (int h, int m, int s) { // initial constructor Time time2=new Time(18,45,0)
hours = h;
minutes = m;
seconds = s;
}
public Time (Time time) { // copy constructor Time time3=new Time(time2)
hours = time.hours;
minutes = time.minutes;
seconds = time.seconds;
}
} // End of Class
String class
In java.lang.* library
Has as data members the ability holds multiple chars (in what is called an array)
String(); // Default constructor
Example String name = new String();
String (“first string intializer”); // Initial constructor
Example String name1 = new String(“Howard”);
String (String) // Copy constructor
Example String name2 = new String (name1);
String.charAt(int); // returns the char at position int- note starting at position 0
Example: String name = “Howard”; // this is allowed too
char letter = name.charAt(0); // letter=’H’
String.length() – returns the number of characters in the string. Name.lenght() = 6

public class StringExample3 {


public static void main (String [ ] args) {
String name1 = "Billy";
String name2 = name1;
String name3 = new String(name1);
System.out.println( name1+','+name2+','+name3); // Billy, Billy, Billy
System.out.println(name1.equals(name2)); // true
System.out.println(name2.equals(name3)); // true
System.out.println(name1.equals(name3)); // true
System.out.println(name1==name2); // true
System.out.println(name2==name3); // false
System.out.println(name1==name3); // false

String fullName=”Lutfi Cildir”;


fName = fullName.split(" ")[0]; // fName=”Lutfi”
lName = fullName.split(" ")[1]; // lName=”Cildir”
}
}

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 '

Static Variables and Methods


A static variable or method means it is global and does not belong to any specific object. it is simply
stored inside of this class.
Its effect depends on where it’s used
 Can be used to qualify a data member in a class: Causes only one instance of the data member
to be created in memory, and all objects of the class share the use of that instance (instead of
creating their own version of it)
 Can be used to qualify a method: Means the method can be called without needing an object of
that class to act on. Static means it does not belong to a class, that is why we can call test
method from main method without creating an instance of Class.
public class StaticExample {
private static int count;
public StaticExample() { count = 0;}
public void increment() { count++; }
public void display () {
System.out.println (“count is “ + count);
}
}
In method main, we write:
StaticExample object1 = new StaticExample ();
StaticExample object2 = new StaticExample ();
object2. display(); // count is 0 is displayed
object1. display(); // count is 0 is displayed
object1.increment();
object1.display(); // count is 1 is displayed
object2.display(); // count is 1 is displayed
object2.increment();
object1.display(); // count is 2 is displayed
object2.display(); // count is 2 is displayed
We can call static variable by using object of a class but it should not be used. object1.MAX_SIZE works
but use Class.MAX_SIZE. Do not forget variable in a class should be always private.
Static local variables are not allowed in Java.
Loop Statements
Loops are used to repeat parts of program. Often the programmer doesn’t know how many times to
repeat. Need to control number of repetitions – use a loop control variable (LCV)
 initial value
 how the value changes
 cessation value (to stop loop - so it doesn’t go forever)
 final value of LCV can often be valuable
While Statement
Syntax: while (boolean expression) {
statement(s);
}
 Check boolean expression
 if false continue processing at statement after }
 if true, execute all statement(s) in the loop body in order, and then go back and evaluate the
boolean expression.
The common error for loops is relation between counter and LCV, so you need to be very careful with
LCV boundary values.
Has similar errors to if statements (e.g. executes single line if no curly brackets, semicolon after round
brackets, …)
Do while statement
Syntax: do {
statement(s);
} while (boolean expression);
 Executes statement(s) in loop body in order
 Check boolean expression
 if true go back and execute statements in loop body again
 if false continue at statement after the }while();
 NOTE: THIS LOOP ALWAYS EXECUTES ONCE
for statement
Syntax:
for (initialization; boolean expression; increment) {
statement(s);
}
 Executes initialization
 Check boolean expression
 if true execute statements in loop body in order; then execute increment; then check boolean
expression again if false continue at statement after the }
continue statement
Can be used in body of a loop (while; do/while; for) When executed, it causes control to immediately
pass out of body of loop and continue back at the top of the loop.
ARRAYS
An array is a Java construct that holds a fixed size set of variables of the same datatype. Size of array
cannot be change. It can dynamically or statically be set. Every time the new keyword is used when
initializing an array all previous data, if any, will be lost and a new memory location is allocated.
datatype[ ] arrayname = new datatype[numberOfElements];
float [ ] grades = new float[10]; // a set of 10 floats called grades
MUST specify size of array when declare it.
arrayname - follows same rules as variable name
datatype – can be any Java data type (including classes).
Splitting declaration and new with primitive data types
We declare int[ ] numbers; //The current value of numbers is null…has no int memory locations yet.
We then execute
int numNums = in.nextInt();
numbers = new int[numNums] //…now numbers has 100 int memory locations
Initialization of Arrays
We can initialize the array when we declare it if it is of type primitive:
Syntax: datatype[ ] arrayname = { val1, val2, val3,..};
int [ ] numbers = {4, 8 ,2, 6, 20}; // numbers[0] = 4 and numbers[1]=8
The indexes (or indices – correct English) of ANY array always start at 0 and end at size-1
Arrays of non-primitives
Say we want an array of some non-primitive datatype…example an array of Items on a Restaurant Bill,
where Item is a class.
Item [ ] bill ; // bill has value null after this
bill = new Item[100]; // allocates array of 100, but no actual Items yet
for (int i = 0; i < 100; i++) {
bill[i] = new Item(); // I have 100 Items in memory, initialized with default constructor
bill[i].getInputFromUser(); // red is any method in Item class
}
Length field
For any array, you can retrieve its length by using .length
int [ ] nums= { 1, 2, 5, 8};
int a = nums.lenght; // a=4
Common to allocate a maximum size for an array, but have less elements actually stored in the array. In
this case, you need to keep a variable ( say, int numInArray) to keep track of how many are actually in
the array.
int nums = new int [100];
int numInArray = 0;
….add to arrray…..
nums[numInArray] = input.nextInt();
numInArray++;
Notes for Arrays
Printing an array like below simply prints the HashCode not the data
int array[] = { 0, 2, 4, 6, 8, 10 };
System.out.println( "Incorrect Array print: " + array); // Incorrect Array print: [I@15db9742
The method below is from the JDK library, the class Arrays has an overloaded set of methods called
toString that returns a string version of any array.
System.out.println( "JDK utility Array print: " + Arrays.toString(array));
To compare two Arrays, we can not use == or arr1.equals(arr2). We can use Arrays.equals(arr1,arr2).
UML and Memory maps
Primitive variables
 Variables of type int float double char boolean are called primitive In Java
 Memory is allocated immediately for such variables
Reference variables
 Objects of a class are also called reference variables in Java
 Memory is NOT allocated immediately for such variables
 Memory is actually allocated for the
o Example: name = new String(“Howard”);
o date = new Date();
Declaring objects of a class in another class
Example:
public class Employee {
private float hoursWorked;
private float rateOfPay;
private Date startDate;
private String name;
……..
}
Issue: when you create an object of type Employee (Employee employee = new Employee();) you need
to use the constructors to allocate the memory for startDate and name as they are just references
(initialized to null).
public Employee() {
hoursWorked = 0.0f;
rateOfPay =0.0f;
startDate = new Date();
name = new String();
}
Otherwise, you will get run time error if you try to use a reference that does not have memory allocated
to it! (Primitives don’t need this!).
UML
Used to document a class
Two sections – top section for data members and bottom section for methods
Public is indicated with a + and private is indicated with a –

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

public class Caller {


public static void main(String[] args) {
Callee callee=new Callee();

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.

Use of this operator


This can be used in a class method to qualify that given multiple versions in memory of the same-named
variable, you mean to use the one that belongs to the current object.
Unicode character set
A code from ‘\u0000’ to ‘\uFFFF’ (\u0000 to \u007F are the same as ASCII)
Unicode is a computing industry standard for the consistent encoding, representation and handling of
text expressed in most of the world's writing systems.
The Java String compareToIgnoreCase() method
The Java String compareToIgnoreCase() method compares two strings lexicographically and returns 0 if
they are equal. As we know compareTo() method does the same thing, however there is a difference
between these two methods. Unlike compareTo() method, the compareToIgnoreCase() method ignores
the case (uppercase or lowercase) while comparing strings.
String s1 = "BEGINNERSBOOK"; //uppercase
String s2 = "beginnersBOOK"; //mixedcase
s1.compareTo(s2); //this would return non-zero value
s1.compareToIgnoreCase(s2); //this would return zero
 An int value: 0 if the string is equal to the other string, ignoring case differences.
 < 0 if the string is lexicographically less than the other string
 0 if the string is lexicographically greater than the other string (more characters)
Debugging
 Use debugging to find logical error in a program.
 Use “print” statements when don’t have a debugger, or only have the commandline
 Use assert to find bugs “that should never happen” while still in development
 Use logging when the code is in a customer site
 There are many tools for when it is not your code

You might also like