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

Size: px
Start display at page:

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

Transcription

1 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.

2 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

3 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

4 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

5 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[]){

6 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 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];

7 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

8 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 ;

9 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 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

10 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

11 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 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

12 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

13 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;

14 // 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

15 Age:21 Designation:Software Engineer Salary:

16 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

17 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

18 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

19 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

20 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

21 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.

22 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

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

Java is an Object Oriented Language. As a language that has the Object Oriented feature Java supports the following fundamental concepts: PART 2 Objects and Classes Java is an Object Oriented Language. As a language that has the Object Oriented feature Java supports the following fundamental concepts: Polymorphism Inheritance Encapsulation

More information

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

Java is a high-level programming language originally developed by Sun Microsystems and released in Java runs on a variety of Java is a high-level programming language originally developed by Sun Microsystems and released in 1995. Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX.

More information

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this

More information

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

Java Programming. MSc Induction Tutorials Stefan Stafrace PhD Student Department of Computing Java Programming MSc Induction Tutorials 2011 Stefan Stafrace PhD Student Department of Computing s.stafrace@surrey.ac.uk 1 Tutorial Objectives This is an example based tutorial for students who want to

More information

Preview from Notesale.co.uk Page 9 of 108

Preview from Notesale.co.uk Page 9 of 108 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

More information

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

Outline. Why Java? (1/2) Why Java? (2/2) Java Compiler and Virtual Machine. Classes. COMP9024: Data Structures and Algorithms COMP9024: Data Structures and Algorithms Week One: Java Programming Language (I) Hui Wu Session 2, 2016 http://www.cse.unsw.edu.au/~cs9024 Outline Classes and objects Methods Primitive data types and operators

More information

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

Software Practice 1 - Basic Grammar Basic Syntax Data Type Loop Control Making Decision Software Practice 1 - Basic Grammar Basic Syntax Data Type Loop Control Making Decision Prof. Hwansoo Han T.A. Minseop Jeong T.A. Wonseok Choi 1 Java Program //package details public class ClassName {

More information

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

Outline. Java Compiler and Virtual Machine. Why Java? Naming Conventions. Classes. COMP9024: Data Structures and Algorithms COMP9024: Data Structures and Algorithms Week One: Java Programming Language (I) Hui Wu Session 1, 2015 http://www.cse.unsw.edu.au/~cs9024 Outline Classes and objects Methods Primitive data types and operators

More information

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

