A class can be defined as a template/ blue print that describes the behaviors/states that object of its type support.

Similar documents
Java is an Object Oriented Language. As a language that has the Object Oriented feature Java supports the following fundamental concepts:

Java is a high-level programming language originally developed by Sun Microsystems and released in Java runs on a variety of

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Java Programming. MSc Induction Tutorials Stefan Stafrace PhD Student Department of Computing

Preview from Notesale.co.uk Page 9 of 108

Outline. Why Java? (1/2) Why Java? (2/2) Java Compiler and Virtual Machine. Classes. COMP9024: Data Structures and Algorithms

Software Practice 1 - Basic Grammar Basic Syntax Data Type Loop Control Making Decision

Outline. Java Compiler and Virtual Machine. Why Java? Naming Conventions. Classes. COMP9024: Data Structures and Algorithms

Computer Components. Software{ User Programs. Operating System. Hardware

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic


Software Practice 1 Basic Grammar

Introduction to Programming Using Java (98-388)

This reference will take you through simple and practical approaches while learning Java Programming language.

JAVA: Improvised Approach to Java

3. Java - Language Constructs I

COMP 202 Java in one week

Modern Programming Languages. Lecture Java Programming Language. An Introduction

STRUCTURING OF PROGRAM

Java Programming. Atul Prakash

Index COPYRIGHTED MATERIAL

CSC 1214: Object-Oriented Programming

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

You must declare all variables before they can be used. Following is the basic form of a variable declaration:

Java Intro 3. Java Intro 3. Class Libraries and the Java API. Outline

Points To Remember for SCJP

Declarations and Access Control SCJP tips

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Computer Components. Software{ User Programs. Operating System. Hardware

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

2 rd class Department of Programming. OOP with Java Programming

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

An overview of Java, Data types and variables

DM550 Introduction to Programming part 2. Jan Baumbach.

Topics. Java arrays. Definition. Data Structures and Information Systems Part 1: Data Structures. Lecture 3: Arrays (1)

CHAPTER 7 OBJECTS AND CLASSES

1 Shyam sir JAVA Notes

BASIC ELEMENTS OF A COMPUTER PROGRAM

Objectives. Problem Solving. Introduction. An overview of object-oriented concepts. Programming and programming languages An introduction to Java

In Java, all variables must be declared before they can be used. The basic form of a variable declaration is shown here:

Pace University. Fundamental Concepts of CS121 1

CSCI 2101 Java Style Guide

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige

Last Time. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

CHETTINAD COLLEGE OF ENGINEERING & TECHNOLOGY JAVA

CHAPTER 7 OBJECTS AND CLASSES

CompSci 125 Lecture 02

Games Course, summer Introduction to Java. Frédéric Haziza

Building Java Programs. Introduction to Programming and Simple Java Programs

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

9 Working with the Java Class Library

CS 231 Data Structures and Algorithms, Fall 2016

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont.

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

Vendor: Oracle. Exam Code: 1Z Exam Name: Java SE 7 Programmer I. Version: Demo

Array. Prepared By - Rifat Shahriyar

Research Group. 3: Loops, Arrays

Java Identifiers. Java Language Essentials. Java Keywords. Java Applications have Class. Slide Set 2: Java Essentials. Copyright 2012 R.M.

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix

JOSE LUIS JUAREZ VIVEROS com) has a. non-transferable license to use this Student Guide

Full file at

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Lecture 2: Variables and Operators. AITI Nigeria Summer 2012 University of Lagos.

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview

1.Which four options describe the correct default values for array elements of the types indicated?

Introduction to. Android Saturday. Yanqiao ZHU Google Camp School of Software Engineering, Tongji University. In courtesy of The Java Tutorials

CS321 Languages and Compiler Design I. Winter 2012 Lecture 2

CMSC 331 Second Midterm Exam

Getting started with Java

Welcome to CSE 142! Zorah Fung University of Washington, Spring Building Java Programs Chapter 1 Lecture 1: Introduction; Basic Java Programs

COP 3330 Final Exam Review

20 Most Important Java Programming Interview Questions. Powered by

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension.

3. Java - Language Constructs I

Computer Science II Data Structures

Java Bytecode (binary file)

Sri Vidya College of Engineering & Technology

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

CS260 Intro to Java & Android 03.Java Language Basics

Training topic: OCPJP (Oracle certified professional Java programmer) or SCJP (Sun certified Java programmer) Content and Objectives

Java Foundations Certified Junior Associate

Java Primer 1: Types, Classes and Operators

The Java Language The Java Language Reference (2 nd ed.) is the defining document for the Java language. Most beginning programming students expect

Java Identifiers, Data Types & Variables

Program Fundamentals

Operators and Expressions

Accelerating Information Technology Innovation

Java Programming. Theory Manual

Unit 5: More on Classes/Objects Notes

Crash Course Review Only. Please use online Jasmit Singh 2

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166

Brief Summary of Java

Last Class. Introduction to arrays Array indices Initializer lists Making an array when you don't know how many values are in it

Chapter 2. Elementary Programming

Java in 21 minutes. Hello world. hello world. exceptions. basic data types. constructors. classes & objects I/O. program structure.

Introduction to Java

Transcription:

Java Basic Syntax 1. What is an Object Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behaviors -wagging, barking, eating. An object is an instance of a class. 2. What is a Class A class can be defined as a template/ blue print that describes the behaviors/states that object of its type support. 3. What is a Methods A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed. 4. First Java Program: Let us look at a simple code that would print the words Hello World. public class MyFirstJavaProgram { /* This is my first java program. * This will print 'Hello World' as the output */ public static void main(string []args) { System.out.println("Hello World"); // prints Hello World Let's look at how to save the file, compile and run the program. Please follow the steps given below: Save the file: MyFirstJavaProgram.java. command prompt go o the directory where you saved the class. Assume it's C:\. C : > javac MyFirstJavaProgram.java C : > java MyFirstJavaProgram Hello World 5. Basic Syntax: About Java programs, it is very important to keep in mind the following points. Case Sensitivity - Java is case sensitive, which means identifier Hello and hello would have different meaning in Java. Class Names - For all class names the first letter should be in Upper Case. If several words are used to form a name of the class, each inner word's first letter should be in Upper Case. Example class MyFirstJavaClass Method Names - All method names should start with a Lower Case letter. 1 If several words are used to form the name of the method, then each inner word's first letter should be in Upper Case.

Example public void mymethodname() Program File Name - Name of the program file should exactly match the class name. When saving the file, you should save it using the class name (Remember Java is case sensitive) and append '.java' to the end of the name (if the file name and the class name do not match your program will not compile). Example : Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved as 'MyFirstJavaProgram.java' public static void main(string args[]) - Java program processing starts from the main() method which is a mandatory part of every Java program.. 6. Java Identifiers: All Java components require names. Names used for classes, variables and methods are called identifiers. In Java, there are several points to remember about identifiers. They are as follows: All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an underscore (_). After the first character identifiers can have any combination of characters. A key word cannot be used as an identifier. Most importantly identifiers are case sensitive. Examples of legal identifiers: age, $salary, _value, 1_value Examples of illegal identifiers: 123abc, -salary 2

7. Java Modifiers: Like other languages, it is possible to modify classes, methods, etc., by using modifiers. There are two categories of modifiers: Access Modifiers: default, public, protected, private Non-access Modifiers: final, abstract, strictfp, abstract, transient, volatile Member (Method and variable) Access Modifier Class Package SubClass same pkg public protected no modifier private default Subclass diff pkg World public exposes to classes outside the package. protected is a version of public restricted only to subclasses private hides from other classes within the package. final Class = makes it impossible to extend a class, Method = it prevents a method from being overridden in a subclass, Variable = it makes it impossible to reinitialise a variable once it has been initialised strictfp floating-point- ensures same result on every platform. strictfp keyword can be applied on methods, classes and interfaces. strictfp class A{ //strictfp applied on class strictfp interface M{ //strictfp applied on interface class A{ strictfp void m(){ //strictfp applied on method transient indicates that a variable is not part of the persistent state of an object. volatile indicates that a thread must reconcile its working copy of the field with the master copy every time it accesses the variable. 8. Java Variables: Local Variables Instance Variables (Non-static variables) Class Variables (Static Variables) Local variables: Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed. will not get default value means class variable cannot be used without initializing it 3 Instance variables: within a class but outside any method. instance specific and are not shared among instances. Public, Private, Protected

Instance Variable can be marked final. transient. Instance variable will get default value means instance variable can be used without initializing it Instance Variable Type Default Value boolean false byte (byte)0 short (short) 0 int 0 long 0L char u0000 float 0.0f double 0.0d Object null Instance Variable CANNOT be marked abstract. synchronized strictfp native Static modifier as it will becomes Class level variable. Class variables/static Variable: declared with in a class, outside any method, with the static keyword. 9. Create constant with static final public static final int MAX_UNITS = 25; 10. Java Int vs Integer 4

int is a number; Integer is a pointer that can reference an object that contains a number. Prefer int for performance reasons Methods that take objects (including generic types like List<T>) will implicitly require the use of Integer Use of Integer is relatively cheap for low values (-128 to 127) because of interning - use Integer.valueOf(int) and not new Integer(int) Do not use == or!= with Integer types Consider using Integer when you need to represent the absence of a value (null) Beware unboxing Integer values to int with null values Converting a primitive value (an int, for example) into an object of the corresponding wrapper class (Integer) is called autoboxing. The Java compiler applies autoboxing when a primitive value is: Passed as a parameter to a method that expects an object of the corresponding wrapper class. Assigned to a variable of the corresponding wrapper class. Consider the following method: public static int sumeven(list<integer> li) { int sum = 0; for (Integer i: li) if (i % 2 == 0) sum += i; return sum; 11. Java Arrays: Arrays are objects that store multiple variables of the same type. However, an array itself is an object on the heap. 12. Java Enums: Enums were introduced in java 5.0. Enums restrict a variable to have one of only a few predefined values. The values in this enumerated list are called enums. With the use of enums it is possible to reduce the number of bugs in your code. For example, if we consider an application for a fresh juice shop, it would be possible to restrict the glass size to small, medium and large. This would make sure that it would not allow anyone to order any size other than the small, medium or large. Example: class FreshJuice { enum FreshJuiceSize{ SMALL, MEDIUM, LARGE FreshJuiceSize size; public class FreshJuiceTest { 5 public static void main(string args[]){

FreshJuice juice = new FreshJuice(); juice.size = FreshJuice. FreshJuiceSize.MEDIUM ; System.out.println("Size: " + juice.size); Above example will produce the following result: Size: MEDIUM Note: enums can be declared as their own or inside a class. Methods, variables, constructors can be defined inside enums as well. 13. Declaring Arrays The general syntax for declaring an array is as follows: type arrayname [ ]; Java allows another syntax for array declaration, as follows: type [ ] arrayname; To declare an array of integers, you would use the following declaration: int[] numbers; The name of the array in this declaration is numbers. Thus, each element of the array would be accessed using this name along with an appropriate index value. To declare an array of float, you use the following declaration: float[] floatnumbers; The name of the array is floatnumbers, and each element of the array holds a floating-point number. Fig ure 2-1.â An array of five integer variables 100 150 49 3 225 14. Creating Arrays Now that you know how to declare an array variable, the next task is to allocate space for the array elements. To allocate space, you use new keyword. For example, to create an array of 10 integers, you would use the following code: int[] numbers; numbers = new int[10]; The first statement declares a variable called numbers of the array type, with each element of type int. The second statement allocates contiguous memory for holding 10 integers and assigns the memory address of the first element to the variable numbers. An array initializer provides initial values for all its components. You may assign different values to these variables somewhere in your code, as explained in the next section. To create an array of 20 floating-point numbers, you use the following code fragment: 6 float[] floatnumbers; floatnumbers = new float[20];

15. Accessing and Modifying Array Elements the first element of the array is accessed using the following syntax: numbers[0] Block Blocks { Loop Blocks do, for, while { xxxx try catch block try { xxx catch ( exception1) { xxx The finally block is always executed, even if an exception is thrown. It may appear with or without a catch block, but always with a try block. try { xxx catch ( exception1) { xxx finally { xxxxx 16. Initializing Using Array Literals Array literals provide a shorter and more readable syntax while initializing an array. For example, consider the following program statement: int[] numbers = {15, 2, 9, 200, 18; This statement declares an array of integers containing five elements. The compiler determines the size of the array based on the number of initializers specified in curly braces. When the JVM loads this code in memory, it will initialize those memory locations allocated to the array with the values specified in the curly braces. import java.io.*; 7

public class TestScoreAverage { public static void main(string[] args) { final int NUMBER_OF_STUDENTS = 5; int[] marks = new int[number_of_students]; try { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); for (int i = 0; i < NUMBER_OF_STUDENTS; i++) { System.out.print("Enter marks for student #" + (i + 1) + ": "); String str = reader.readline(); marks[i] = Integer.parseInt(str); // Because both readline and parseint methods can generate a runtime error, these are // enclosed in a try-catch block. The exception handler prints a trace of the stack by calling the printstacktrace method on the Exception object: catch (Exception e) { e.printstacktrace(); int total = 0; for (int i = 0; i < NUMBER_OF_STUDENTS; i++) { total += marks[i]; System.out.println("Average Marks " + (float) total / NUMBER_OF_STUDENTS); In the main method, we first create a constant for defining the number of students in the class: final int NUMBER_OF_STUDENTS = 5; 17. Two-dimensional Arrays A two-dimensional array can be visualized as a table consisting of rows and columns. Each cell of the table denotes an array element. The [] may appear as part of the type at the beginning of the declaration, or as part of the declarator for a particular variable, or both. For example: byte[] rowvector, colvector, matrix[]; This declaration is equivalent to: byte rowvector[], colvector[], matrix[][]; For example: int a, b[], c[][]; This declaration is equivalent to: int a; int[] b; int[][] c; Declarations syntax for declaring a two-dimensional array is as follows: or int arrayname [ ] [ ] ; object [] arrayname char [ ] [ ] arrayname ; int [] arrayname; Declarations of array variables that do create array objects 8 char a[] = { a, b, c, c ;

Object a[][] = new Exception[2][3]; 18. Initializing Two-dimensional Arrays 19. Initializing at Runtime To initialize an element of a two-dimensional array, you use the syntax discussed earlier for accessing the element and then use an assignment statement to initialize it: arrayname [ row ] [ col ] = data ; int[][] subjectmarks = { {1, 98, {2, 58, {3, 78, {4, 89 ; 20. Initialization Using Array Literals The same way you initialize single-dimensional and other rectangular arrays using array literals, you can initialize a nonrectangular array. Consider the following declaration: int[][] myarray = { {3, 4, 5, {1, 2 ; To determine the length of each of these arrays, we use the syntax arrayname.length. 21. arraycopy arraycopy( src, srcpos, dest, destpos, length) The components at positions srcpos through srcpos+length-1 in the source array are copied into positions destpos through destpos+length-1, respectively, of the destination array. src -- This is the source array. srcpos -- This is the starting position in the source array. dest -- This is the destination array. destpos -- This is the starting position in the destination data. length -- This is the number of array elements to be copied. class ArrayCopyDemo { public static void main(string[] args) { char[] copyfrom = {'d','e','c','a','f','f','e','i','n','a','t','e','d'; array position 0 1 2 char[] copyto = new char[7]; or { 0,1, 2, 3, 4, 5, 6 System.arraycopy(copyFrom, 2, copyto, 0, 7); copyfrom starting at array position 2 start filling at copyto array position 1 copy a total of 7 elements result of copy copyto {'c','a','f','f','e','i','n' 9

System.out.println(new String(copyTo)); The output from this program is: caffein 22. Java Keywords: The following list shows the reserved words in Java. These reserved words may not be used as constant or variable or any other identifier names. abstract assert boolean break byte case catch char class const continue default do double else enum extends final finally float for goto if implements import instanceof int interface long native new package private protected public return short static strictfp super switch synchronized this throw throws transient try void volatile while 23. Comments in Java Java supports single-line and multi-line comments very similar to c and c++. All characters available inside any comment are ignored by Java compiler. public class MyFirstJavaProgram{ /* This is my first java program. * This will print 'Hello World' as the output * This is an example of multi-line comments. */ public static void main(string []args){ // This is an example of single line comment /* This is also an example of single line comment. */ 10

System.out.println("Hello World"); 24. Using Blank Lines: A line containing only whitespace, possibly with a comment, is known as a blank line, and Java totally ignores it. up to the subclass. 25. Constructors: When discussing about classes, one of the most important sub topic would be constructors. Every class has a constructor. If we do not explicitly write a constructor for a class the Java compiler builds a default constructor for that class. Each time a new object is created, at least one constructor will be invoked. The main rule of constructors is that they should have the same name as the class. A class can have more than one constructor. Example of a constructor is given below: public class Puppy{ public Puppy(){ public Puppy(String name){ 26. Creating an Object: // This constructor has no parameters. // This constructor has one parameter, name. As mentioned previously, a class provides the blueprints for objects. So basically an object is created from a class. In Java, the new key word is used to create new objects. Each of these statements has three parts (discussed in detail below): 1. Declaration: The code set in bold are all variable declarations that associate a variable name with an object type. 2. Instantiation: The new keyword is a Java operator that creates the object. 3. Initialization: The new operator is followed by a call to a constructor, which initializes the new object. @creat a new object Point originone = new Point(23, 94); Rectangle rectone = new Rectangle(originOne, 100, 200); Rectangle recttwo = new Rectangle(50, 100); The first line creates an object of the Point class, and the second and third lines each create an object of the Rectangle class. 27. Declaring a Variable to Refer to an Object You can also declare a reference variable on its own line. For example: Point originone; If you declare originone like this, its value will be undetermined until an object is actually created and assigned to it. Simply declaring a reference variable does not create an object. For that, you need to use the new operator, as described in the next section. You must assign an object to originone before you use it in your code. Otherwise, you will get a compiler error. 11

28. Instantiating a Class The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes the object constructor. Note: The phrase "instantiating a class" means the same thing as "creating an object." When you create an object, you are creating an "instance" of a class, therefore "instantiating" a class. The new operator requires a single, postfix argument: a call to a constructor. The name of the constructor provides the name of the class to instantiate. The new operator returns a reference to the object it created. This reference is usually assigned to a variable of the appropriate type, like: Point originone = new Point(23, 94); The reference returned by the new operator does not have to be assigned to a variable. It can also be used directly in an expression. For example: int height = new Rectangle().height; This statement will be discussed in the next section. 29. Initializing an Object Here's the code for the Point class: public class Point { public int x = 0; public int y = 0; //constructor public Point(int a, int b) { x = a; y = b; 30. Accessing Instance Variables and Methods: Instance variables and methods are accessed via created objects. To access an instance variable the fully qualified path should be as follows: Example: This example explains how to access instance variables and methods of a class: public class Puppy{ int puppyage; public Puppy(String name){ // This constructor has one parameter, name. System.out.println("Passed Name is :" + name ); public void setage( int age ){ puppyage = age; 12

public int getage( ){ System.out.println("Puppy's age is :" + puppyage ); return puppyage; public static void main(string []args){ Puppy mypuppy = new Puppy( "tommy" ); /* Object creation */ mypuppy.setage( 2 ); /* Call a class method to set puppy's age */ mypuppy.getage( ); /* Call a another class method */ System.out.println("Variable Value :" + mypuppy.puppyage ); /* access instance variable */ If we compile and run the above program, then it would produce the following result: Passed Name is :tommy Puppy's age is :2 Variable Value :2 31. Java Package: In simple, it is a way of categorizing the classes and interfaces. When developing applications in Java, hundreds of classes and interfaces will be written, therefore categorizing these classes is a must as well as makes life much easier. 32. Import statements: In Java if a fully qualified name, which includes the package and the class name, is given then the compiler can easily locate the source code or classes. Import statement is a way of giving the proper location for the compiler to find that particular class. For example, the following line would ask compiler to load all the classes available in directory java_installation/java/io : import java.io.*; 33. A Simple Case Study: For our case study, we will be creating two classes. They are Employee and EmployeeTest. First open notepad and add the following code. Remember this is the Employee class and the class is a public class. Now, save this source file with the name Employee.java. The Employee class has four instance variables name, age, designation and salary. The class has one explicitly defined constructor, which takes a parameter. import java.io.*; public class Employee{ String name; int age; String designation; double salary; 13 // This is the constructor of the class Employee public Employee(String name){ this.name = name;

// Assign the age of the Employee to the variable age. public void empage(int empage){ age = empage; /* Assign the designation to the variable designation.*/ public void empdesignation(string empdesig){ designation = empdesig; /* Assign the salary to the variable salary.*/ public void empsalary(double empsalary){ salary = empsalary; /* Print the Employee details */ public void printemployee(){ System.out.println("Name:"+ name ); System.out.println("Age:" + age ); System.out.println("Designation:" + designation ); System.out.println("Salary:" + salary); As mentioned previously in this tutorial, processing starts from the main method. Therefore in-order for us to run this Employee class there should be main method and objects should be created. We will be creating a separate class for these tasks. Given below is the EmployeeTest class, which creates two instances of the class Employee and invokes the methods for each object to assign values for each variable. Save the following code in EmployeeTest.java file import java.io.*; public class EmployeeTest{ public static void main(string args[]){ Employee empone = new Employee("James Smith");/* Create two objects using constructor */ Employee emptwo = new Employee("Mary Anne"); /* Create two objects using constructor */ empone.empage(26); // Invoking methods for each object created empone.empdesignation("senior Software Engineer"); empone.empsalary(1000); empone.printemployee(); Name:Mary Anne 14 emptwo.empage(21); emptwo.empdesignation("software Engineer"); emptwo.empsalary(500); emptwo.printemployee(); Now, compile both the classes and then run EmployeeTest to see the result as follows: C :> javac Employee.java C :> vi EmployeeTest.java C :> javac EmployeeTest.java C :> java EmployeeTest Name:James Smith Age:26 Designation:Senior Software Engineer Salary:1000.0

Age:21 Designation:Software Engineer Salary:500.0 15

Passing and Returning Objects in Java 34. If Java uses the pass-by reference, why won't a swap function work? A: "Java manipulates objects 'by reference,' and all object variables are references but it passes object references to methods 'by value.'" Again Java doesn't pass method arguments by reference; it passes them by value. As a result, you cannot write a standard swap method to swap objects. Take the badswap() method for example: public void badswap(int var1, int var2) { int temp = var1; var1 = var2; var2 = temp; When badswap() returns, the variables passed as arguments will still hold their original values. The method will also fail if we change the arguments type from int to Object, since Java passes object references by value as well. Now, here is where it gets tricky: public void tricky(point arg1, Point arg2) { arg1.x = 100; arg1.y = 100; Point temp = arg1; arg1 = arg2; arg2 = temp; public static void main(string [] args) { Point pnt1 = new Point(0,0); Point pnt2 = new Point(0,0); // In the main() method, pnt1 and pnt2 are nothing more than object references System.out.println("X: " + pnt1.x + " Y: " +pnt1.y); System.out.println("X: " + pnt2.x + " Y: " +pnt2.y); System.out.println(" "); // When you pass pnt1 and pnt2 to the tricky() method, Java passes the references //by value just like any other parameter. This means the references passed to the //method are actually copies of the original references. tricky(pnt1,pnt2); System.out.println("X: " + pnt1.x + " Y:" + pnt1.y); System.out.println("X: " + pnt2.x + " Y: " +pnt2.y); If we execute this main() method, we see the following output: X: 0 Y: 0 X: 0 Y: 0 X: 100 Y: 100 X: 0 Y: 0 The method successfully alters the value of pnt1, even though it is passed by value; however, a swap of pnt1 and pnt2 fails! This is the major source of confusion. In the main() method, pnt1 and pnt2 are nothing more than object 16

references. When you pass pnt1 and pnt2 to the tricky() method, Java passes the references by value just like any other parameter. This means the references passed to the method are actually copies of the original references. Figure 1 below shows two references pointing to the same object after Java passes an object to a method. Figure 1. After being passed to a method, an object will have at least two references Java copies and passes the reference by value, not the object. Thus, method manipulation will alter the objects, since the references point to the original objects. But since the references are copies, swaps will fail. As Figure 2 illustrates, the method references swap, but not the original references. Unfortunately, after a method call, you are left with only the unswapped original references. For a swap to succeed outside of the method call, we need to swap the original references, not the copies. Figure 2. Only the method references are swapped, not the original ones O'Reilly's Java in a Nutshell by David Flanagan (see Resources) puts it best: "Java manipulates objects 'by reference,' but it passes object references to methods 'by value.'" As a result, you cannot write a standard swap method to swap objects. Tony Sintes is a principal consultant at BroadVision. Tony, a Sun-certified Java 1.1 programmer and Java 2 developer, has worked with Java since 1997. 17

35. Although Java is strictly pass by value, the precise effect differs between whether a primitive type or a reference type is passed. When we pass a primitive type to a method, it is passed by value. But when we pass an object to a method, the situation changes dramatically, because objects are passed by what is effectively call-by-reference. Java does this interesting thing that s sort of a hybrid between pass-by-value and pass-by-reference. Basically, a parameter cannot be changed by the function, but the function can ask the parameter to change itself via calling some method within it. While creating a variable of a class type, we only create a reference to an object. Thus, when we pass this reference to a method, the parameter that receives it will refer to the same object as that referred to by the argument. This effectively means that objects act as if they are passed to methods by use of call-by-reference. Changes to the object inside the method do reflect in the object used as an argument. In Java we can pass objects to methods. For example, consider the following program : // Java program to demonstrate objects // passing to methods. class ObjectPassDemo { int a, b; ObjectPassDemo(int i, int j) { a = i; b = j; // return true if o is equal to the invoking // object notice an object is passed as an // argument to method boolean equalto(objectpassdemo o) { return (o.a == a && o.b == b); // Driver class public class Test { public static void main(string args[]) { ObjectPassDemo ob1 = new ObjectPassDemo(100, 22); ObjectPassDemo ob2 = new ObjectPassDemo(100, 22); ObjectPassDemo ob3 = new ObjectPassDemo(-1, -1); Run on IDE Output: ob1 == ob2: true ob1 == ob3: false System.out.println("ob1 == ob2: " + ob1.equalto(ob2)); System.out.println("ob1 == ob3: " + ob1.equalto(ob3)); 18

Illustrative images for the above program Three objects ob1, ob2 and ob3 are created: ObjectPassDemo ob1 = new ObjectPassDemo(100, 22); ObjectPassDemo ob2 = new ObjectPassDemo(100, 22); ObjectPassDemo ob3 = new ObjectPassDemo(-1, -1); From the method side, a reference of type Foo with a name a is declared and it s initially assigned to null. boolean equalto(objectpassdemo o); As we call the method equalto, the reference o will be assigned to the object which is passed as an argument, i.e. o will refer to ob2 as following statement execute. System.out.println("ob1 == ob2: " + ob1.equalto(ob2)); 19

Now as we can see, equalto method is called on ob1, and o is referring to ob2. Since values of a and b are same for both the references, so if(condition) is true, so boolean true will be return. if(o.a == a && o.b == b) Again o will reassign to ob3 as the following statement execute. System.out.println("ob1 == ob3: " + ob1.equalto(ob3)); Now as we can see, equalto method is called on ob1, and o is referring to ob3. Since values of a and b are not same for both the references, so if(condition) is false, so else block will execute and false will be return. 20

36. So do you pass an object or a reference to an object, ie a pointer to an object!! In short, you are confusing reassigning a local variable with modifying a shared object. sb.append() does not modify the variable sb, it modifies the object that the variable references. But number = 3 modifies the variable number by assigning it a new value. Objects are shared across method calls, but local variables are not. Therefore assigning a local variable a new value will not have any effect outside the method, but modifying an object will. A bit simplified: if you use a dot (.), you are modifying an object, not a local variable. You confusion is probably due to confusing terminology. "Reference" means two different things in different context. 1) When talking about Java objects and variables, a reference is a "handle" to an object. Strictly speaking, a variable cannot hold an object, it holds a reference to an object. References can be copied, so two variables can get a reference to the same object. E.g. StringBuilder a = new StringBuilder(); StringBuilder b = a; // a and b now references the same object a.writeline("hello"); // modify the shared object b.tostring() // -> "Hello" When an objects is passed into a method as a parameter, it is also the reference that is copied, so the called method can modify the same object. This is also called "Call by sharing". void main(){ String builder b = new StringBuilder(); othermethod(b); b.tostring(); // --> "Hello" because the shared object is modified void othermethod(stringbuilder b){ b.write("hello"); // modify the shared object But the othermethod can only modify the shared object, it cannot modify any local variables in the calling method. If the called function assigns a new value to its own parameters, it doesn't affect the calling function. void main(){ String builder b = new StringBuilder(); b.writeline("hello"); othermethod(b); b.tostring(); // --> "Hello" because the shared object is NOT modified void othermethod(stringbuilder b){ b = new StringBuilder(); // assign a new object to b b.write("goodbye"); // modify the new object So you have to be clear on the distinction between modifying a shared object (through modifying fields or calling method on the object) and assigning a new value to a local variable or parameter. 2) When talking evaluation strategy (how parameters are passed into function) in general computer language theory, call-by-reference and call-by-value means something quite different. Call-by-value, which Java supports, means that values from arguments are copied into parameters when calling methods. The value can be a reference, which is why the called function will get a reference to the shared object. Confusingly Java is said to "pass references by value", which is quite distinct from call-byreference. 21 If a language supports call-by-reference, a function can change the value of a local variable in the calling function. Java does not support this, which is shown by the example above. Call-by-reference means the called function gets a reference to the local variable used as argument in the call. This notion is completely foreign to Java, where we simply do not have the concept of a reference to a local variable. We only have references to objects, never to local variables.

So what about primitives like integers, booleans etc.? These are immutable which means they cannot be modified like objects can. Since they cannot be modified, the question if they are shared or not is moot, since there is no observable difference whether they are shared or copied. public class test { public static void main(string args[]) { StringBuilder b = new StringBuilder(); b.append("hello"); System.out.println("before method call b: "+b); othermethod(b); b.tostring(); // --> "Hello" because the shared object is NOT modified System.out.println("after method call b: "+b); public static void othermethod(stringbuilder b){ b = new StringBuilder(); // assign a new object to b b.append("goodbye"); // modify the new object System.out.println("in method call b: "+b); run: before method call b: Hello in method call b: Goodbye after method call b: Hello BUILD SUCCESSFUL (total time: 0 seconds) public class test { public static void main(string args[]) { StringBuilder b = new StringBuilder(); b.append("hello"); System.out.println("before method call b: "+b); othermethod(b); b.tostring(); // --> "Hello" because the shared object is NOT modified System.out.println("after method call b: "+b); public static void othermethod(stringbuilder b){ //b = new StringBuilder(); // assign a new object to b b.append("goodbye"); // modify the object reference passed in System.out.println("in method call b: "+b); run: before method call b: Hello in method call b: HelloGoodbye after method call b: HelloGoodbye BUILD SUCCESSFUL (total time: 0 seconds) 22