Computer Components. Software{ User Programs. Operating System. Hardware Computer Components Software{ User Programs Operating System Hardware What are Programs? Programs provide instructions for computers Similar to giving directions to a person who is trying to get from point

More information

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

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic BIT 3383 Java Programming Sem 1 Session 2011/12 Chapter 2 JAVA basic Objective: After this lesson, you should be able to: declare, initialize and use variables according to Java programming language guidelines

More information

WWW.STUDENTSFOCUS.COM UNIT I Introduction to java Java is an Object-Oriented Language. As a language that has the Object Oriented feature, Java supports the following fundamental concepts: Polymorphism

More information

Software Practice 1 Basic Grammar

Software Practice 1 Basic Grammar Software Practice 1 Basic Grammar Basic Syntax Data Type Loop Control Making Decision Prof. Joonwon Lee T.A. Jaehyun Song Jongseok Kim (42) T.A. Sujin Oh Junseong Lee (43) 1 2 Java Program //package details

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

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

This reference will take you through simple and practical approaches while learning Java Programming language. About the Tutorial Java is a high-level programming language originally developed by Sun Microsystems and released in 1995. Java runs on a variety of platforms, such as Windows, Mac OS, and the various

More information

JAVA: Improvised Approach to Java

JAVA: Improvised Approach to Java JAVA: Improvised Approach to Java Jorawar Singh & Jobin Abraham Department of Computer Science and Engineering, Dronacharya College Of Engineering, Gurgaon, India Abstract- Java is, as of 2014, one of

More information

3. Java - Language Constructs I

3. Java - Language Constructs I Educational Objectives 3. Java - Language Constructs I Names and Identifiers, Variables, Assignments, Constants, Datatypes, Operations, Evaluation of Expressions, Type Conversions You know the basic blocks

More information

COMP 202 Java in one week

COMP 202 Java in one week COMP 202 Java in one week... Continued CONTENTS: Return to material from previous lecture At-home programming exercises Please Do Ask Questions It's perfectly normal not to understand everything Most of

More information

Modern Programming Languages. Lecture Java Programming Language. An Introduction

Modern Programming Languages. Lecture Java Programming Language. An Introduction Modern Programming Languages Lecture 27-30 Java Programming Language An Introduction 107 Java was developed at Sun in the early 1990s and is based on C++. It looks very similar to C++ but it is significantly

More information

STRUCTURING OF PROGRAM

STRUCTURING OF PROGRAM Unit III MULTIPLE CHOICE QUESTIONS 1. Which of the following is the functionality of Data Abstraction? (a) Reduce Complexity (c) Parallelism Unit III 3.1 (b) Binds together code and data (d) None of the

More information

Java Programming. Atul Prakash

Java Programming. Atul Prakash Java Programming Atul Prakash Java Language Fundamentals The language syntax is similar to C/ C++ If you know C/C++, you will have no trouble understanding Java s syntax If you don't, it will be easier

More information

Index COPYRIGHTED MATERIAL

Index COPYRIGHTED MATERIAL Index COPYRIGHTED MATERIAL Note to the Reader: Throughout this index boldfaced page numbers indicate primary discussions of a topic. Italicized page numbers indicate illustrations. A abstract classes

More information

CSC 1214: Object-Oriented Programming

CSC 1214: Object-Oriented Programming CSC 1214: Object-Oriented Programming J. Kizito Makerere University e-mail: jkizito@cis.mak.ac.ug www: http://serval.ug/~jona materials: http://serval.ug/~jona/materials/csc1214 e-learning environment:

More information

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types

More information

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

You must declare all variables before they can be used. Following is the basic form of a variable declaration: Variable Types A variable provides us with named storage that our programs can manipulate. Each variable in Java has a specific type, which determines the size and layout of the variable's memory; the

More information

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

Java Intro 3. Java Intro 3. Class Libraries and the Java API. Outline Java Intro 3 9/7/2007 1 Java Intro 3 Outline Java API Packages Access Rules, Class Visibility Strings as Objects Wrapper classes Static Attributes & Methods Hello World details 9/7/2007 2 Class Libraries

More information

Points To Remember for SCJP

Points To Remember for SCJP Points To Remember for SCJP www.techfaq360.com The datatype in a switch statement must be convertible to int, i.e., only byte, short, char and int can be used in a switch statement, and the range of the

More information

Declarations and Access Control SCJP tips

Declarations and Access Control  SCJP tips Declarations and Access Control www.techfaq360.com SCJP tips Write code that declares, constructs, and initializes arrays of any base type using any of the permitted forms both for declaration and for

More information

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types and

More information

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

Object oriented programming. Instructor: Masoud Asghari Web page:   Ch: 3 Object oriented programming Instructor: Masoud Asghari Web page: http://www.masses.ir/lectures/oops2017sut Ch: 3 1 In this slide We follow: https://docs.oracle.com/javase/tutorial/index.html Trail: Learning

More information

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

Computer Components. Software{ User Programs. Operating System. Hardware Computer Components Software{ User Programs Operating System Hardware What are Programs? Programs provide instructions for computers Similar to giving directions to a person who is trying to get from point

More information

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp DM550 / DM857 Introduction to Programming Peter Schneider-Kamp petersk@imada.sdu.dk http://imada.sdu.dk/~petersk/dm550/ http://imada.sdu.dk/~petersk/dm857/ OBJECT-ORIENTED PROGRAMMING IN JAVA 2 Programming

More information

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

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java

More information

2 rd class Department of Programming. OOP with Java Programming

2 rd class Department of Programming. OOP with Java Programming 1. Structured Programming and Object-Oriented Programming During the 1970s and into the 80s, the primary software engineering methodology was structured programming. The structured programming approach

More information

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

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University CS5000: Foundations of Programming Mingon Kang, PhD Computer Science, Kennesaw State University Overview of Source Code Components Comments Library declaration Classes Functions Variables Comments Can

More information

An overview of Java, Data types and variables

An overview of Java, Data types and variables An overview of Java, Data types and variables Lecture 2 from (UNIT IV) Prepared by Mrs. K.M. Sanghavi 1 2 Hello World // HelloWorld.java: Hello World program import java.lang.*; class HelloWorld { public

More information

DM550 Introduction to Programming part 2. Jan Baumbach.

DM550 Introduction to Programming part 2. Jan Baumbach. DM550 Introduction to Programming part 2 Jan Baumbach jan.baumbach@imada.sdu.dk http://www.baumbachlab.net COURSE ORGANIZATION 2 Course Elements Lectures: 10 lectures Find schedule and class rooms in online

More information

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

Topics. Java arrays. Definition. Data Structures and Information Systems Part 1: Data Structures. Lecture 3: Arrays (1) Topics Data Structures and Information Systems Part 1: Data Structures Michele Zito Lecture 3: Arrays (1) Data structure definition: arrays. Java arrays creation access Primitive types and reference types

More information

CHAPTER 7 OBJECTS AND CLASSES

CHAPTER 7 OBJECTS AND CLASSES CHAPTER 7 OBJECTS AND CLASSES OBJECTIVES After completing Objects and Classes, you will be able to: Explain the use of classes in Java for representing structured data. Distinguish between objects and

More information

1 Shyam sir JAVA Notes

1 Shyam sir JAVA Notes 1 Shyam sir JAVA Notes 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write

More information

BASIC ELEMENTS OF A COMPUTER PROGRAM

BASIC ELEMENTS OF A COMPUTER PROGRAM BASIC ELEMENTS OF A COMPUTER PROGRAM CSC128 FUNDAMENTALS OF COMPUTER PROBLEM SOLVING LOGO Contents 1 Identifier 2 3 Rules for naming and declaring data variables Basic data types 4 Arithmetic operators

More information

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

Objectives. Problem Solving. Introduction. An overview of object-oriented concepts. Programming and programming languages An introduction to Java Introduction Objectives An overview of object-oriented concepts. Programming and programming languages An introduction to Java 1-2 Problem Solving The purpose of writing a program is to solve a problem

More information

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

In Java, all variables must be declared before they can be used. The basic form of a variable declaration is shown here: PART 4 Variable Types In Java, all variables must be declared before they can be used. The basic form of a variable declaration is shown here: type identifier [ = value][, identifier [= value]...] ; To

More information

Pace University. Fundamental Concepts of CS121 1

Pace University. Fundamental Concepts of CS121 1 Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction

More information

CSCI 2101 Java Style Guide

CSCI 2101 Java Style Guide CSCI 2101 Java Style Guide Fall 2017 This document describes the required style guidelines for writing Java code in CSCI 2101. Guidelines are provided for four areas of style: identifiers, indentation,

More information

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

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige CSC 308 2.0 System Development with Java Exception Handling Department of Statistics and Computer Science 1 2 Errors Errors can be categorized as several ways; Syntax Errors Logical Errors Runtime Errors

More information

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

Last Time. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings University of British Columbia CPSC 111, Intro to Computation Alan J. Hu Writing a Simple Java Program Intro to Variables Readings Your textbook is Big Java (3rd Ed). This Week s Reading: Ch 2.1-2.5, Ch

More information

CHETTINAD COLLEGE OF ENGINEERING & TECHNOLOGY JAVA

CHETTINAD COLLEGE OF ENGINEERING & TECHNOLOGY JAVA 1. JIT meaning a. java in time b. just in time c. join in time d. none of above CHETTINAD COLLEGE OF ENGINEERING & TECHNOLOGY JAVA 2. After the compilation of the java source code, which file is created

More information

CHAPTER 7 OBJECTS AND CLASSES

CHAPTER 7 OBJECTS AND CLASSES CHAPTER 7 OBJECTS AND CLASSES OBJECTIVES After completing Objects and Classes, you will be able to: Explain the use of classes in Java for representing structured data. Distinguish between objects and

More information

CompSci 125 Lecture 02

CompSci 125 Lecture 02 Assignments CompSci 125 Lecture 02 Java and Java Programming with Eclipse! Homework:! http://coen.boisestate.edu/jconrad/compsci-125-homework! hw1 due Jan 28 (MW), 29 (TuTh)! Programming:! http://coen.boisestate.edu/jconrad/cs125-programming-assignments!

More information

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

Games Course, summer Introduction to Java. Frédéric Haziza Games Course, summer 2005 Introduction to Java Frédéric Haziza (daz@it.uu.se) Summer 2005 1 Outline Where to get Java Compilation Notions of Type First Program Java Syntax Scope Class example Classpath

More information

Building Java Programs. Introduction to Programming and Simple Java Programs

Building Java Programs. Introduction to Programming and Simple Java Programs Building Java Programs Introduction to Programming and Simple Java Programs 1 A simple Java program public class Hello { public static void main(string[] args) { System.out.println("Hello, world!"); code

More information

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

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved. Java How to Program, 10/e Education, Inc. All Rights Reserved. Each class you create becomes a new type that can be used to declare variables and create objects. You can declare new classes as needed;

More information

9 Working with the Java Class Library

9 Working with the Java Class Library 9 Working with the Java Class Library 1 Objectives At the end of the lesson, the student should be able to: Explain object-oriented programming and some of its concepts Differentiate between classes and

More information

CS 231 Data Structures and Algorithms, Fall 2016

CS 231 Data Structures and Algorithms, Fall 2016 CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard

More information

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

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. Today! Build HelloWorld yourself in BlueJ and Eclipse. Look at all the Java keywords. Primitive Types. HelloWorld in BlueJ 1. Find BlueJ in the start menu, but start the Select VM program instead (you

More information

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and Classes CS 251 Intermediate Programming Methods and Classes Brooke Chenoweth University of New Mexico Fall 2018 Methods An operation that can be performed on an object Has return type and parameters Method with

More information

CS 251 Intermediate Programming Methods and More

CS 251 Intermediate Programming Methods and More CS 251 Intermediate Programming Methods and More Brooke Chenoweth University of New Mexico Spring 2018 Methods An operation that can be performed on an object Has return type and parameters Method with

More information

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

Vendor: Oracle. Exam Code: 1Z Exam Name: Java SE 7 Programmer I. Version: Demo Vendor: Oracle Exam Code: 1Z0-803 Exam Name: Java SE 7 Programmer I Version: Demo QUESTION 1 A. 3 false 1 B. 2 true 3 C. 2 false 3 D. 3 true 1 E. 3 false 3 F. 2 true 1 G. 2 false 1 Correct Answer: D :

More information

Array. Prepared By - Rifat Shahriyar

Array. Prepared By - Rifat Shahriyar Java More Details Array 2 Arrays A group of variables containing values that all have the same type Arrays are fixed length entities In Java, arrays are objects, so they are considered reference types

More information

Research Group. 3: Loops, Arrays

Research Group. 3: Loops, Arrays Research Group 3: Loops, Arrays Assignment 2 Foo Corporationneeds a program to calculate how much to pay theiremployees. 1. Pay = hours worked x base pay 2. Hours over 40 get paid 1.5 the base pay 3. The

More information

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

Java Identifiers. Java Language Essentials. Java Keywords. Java Applications have Class. Slide Set 2: Java Essentials. Copyright 2012 R.M. Java Language Essentials Java is Case Sensitive All Keywords are lower case White space characters are ignored Spaces, tabs, new lines Java statements must end with a semicolon ; Compound statements use

More information

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

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix PGJC4_JSE8_OCA.book Page ix Monday, June 20, 2016 2:31 PM Contents Figures Tables Examples Foreword Preface xix xxi xxiii xxvii xxix 1 Basics of Java Programming 1 1.1 Introduction 2 1.2 Classes 2 Declaring

More information

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

JOSE LUIS JUAREZ VIVEROS com) has a. non-transferable license to use this Student Guide Module 3 Identifiers, Keywords, and Types Objectives Upon completion of this module, you should be able to: Use comments in a source program Distinguish between valid and invalid identifiers Recognize

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers) Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement

More information

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

Lecture 2: Variables and Operators. AITI Nigeria Summer 2012 University of Lagos. Lecture 2: Variables and Operators AITI Nigeria Summer 2012 University of Lagos. Agenda Variables Types Naming Assignment Data Types Type casting Operators Declaring Variables in Java type name; Variables

More information

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

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview Introduction to Visual Basic and Visual C++ Introduction to Java Lesson 13 Overview I154-1-A A @ Peter Lo 2010 1 I154-1-A A @ Peter Lo 2010 2 Overview JDK Editions Before you can write and run the simple

More information

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

1.Which four options describe the correct default values for array elements of the types indicated? 1.Which four options describe the correct default values for array elements of the types indicated? 1. int -> 0 2. String -> "null" 3. Dog -> null 4. char -> '\u0000' 5. float -> 0.0f 6. boolean -> true

More information

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

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

More information

CS321 Languages and Compiler Design I. Winter 2012 Lecture 2

CS321 Languages and Compiler Design I. Winter 2012 Lecture 2 CS321 Languages and Compiler Design I Winter 2012 Lecture 2 1 A (RE-)INTRODUCTION TO JAVA FOR C++/C PROGRAMMERS Why Java? Developed by Sun Microsystems (now Oracle) beginning in 1995. Conceived as a better,

More information

CMSC 331 Second Midterm Exam

CMSC 331 Second Midterm Exam 1 20/ 2 80/ 331 First Midterm Exam 11 November 2003 3 20/ 4 40/ 5 10/ CMSC 331 Second Midterm Exam 6 15/ 7 15/ Name: Student ID#: 200/ You will have seventy-five (75) minutes to complete this closed book

More information

Getting started with Java

Getting started with Java Getting started with Java by Vlad Costel Ungureanu for Learn Stuff Programming Languages A programming language is a formal constructed language designed to communicate instructions to a machine, particularly

More information

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

Welcome to CSE 142! Zorah Fung University of Washington, Spring Building Java Programs Chapter 1 Lecture 1: Introduction; Basic Java Programs Welcome to CSE 142! Zorah Fung University of Washington, Spring 2015 Building Java Programs Chapter 1 Lecture 1: Introduction; Basic Java Programs reading: 1.1-1.3 1 What is computer science? computers?

More information

COP 3330 Final Exam Review

COP 3330 Final Exam Review COP 3330 Final Exam Review I. The Basics (Chapters 2, 5, 6) a. comments b. identifiers, reserved words c. white space d. compilers vs. interpreters e. syntax, semantics f. errors i. syntax ii. run-time

More information

20 Most Important Java Programming Interview Questions. Powered by

20 Most Important Java Programming Interview Questions. Powered by 20 Most Important Java Programming Interview Questions Powered by 1. What's the difference between an interface and an abstract class? An abstract class is a class that is only partially implemented by

More information

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.

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. Java How to Program, 9/e Education, Inc. All Rights Reserved. } Covered in this chapter Classes Objects Methods Parameters double primitive type } Create a new class (GradeBook) } Use it to create an object.

More information

3. Java - Language Constructs I

3. Java - Language Constructs I Names and Identifiers A program (that is, a class) needs a name public class SudokuSolver {... 3. Java - Language Constructs I Names and Identifiers, Variables, Assignments, Constants, Datatypes, Operations,

More information

Computer Science II Data Structures

Computer Science II Data Structures Computer Science II Data Structures Instructor Sukumar Ghosh 201P Maclean Hall Office hours: 10:30 AM 12:00 PM Mondays and Fridays Course Webpage homepage.cs.uiowa.edu/~ghosh/2116.html Course Syllabus

More information

Java Bytecode (binary file)

Java Bytecode (binary file) Java is Compiled Unlike Python, which is an interpreted langauge, Java code is compiled. In Java, a compiler reads in a Java source file (the code that we write), and it translates that code into bytecode.

More information

Sri Vidya College of Engineering & Technology

Sri Vidya College of Engineering & Technology UNIT I INTRODUCTION TO OOP AND FUNDAMENTALS OF JAVA 1. Define OOP. Part A Object-Oriented Programming (OOP) is a methodology or paradigm to design a program using classes and objects. It simplifies the

More information

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

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach. CMSC 131: Chapter 28 Final Review: What you learned this semester The Big Picture Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach. Java

More information

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

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance Contents Topic 04 - Inheritance I. Classes, Superclasses, and Subclasses - Inheritance Hierarchies Controlling Access to Members (public, no modifier, private, protected) Calling constructors of superclass

More information

CS260 Intro to Java & Android 03.Java Language Basics

CS260 Intro to Java & Android 03.Java Language Basics 03.Java Language Basics http://www.tutorialspoint.com/java/index.htm CS260 - Intro to Java & Android 1 What is the distinction between fields and variables? Java has the following kinds of variables: Instance

More information

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

Training topic: OCPJP (Oracle certified professional Java programmer) or SCJP (Sun certified Java programmer) Content and Objectives Training topic: OCPJP (Oracle certified professional Java programmer) or SCJP (Sun certified Java programmer) Content and Objectives 1 Table of content TABLE OF CONTENT... 2 1. ABOUT OCPJP SCJP... 4 2.

More information

Java Foundations Certified Junior Associate

Java Foundations Certified Junior Associate Java Foundations Certified Junior Associate 习题 1. When the program runs normally (when not in debug mode), which statement is true about breakpoints? Breakpoints will stop program execution at the last

More information

Java Primer 1: Types, Classes and Operators

Java Primer 1: Types, Classes and Operators Java Primer 1 3/18/14 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and M. H. Goldwasser, Wiley, 2014 Java Primer 1: Types,

More information

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

The Java Language The Java Language Reference (2 nd ed.) is the defining document for the Java language. Most beginning programming students expect The Java Language The Java Language Reference (2 nd ed.) is the defining document for the Java language. Most beginning programming students expect such a document to be totally beyond them. That expectation

More information

Java Identifiers, Data Types & Variables

Java Identifiers, Data Types & Variables Java Identifiers, Data Types & Variables 1. Java Identifiers: Identifiers are name given to a class, variable or a method. public class TestingShastra { //TestingShastra is an identifier for class char

More information

Program Fundamentals

Program Fundamentals Program Fundamentals /* HelloWorld.java * The classic Hello, world! program */ class HelloWorld { public static void main (String[ ] args) { System.out.println( Hello, world! ); } } /* HelloWorld.java

More information

Operators and Expressions

Operators and Expressions Operators and Expressions Conversions. Widening and Narrowing Primitive Conversions Widening and Narrowing Reference Conversions Conversions up the type hierarchy are called widening reference conversions

More information

Accelerating Information Technology Innovation

Accelerating Information Technology Innovation Accelerating Information Technology Innovation http://aiti.mit.edu Cali, Colombia Summer 2012 Lesson 02 Variables and Operators Agenda Variables Types Naming Assignment Data Types Type casting Operators

More information

Java Programming. Theory Manual

Java Programming. Theory Manual Java Programming Theory Manual Dr. S.N. Mishra Head of Department Computer Science Engineering and Application IGIT Sarang Ramesh kumar Sahoo Asst. Prof. Dept. of CSEA IGIT Sarang CHAPTER 1 INTRODUCTION

More information

Unit 5: More on Classes/Objects Notes

Unit 5: More on Classes/Objects Notes Unit 5: More on Classes/Objects Notes AP CS A The Difference between Primitive and Object/Reference Data Types First, remember the definition of a variable. A variable is a. So, an obvious question is:

More information

Crash Course Review Only. Please use online Jasmit Singh 2

Crash Course Review Only. Please use online Jasmit Singh 2 @ Jasmit Singh 1 Crash Course Review Only Please use online resources @ Jasmit Singh 2 Java is an object- oriented language Structured around objects and methods A method is an action or something you

More information

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

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166 Lecture 20 Java Exceptional Event Handling Dr. Martin O Connor CA166 www.computing.dcu.ie/~moconnor Topics What is an Exception? Exception Handler Catch or Specify Requirement Three Kinds of Exceptions

More information

Brief Summary of Java

Brief Summary of Java Brief Summary of Java Java programs are compiled into an intermediate format, known as bytecode, and then run through an interpreter that executes in a Java Virtual Machine (JVM). The basic syntax of Java

More information

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

Last Class. Introduction to arrays Array indices Initializer lists Making an array when you don't know how many values are in it Last Class Introduction to arrays Array indices Initializer lists Making an array when you don't know how many values are in it public class February4{ public static void main(string[] args) { String[]

More information

Chapter 2. Elementary Programming

Chapter 2. Elementary Programming Chapter 2 Elementary Programming 1 Objectives To write Java programs to perform simple calculations To obtain input from the console using the Scanner class To use identifiers to name variables, constants,

More information

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

Java in 21 minutes. Hello world. hello world. exceptions. basic data types. constructors. classes & objects I/O. program structure. Java in 21 minutes hello world basic data types classes & objects program structure constructors garbage collection I/O exceptions Strings Hello world import java.io.*; public class hello { public static

More information

Introduction to Java

Introduction to Java Introduction to Java Module 1: Getting started, Java Basics 22/01/2010 Prepared by Chris Panayiotou for EPL 233 1 Lab Objectives o Objective: Learn how to write, compile and execute HelloWorld.java Learn

More information