Chettinad College of Engineering & Technology/II-MCA/ MC9235 Web Programming WEB PROGRAMMING DEPARTMENT OF MCA

Size: px
Start display at page:

Download "Chettinad College of Engineering & Technology/II-MCA/ MC9235 Web Programming WEB PROGRAMMING DEPARTMENT OF MCA"

Transcription

1 WEB PROGRAMMING DEPARTMENT OF MCA Class II MCA Semester III Batch & Year B4 & 2012 Staff A.SALEEM RAJA, MCA.,M.Phil.,M.Tech Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 1

2 UNIT III JAVA FUNDAMENTALS Java features Java Platform Java Fundamentals Expressions, Operators, and Control Structures Classes, Packages and Interfaces Exception Handling. Objective Chapter 1 The Java Programming Language Learn the characteristics of Java Understand Java platform. Understand how a Java program is written, compiled, and executed. Origin of Java Java was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan at Sun Microsystems, Inc. in It took 18 months to develop the first working version. This language was initially called Oak but was renamed Java in Between the initial implementation of Oak in the fall of 1992 and the public announcement of Java in the spring of 1995, many more people contributed to the design and evolution of the language. Bill Joy, Arthur van Hoff, Jonathan Payne, Frank Yellin, and Tim Lindholm were key contributors to the maturing of the original prototype. Java technology is both a programming language and a platform. The Java programming language is a high-level language that can be characterized by all of the following buzzwords: Simple Architecture neutral Object oriented Portable Distributed Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 2

3 High performance Multithreaded Robust Dynamic Secure The Java Platform A platform is the hardware or software environment in which a program runs. Some of the most popular platforms like Microsoft Windows, Linux, Solaris OS, and Mac OS. Most platforms can Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 3

4 be described as a combination of the operating system and underlying hardware. The Java platform differs from most other platforms in that it's a software-only platform that runs on top of other hardware-based platforms. The Java platform has two components: Java Virtual Machine Java Application Programming Interface (API) Java Virtual Machine In the Java programming language, all source code is first written in plain text files ending with the.java extension. Those source files are then compiled into.class files by the javac compiler. A.class file does not contain code that is native to our processor; it instead contains bytecodes the machine language of the Java Virtual Machine (Java VM). The java launcher tool then runs our application with an instance of the Java Virtual Machine. Because the Java VM is available on many different operating systems, the same.class files are capable of running on Microsoft Windows, the Solaris TM Operating System (Solaris OS), Linux, or Mac OS. Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 4

5 Through the Java VM, the same application is capable of running on multiple platforms. Java Application Programming Interface (API) The API is a large collection of ready-made software components that provide many useful capabilities. It is grouped into libraries of related classes and interfaces; these libraries are known as packages. The API and Java Virtual Machine insulate the program from the underlying hardware. As a platform-independent environment, the Java platform can be a bit slower than native code. However, advances in compiler and virtual machine technologies are bringing performance close to that of native code without threatening portability. First Step into Java Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 5

6 It's time to write our first application! The following instructions are for users of Windows XP Professional, Windows XP Home, Windows Server 2003, Windows 2000 Professional, and Windows Vista. To write our first program, we'll need: 1. The Java SE Development Kit 6 (JDK 6) We can download the Windows version : /javase/downloads/index_jdk5.jsp. (Make sure you download the JDK, not the JRE.). Install the JDK 6 properly. 2. A text editor In this example, we'll use Notepad, a simple editor included with the Windows platforms. These two items are all we'll need to write your first application. Creating Our First Application Our first application, HelloWorldApp, will simply display the greeting "Hello world!". To create this program, we will: Create a source file A source file contains code, written in the Java programming language. Use any text editor to create and edit source files. Compile the source file into a.class file The Java programming language compiler (javac) takes our source file and translates its text into instructions that the Java virtual machine can understand. The instructions contained within this file are known as bytecodes. Run the program Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 6

7 The Java application launcher tool (java) uses the Java virtual machine to run our application. Create a Source File First, start our editor. Launch the Notepad editor from the Start menu by selecting Programs > Accessories > Notepad. In a new document, type in the following code: /** * The HelloWorldApp class implements an application that * simply prints "Hello World!" to standard output. */ class HelloWorldApp { public static void main(string[] args) { System.out.println("Hello World!"); // Display the string. Save the code in a file with the name HelloWorldApp.java. To do this in Notepad, first choose the File > Save As menu item. Then, in the Save As dialog box: 1. Using the Save in combo box, specify the folder (directory) where we'll save our file. In this example, the directory is java on the C drive. 2. In the File name text field, type "HelloWorldApp.java", including the quotation marks. 3. From the Save as type combo box, choose Text Documents (*.txt). 4. In the Encoding combo box, leave the encoding as ANSI. When we're finished, the dialog box should look like this. Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 7

8 Now click Save, and exit Notepad. Compile the Source File into a.class File The Save As dialog just before click Save. Bring up a shell, or "command," window. We can do this from the Start menu by choosing Command Prompt (Windows XP), or by choosing Run... and then entering cmd. The shell window should look similar to the following figure. A shell window. The prompt shows our current directory. When we bring up the prompt, our current directory is usually our home directory for Windows XP (as shown in the preceding figure). Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 8

9 To compile our source file, change our current directory to the directory where our file is located. For example, if our source directory is java on the C drive, type the following command at the prompt and press Enter: cd C:\java Now the prompt should change to C:\java>. If we enter dir at the prompt, we can see our source file, as the following figure shows. Directory listing showing the.java source file. Now we are ready to compile. At the prompt, type the following command and press Enter. javac HelloWorldApp.java The compiler has generated a bytecode file, HelloWorldApp.class. At the prompt, type dir to see the new file that was generated, as shown in the following figure. Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 9

10 Directory listing, showing the generated.class file Now that we have a.class file, we can run your program. Run the Program In the same directory, enter the following command at the prompt: java HelloWorldApp The next figure shows what you should now see: The program prints "Hello World!" to the screen. A Closer Look at the "Hello World!" Application The "Hello World!" application consists of three primary components: source code comments, the HelloWorldApp class definition, and the main method. Source Code Comments The following bold text defines the comments of the "Hello World!" application: /** * The HelloWorldApp class implements an application that * simply prints "Hello World!" to standard output. */ class HelloWorldApp { public static void main(string[] args) { System.out.println("Hello World!"); // Display the string. Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 10

11 Comments are ignored by the compiler but are useful to other programmers. The Java programming language supports three kinds of comments: /* text */ The compiler ignores everything from /* to */. /** documentation */ This indicates a documentation comment (doc comment, for short). The compiler ignores this kind of comment, just like it ignores comments that use /* and */. The javadoc tool uses doc comments when preparing automatically generated documentation. // text The compiler ignores everything from // to the end of the line. The HelloWorldApp Class Definition The following bold text begins the class definition block for the "Hello World!" application: /** * The HelloWorldApp class implements an application that * simply displays "Hello World!" to the standard output. */ class HelloWorldApp { public static void main(string[] args) { System.out.println("Hello World!"); // Display the string. As shown above, the most basic form of a class definition is: class name {... Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 11

12 The keyword class begins the class definition for a class named name, and the code for each class appears between the opening and closing curly braces marked in bold above. The main Method The following bold text begins the definition of the main method: /** * The HelloWorldApp class implements an application that * simply displays "Hello World!" to the standard output. */ class HelloWorldApp { public static void main(string[] args) { System.out.println("Hello World!"); //Display the string. In the Java programming language, every application must contain a main method whose signature is: public static void main(string[] args) The modifiers public and static can be written in either order (public static or static public), but the convention is to use public static as shown above. We can name the argument anything we want, but most programmers choose "args" or "argv". The main method accepts a single argument: an array of elements of type String. public static void main(string[] args) This array is the mechanism through which the runtime system passes information to our application. For example: java MyApp arg1 arg2 Each string in the array is called a command-line argument. Command-line arguments let users affect the operation of the application without recompiling it. Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 12

13 The "Hello World!" application ignores its command-line arguments, but we should be aware of the fact that such arguments do exist. Finally, the line: System.out.println("Hello World!"); uses the System class from the core library to print the "Hello World!" message to standard output. Objectives Learn the Java s most fundamental elements: Data types Variables Keywords Arrays Data type enum Operators Control Statements Block Breaker Statements Data Types and Variables Chapter 2 Language Basics A computer program, written in any programming language, is basically made of three elements: data, operations on data, and the logic that determines the operations. Therefore, manipulating the data (i.e. holding and operating on it) is at the core of a typical computer program. The data is held by variables, and the operations are made by using what are called operators. Data handled by the program may come in different types, such as integer or character. Every language supports certain basic data types, called primitive data types. However, a given variable may hold data of one specific type only. Data Types Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 13

14 Java defines eight simple (or elemental) types of data: byte, short, int, long, char, float, double, and boolean. These can be put in four groups: Integers This group includes byte, short, int, and long, which are for wholevalued signed numbers. Floating-point numbers This group includes float and double, which represent numbers with fractional precision. Characters This group includes char, which represents symbols in a character set, like letters and numbers. Boolean This group includes boolean, which is a special type for representing true/false values. byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). short: The short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive). int: The int data type is a 32-bit signed two's complement integer. It has a minimum value of - 2,147,483,648 and a maximum value of 2,147,483,647 (inclusive). long: The long data type is a 64-bit signed two's complement integer. It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive). float: The float data type is a single-precision 32-bit of storage. It has an approximate range from 1.4e-045 to 3.4e+038 double: The double data type is a double-precision 64-bit of storage. It has an approximate range from 4.9e 324 to 1.8e+308 boolean: The boolean data type has only two possible values: true and false. char: The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive). Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 14

15 In addition to the eight primitive data types listed above, the Java programming language also provides special support for character strings via the java.lang.string class. Enclosing our character string within double quotes will automatically create a new String object; for example, String s = "this is a string";. String objects are immutable, which means that once created, their values cannot be changed. The String class is not technically a primitive data type, but considering the special support given to it by the language. The following chart summarizes the default values for the above data types. Data Type Default Value (for fields) byte 0 short 0 int 0 long 0L float 0.0f double 0.0d char '\u0000' String (or any object) null boolean false Table: Primitive Data Types, Their Sizes, and the Ranges of Their Values Literals A literal is the source code representation of a fixed value; literals are represented directly in our code without requiring computation. Integer Literals Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 15

16 Integers are probably the most commonly used type in the typical program. Any whole number value is an integer literal. Examples are 1, 2, 3, and 42. As shown below, it's possible to assign a literal to a variable of a primitive type: boolean result = true; char capitalc = 'C'; byte b = 100; short s = 10000; int i = ; Floating-Point Literals Floating-point numbers represent decimal values with a fractional component. They can be expressed in either standard or scientific notation. Standard notation consists of a whole number component followed by a decimal point followed by a fractional component. For example, 2.0, , and represent valid standard-notation floating-point numbers. Scientific notation uses a standard-notation, floating-point number plus a suffix that specifies a power of 10 by which the number is to be multiplied. The exponent is indicated by an E or e followed by a decimal number, which can be positive or negative. Examples include 6.022E23, E 05, and 2e+100. As shown below, it's possible to assign a literal to a variable of a primitive type: double d1 = 123.4; double d2 = 1.234e2; // same value as d1, but in scientific notation float f1 = 123.4f; Boolean Literals Boolean literals are simple. There are only two logical values that a boolean value can have, true and false. The values of true and false do not convert into any numerical representation. The true literal in Java does not equal 1, nor does the false literal equal 0. In Java, they can only be assigned to variables declared as boolean, or used in expressions with Boolean operators. Character Literals Characters in Java are indices into the Unicode character set. They are 16-bit values that can be converted into integers and manipulated with the integer operators, such as the addition and Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 16

17 subtraction operators. A literal character is represented inside a pair of single quotes. All of the visible ASCII characters can be directly entered inside the quotes, such as a, z, String Literals String literals in Java are specified like they are in most other languages by enclosing a sequence of characters between a pair of double quotes. Examples of string literals are Hello World two\nlines \ This is in quotes\ Character Escape Sequences Escape Sequence Description \ddd Octal character (ddd) \uxxxx Hexadecimal UNICODE character (xxxx) \ Single quote \ Double quote \\ Backslash \r Carriage return \n New line (also known as line feed) \f Form feed \t Tab \b Backspace Variables The variable is the basic unit of storage in a Java program. A variable is defined by the combination of an identifier, a type, and an optional initializer. In addition, all variables have a scope, which defines their visibility, and a lifetime. Declaring the variable 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]...] ; Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 17

18 The type is one of Java s atomic types, or the name of a class or interface. The identifier is the name of the variable. We can initialize the variable by specifying an equal sign and a value. Keep in mind that the initialization expression must result in a value of the same (or compatible) type as that specified for the variable. To declare more than one variable of the specified type, use a comma-separated list. Here are several examples of variable declarations of various types. Note that some include an initialization. int a, b, c; // declares three ints, a, b, and c. int d = 3, e, f = 5; // declares three more ints, initializing d and f. byte z = 22; // initializes z. double pi = ; // declares an approximation of pi. char x = 'x'; // the variable x has the value 'x'. Java allows variables to be initialized dynamically, using any expression valid at the time the variable is declared. Naming the Variables: Legal Identifiers Each variable has a name, given to it by the programmer while declaring the variable. This name is called an identifier. For example, v1 is an example of an identifier. Following are the rules to name a variable (or define an identifier): The first character of an identifier must be a letter, a dollar sign ($), or an underscore (_). A character other than the first character in an identifier may be a letter, a dollar sign, an underscore, or a digit. None of the Java language keywords (or reserved words) can be used as identifiers. Scope and Lifetime of Variables Java allows variables to be declared within any block. A block is begun with an opening curly brace and ended by a closing curly brace. A block defines a scope. Thus, each time we start a new block, we are creating a new scope. A scope determines what objects are visible to other parts of our program. It also determines the lifetime of those objects. A variable can be accessed only within its scope, which is the area in the program from which it can be legally referred to. From the viewpoint of scope, variables can be classified into three categories: Local variables: All the variables declared inside a method. Their scope is the method. In other words, they can be accessed only from inside the method in which they are Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 18

19 declared, and they are destroyed when the method completes. Local variables are also called stack variables because they live on the stack. Instance variables: The variables declared inside a class but outside of any method. Their scope is the instance of the class in which they are declared. These variables, for example, can be used to maintain a counter at instance level. Instance variables live on the heap. Static variables: The instance variables declared with the modifier static. Their scope is the class in which they are declared. These variables can be used to maintain a counter at class level, which is a variable shared by all the objects of the class. Reserved Names: The Keywords Java keywords are the reserved words in the Java language. Each keyword has a specific meaning within the language. Therefore, a programmer cannot use these words to name the variables, classes, or methods. For example, the word int is a keyword used to declare a variable of type integer. The Java keywords are listed in Table Below. Table: Keywords in Java Keywords use letters only; they do not use special characters (such as $, _, etc.) or digits. All keywords are in all lowercase letters. Arrays Arrays in Java are objects that are used to store multiple variables of the same type. These variables may be of primitive types or of non-primitive types (i.e. object references). Whether an array stores a primitive variable or an object reference, the array itself is always an object. Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 19

20 We declare an array by specifying the data type of the elements that the array will hold, followed by the identifier, plus a pair of square brackets before or after the identifier. The data type may be a primitive or a class. Arrays of any type can be created and may have one or more dimensions. A specific element in an array is accessed by its index. Arrays offer a convenient means of grouping related information. Making an array of data items consists of three logical steps: 1. Declare an array variable. 2. Create an array of a certain size and assign it to the array variable. 3. Assign a value to each array element. An array of ten elements Declaring an Array Variable Following is an example of declaring an array variable of primitive data type int: int[] scores; The following is also legal: int scores []; Similarly, the following is an example of declaring an array variable of a non-primitive data type, where Student is the name of a class: Student[] students; Again, the following is also a legal declaration: Student students[]; It is not legal to include the size of an array in the declaration. For example, the compiler will generate an error on the following statement: int [5] scores; The size is included when we create the array. Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 20

21 Creating an Array Because an array is an object, we create it with the new operator. An array of primitives is created and assigned to an already declared array variable as shown in this example: scores = new int[3]; This statement creates an array of three elements that can hold integer values and assigns it to the array variable scores, which is already declared. An array of a non-primitive data type is created and assigned to an already declared array variable as shown in the following example: students = new Student[3]; This statement creates an array of three elements that can hold object references (which will reference to the objects of the Student class) and assigns it to the array variable students, which we have already declared. Assigning Values to Array Elements Each element of an array needs to be assigned a value, which may be data of a primitive type or a reference to an object, depending upon the type of the array. The value is assigned by referring to the array element, as shown in the following code fragment: scores[0] = 75; scores[1] = 80; scores[2] = 100; So, elements of an int array just act like int variables. Similarly, elements in an object array act like object reference variables: students[0] = new Student(); students[1] = new Student(); students[2] = new Student(); This code will create three Student objects on the heap and assign each of them to the corresponding array element. Note that the index value for an array starts from 0; that is, if an array is of size 5, the index for the first element is 0 and the index for the last element is 4. Also, once we have created an array of a specific size, we cannot change the size. Multidimensional Arrays Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 21

22 In Java, multidimensional arrays are actually arrays of arrays. To declare a multidimensional array variable, specify each additional index using another set of square brackets. For example, the following declares a two-dimensional array variable called twod. int twod[][] = new int[4][5]; This allocates a 4 by 5 array and assigns it to twod. Internally this matrix is implemented as an array of arrays of int. Conceptually, this array will look like the one shown in Figure. Program: One Dimensional Array //Program that creates an array of the number of days in each month. // Demonstrate a one-dimensional array. class Array { public static void main(string args[]) { int month_days[]; month_days = new int[12]; month_days[0] = 31; month_days[1] = 28; month_days[2] = 31; month_days[3] = 30; month_days[4] = 31; Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 22

23 month_days[5] = 30; month_days[6] = 31; month_days[7] = 31; month_days[8] = 30; month_days[9] = 31; month_days[10] = 30; month_days[11] = 31; System.out.println("April has " + month_days[3] + " days."); When we run this program, it prints the number of days in April. Note: Java strictly checks to make sure we do not accidentally try to store or reference values outside of the range of the array. The Java run-time system will check to be sure that all array indexes are in the correct range. (In this regard, Java is fundamentally different from C/C++, which provides no run-time boundary checks.) Program: Two Dimensional Arrays // Demonstrate a two-dimensional array. class TwoDArray { public static void main(string args[]) { int twod[][]= new int[4][5]; int i, j, k = 0; for(i=0; i<4; i++) for(j=0; j<5; j++) { twod[i][j] = k; k++; for(i=0; i<4; i++) { for(j=0; j<5; j++) System.out.print(twoD[i][j] + " "); System.out.println(); Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 23

24 This program generates the following output: Data Type enum The data type enum, introduced in J2SE 5.0, is useful when we want a variable to hold only a predetermined set of values. We should use enum any time as we need a fixed set of constants, including natural enumerated types such as days of the week. We can define an enum variable in two steps: 1. Define the enum type with a set of named values. 2. Define a variable to hold one of those values. Following is an example: enum AllowedCreditCard {VISA, MASTER_CARD, AMERICAN_EXPRESS; AllowedCreditCard visa = AllowedCreditCard.VISA; A value stored in an instance of an enum is retrieved by referring to it just like a variable, as shown in this example: System.out.println("The allowed credit card value: " + visa) Operators in Java Operators are special symbols that perform specific operations on one, two, or three operands, and then return a result. Java provides a rich operator environment. First, let s look at the operators in a rather generic way. From the perspective of the number of operands they operate on, Java operators can be classified into the following three categories: Unary operators: Require only one operand. For example: ++ increments the value of its operand by one. Binary operators: Require two operands. For example: + adds the values of its two operands. Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 24

25 Ternary operators: Operate on three operands. The Java programming language has one ternary operator (?:). Most of its operators can be divided into the following four groups: arithmetic, bitwise, relational, and logical. Java also defines some additional operators that handle certain special situations. Arithmetic Operators In mathematics, we are all familiar with the arithmetic operators, which perform arithmetic operations on their operands, and apply to operands of any numeric type. The arithmetic operators supported by the Java programming language are summarized in Table Table 2.7.1: Arithmetic Operators The Unary Arithmetic Operators The unary operators are of two kinds: those that just change the sign, called the sign unary operators, and those that change the absolute value of the operand, called increment and decrement operators. The Sign Unary Operators: + and These operators do not change the absolute value of the operand, only the sign. The + operator does not have any real effect. The operator multiplies the value of the operand by -1 before assigning it to another operand. However, it does not change the absolute value of the operand on which it operates. The Increment and Decrement Operators: ++ and -- The operators ++ and -- increment and decrement the value of an operand by 1. Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 25

26 Table 2.7.2: Increment and Decrement Operators: ++ and -- Bitwise Logical Operators Java offers some logical operators that are used to manipulate (test, or set) the bits of an integer (byte, short, char, int, long) value. These operators act upon the individual bits of their operands. They are summarized in the following table: Table 2.7.3: Bitwise Logical Operators The bitwise logical operators are &,, ^, and ~. The following table shows the outcome of each operation. Relational Operators A relational operator, also called a comparison operator, compares the values of two operands and returns a Boolean value: true or false. In other words, a comparison operator tests a relationship between two operands to be true or false. For this reason, comparison operators are also called relational operators. The operand could be any of the numeric operands. Table below summarizes the comparison operators. Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 26

27 Table 2.7.4: Relational Operators Logical Operators Logical operators are used to combine more than one condition that may be true or false. In other words, logical operators deal with connecting the boolean values. These operators are called short-circuit logical operators. The outcome of these operators is, of course, a boolean. These operators are summarized in Table. Table 2.7.5: Logical Operators Assignment Operators An assignment operator is used to set (or reset) the value of a variable. The most common and obvious assignment operator is =. For example, the following code statement declares a variable x of type int and sets its value to 7: int x = 7; There are several shortcut assignment operators that reduce down to the basic assignment operator. These shortcut assignment operators are summarized in Table. Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 27

28 Table 2.7.6: Shortcut Assignment Operators Advanced Operators In addition to the operators discussed so far in this chapter, Java offers a few more operators, summarized in Table: Operator Precedence Table 2.7.7: Advanced Operators Operator Precedence Operators Precedence postfix expr++ expr-- unary ++expr --expr +expr -expr ~! multiplicative * / % additive + - shift << >> >>> Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 28

29 relational < > <= >= instanceof equality ==!= bitwise AND & bitwise exclusive OR ^ bitwise inclusive OR logical AND && logical OR ternary? : assignment = += -= *= /= %= &= ^= = <<= >>= >>>= Control statements in Java The order in which the code statements will be executed is an important component of the internal architecture of a program. In a given block, the program is executed sequentially one statement at a time starting from the first statement at the top and proceeding toward the bottom. This scheme, without any additional flow logic, will execute each statement precisely once. However, if a programming language is to allow us to write programs to solve real-life problems, it must recognize the conditional logic that is at work in real life. A set of statements may be executed once, more than once, or skipped altogether, and the decision may be made at runtime (that is, at the time of program execution). This makes programming more dynamic, efficient, and powerful. Java s program control statements can be put into the following categories: selection, iteration, and jump. Selection statements allow our program to choose different paths of execution based upon the outcome of an expression or the state of a variable. Iteration statements enable program execution to repeat one or more statements (that is, iteration statements form loops). Jump statements allow your program to execute in a nonlinear fashion. Selection statements The selection statements, also called the decision statements, are of two types: if and switch. if Statements Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 29

30 The if statements can handle a range of conditions starting from very simple to quite sophisticated. Accordingly, they come in four different constructs: if, if-else, if-else if, and if-else if-else. The if Construct The if construct allows the execution of a single statement or a block of statements enclosed within curly braces. The syntax of the if construct is shown here: if( <expression> ) { // if <expression> returns true, the statements in this // blocks are executed. If there is only one statement in the block, the curly braces are not mandatory, but it is a good programming practice to use the curly braces regardless of whether there is one or more statements to execute. Following is an example of an if statement: if ( x > 0 ) { System.out.println("x is greater than zero."); The if-else Construct We can handle two blocks of code with the if-else construct. If a condition is true, the first block of code will be executed, otherwise the second block of code will be executed. The syntax for the if-else construct follows: if( <expression> ) { // if <expression> returns true, statements in this block are executed. else { // if <expression> is false, then statements in this block will be executed. For example, consider the following code fragment: if ( x > 0 ) { System.out.println("x is greater than zero."); else { Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 30

31 System.out.println("x is not greater than zero."); The if-else if Construct With the if-else if construct we can handle multiple blocks of code, and only one of those blocks will be executed at most. The syntax for the if-else construct follows: if( <expression1> ) { // if <expression1> returns true, statements in this block are executed. else if ( <expression2>) { // if <expression1> is false and <expression2> is true, then statements in this block will be executed. else if (<expression3>) { // if <expression1> is false, and <expression2> is false, and <expression3> is true, then statements in this block will be executed. The if-else if-else Construct The syntax for the if-else if-else construct follows: if( <expression1> ) { // if <expression1> returns true, statements in this block are executed. else if (<expression2>) { // if <expression1> is false and <expression2> is true, then statements in this block will be executed. else if (<expression3>) { // if <expression1> is false and <expression2> is false, and <expression3> is true, then statements in this block will be executed. Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 31

32 else { // if the expression in the if statement and the expressions in all the else if statements were false, then the statements in this block will be executed. Program: if-else-if statements // Demonstrate if-else-if statements. class IfElse { public static void main(string args[]) { int month = 4; // April String season; if(month == 12 month == 1 month == 2) season = "Winter"; else if(month == 3 month == 4 month == 5) season = "Spring"; else if(month == 6 month == 7 month == 8) season = "Summer"; else if(month == 9 month == 10 month == 11) season = "Autumn"; else season = "Bogus Month"; System.out.println("April is in the " + season + "."); Here is the output produced by the program: April is in the Spring. switch Statements The switch statement is Java s multi-way branch statement. It provides an easy way to dispatch execution to different parts of our code based on the value of an expression. As such, it often Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 32

33 provides a better alternative than a large series of if-else-if statements. Here is the general form of a switch statement: switch (expression) { case value1: // statement sequence break; case value2: // statement sequence break;... case valuen: // statement sequence break; default: // default statement sequence The expression must be of type byte, short, int, or char; each of the values specified in the case statements must be of a type compatible with the expression. Each case value must be a unique literal (that is, it must be a constant, not a variable). Duplicate case values are not allowed. Program: switch Statement // A simple example of the switch. class SampleSwitch { public static void main(string args[]) { for(int i=0; i<6; i++) switch(i) { case 0: System.out.println("i is zero."); break; case 1: System.out.println("i is one."); break; Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 33

34 case 2: System.out.println("i is two."); break; case 3: System.out.println("i is three."); break; default: System.out.println("i is greater than 3."); The output produced by this program is shown here: i is zero. i is one. i is two. i is three. i is greater than 3. i is greater than 3. Iteration Statements There will be situations in programming in which we want to have a block of statements executed over and over again as long as a certain condition is true. This is accomplished by using the iteration statements. In order to facilitate iterative execution, Java offers four iteration constructs: while, do-while, for, and for-each. The while Loop Construct The while loop construct handles the situation in which a block is executed for the first time only when a condition is true. After execution the condition is checked again, and as long as the condition stays true, the block is executed repeatedly. The syntax for the while loop construct follows: while ( <expression> ) { // if the <expression> is true, execute the statements in this block. // After the execution, go back to check the condition again. Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 34

35 The <expression> in the parentheses of while is a boolean condition that returns true or false. For example, consider a while loop that counts down from 10, printing exactly ten lines of tick : Program: while Loop // Demonstrate the while loop. class While { public static void main(string args[]) { int n = 10; while(n > 0) { System.out.println("tick " + n); n--; When we run this program, it will tick ten times: tick 10 tick 9 tick 8 tick 7 tick 6 tick 5 tick 4 tick 3 tick 2 tick 1 The do-while Loop Construct The do-while loop always executes its body at least once, because its conditional expression is at the bottom of the loop. The syntax for the do-while construct follows: do { // Execute the statements in this block. while ( <expression> ); Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 35

36 Again, the <expression> is a boolean condition that returns true or false. When the execution control arrives at do, it enters the do block. After executing the statements in the do block, the expression specified by <expression> is executed. If it returns true, the control goes back to the do statement and the do block is executed again. Note: The do-while loop will be executed at least once, whereas, depending upon the expression, the while loop may not be executed at all. For example, Here is a reworked version of the tick program that demonstrates the do-while loop. It generates the same output as before. Program: do-while Loop // Demonstrate the do-while loop. class DoWhile { public static void main(string args[]) { int n = 10; do { System.out.println("tick " + n); n--; while(n > 0); When we run this program, it will tick ten times: tick 10 tick 9 tick 8 tick 7 tick 6 tick 5 tick 4 tick 3 tick 2 tick 1 Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 36

37 The for Loop Construct The for loop is the most sophisticated of all the loop constructs and provides a richer functionality as a result. The syntax for the for loop construct is shown here: for ( <statement>; <test>; <expression>) { // if the <test> is true, execute the block. The following list explains the arguments (the three elements appearing in the parentheses) of the for construct: <statement>: Often used to initialize the iteration variable that will monitor the iteration (e.g. i=0). The variable may also be declared and initialized (e.g. int i = 0). The <statement> is executed only once, when the control comes to the for loop for the first time. <test>: A boolean condition that returns either true or false. The for block is executed repeatedly until the <test> returns false. Depending upon the test, and the value of the iteration variable, the for block may never be executed. <expression>: Executed immediately after the execution of the for block, each time the for block is executed. Generally, it is used to change the value of the iteration variable, also called the loop counter. If the <test> returns true, the for block will be executed. Immediately after the block execution, <expression> will be executed. Then the <test> will be executed again. If it returns true, the block will be executed again. Following this, <expression> will be executed again, and so on. When <test> returns false, the execution control jumps to the first statement immediately after the for block. Program: do-while Loop // Demonstrate the for loop. class ForTick { public static void main(string args[]) { int n; for(n=10; n>0; n--) System.out.println("tick " + n); Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 37

38 When we run this program, it will tick ten times: tick 10 tick 9 tick 8 tick 7 tick 6 tick 5 tick 4 tick 3 tick 2 tick 1 More About Arguments of the for() Construct: Beware! We must remember some rules for the elements in the parentheses of the for() construct. To start, the <statement> in for() has to be a code statement. For example, if i is already declared and initialized, the following code line will generate a compiler error: for (i; i<5; i++) However, the following code line will work: for (i=i+1; i<5; i++) The <statement> may have two non-declarative expressions, separated by a comma. For example, the following is a valid code line: for( i++, j++ ; i+j < 5 ; i++) However, the <statement> cannot have multiple declarations or a mix of a declarative and nondeclarative statement. For example, both of the following lines of code are illegal and will generate compiler errors: for ( int i = 0, int j = 0; i+j < 5; i++) for (int i = 0; i = i + 1; i + j < 5; i++ ) Any of the three components in the parentheses of for() may be omitted, but the semicolons cannot be. For example, the following is a legal code fragment that generates an infinite loop: for(; ;) { System.out.println ("Round and round we go for ever."); Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 38

39 However, the following code fragment will generate a compiler error: for() { System.out.println ("Round and round we go for ever."); Another thing to note is that a variable declared inside a for loop will not exist (and hence cannot be used) outside the for loop. If a variable is declared before the for loop, even though initialized in the for() statement, it will exist (and hence can be used) even after the for loop. Note: A variable declared inside a for loop cannot be accessed from outside the for loop, whereas a variable only initialized inside a for loop, and declared before it, can also be accessed after the for loop is executed. A programmer often iterates over the elements of a list, array, or any other collection. Previously, there was not an automated way to do it in Java, and hence such looping was prone to errors. J2SE 5.0 has introduced a solution to this problem in the form of the for-each loop construct. The for-each Loop Construct The for-each loop construct, introduced in J2SE 5.0, makes it easier and less error prone to iterate through the elements of an array and any other collection. The syntax for this construct is shown here: for (<variable> : <collection>) { // the block code It sets the <variable> to the first element of the collection during the first iteration, to the second element during the second iteration, and so on. Iterations are performed automatically for all the elements of the collection. Program: for-each Loop class ForEachTest { public static void main(string[] args) { int[] myarray = new int[3]; myarray[0]= 10; myarray[1] = 20; Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 39

40 myarray[2] = 30; for(int i : myarray) { System.out.println (i); The output of program follows: Block Breaker Statements There will be situations in a program when you want to quit either the current iteration of a loop or the entire loop altogether. To handle such situations, Java offers two block breaker statements: continue and break. The continue Statement The continue statement, in its simplest form, has the following syntax: continue; When this statement is executed, the current iteration of the block execution is terminated, and the control jumps to the next iteration of the block according to the following rules: If the continue statement is in the while, or do-while, block, control jumps to the Boolean condition in the parentheses of while. If the continue statement is in the for block, control jumps to the <expression> in the for (<statement>; <test>; <expression>) statement. For example, consider the following code fragment: for ( int i = 0; i < 5; i++ ) { if ( i == 3 ) continue; System.println ( "The value of i is " + i ); This generates the following output: The value of i is 0 The value of i is 1 Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 40

41 The value of i is 2 The value of i is 4 The line the value of i is 3 is missing from the output due to the continue statement. Note: The continue statement is only valid inside a loop. If we write it outside the loop, your program will generate a compiler error. The break Statement Whereas the continue statement breaks the execution control out of the current block iteration to the next iteration, the break statement throws the execution control out of the block altogether. However, note that a break statement may be used either in a loop or in a switch block. The break statement, in its simplest form, has the following syntax: break; For example, consider the following code fragment: for ( int i = 3; i >0; i-- ) { for (int j = 0; j<4; j++) { System.out.println ( "i=" + i + " and j=" + j); if ( i == j ) break; This will generate the following output: i=3 and j=0 i=3 and j=1 i=3 and j=2 i=3 and j=3 i=2 and j=0 i=2 and j=1 i=2 and j=2 i=1 and j=0 i=1 and j=1 Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 41

42 Objective Chapter 3 Working with Classes and Objects At the end of this session, students can learn Basics of class and objects. Methods and Modifiers Constructors Usage of final, finalize () Nested and Inner Class Command line Arguments Classes The class is the basis for object-oriented programming. The data and the operations on the data are encapsulated in a class. In other words, a class is a template that contains the data variables and the methods that operate on those data variables following some logic. So, the class is the foundation on which the entire Java language is built. All the programming activity happens inside classes. The data variables and the methods in a class are called class members. Variables, which hold the data (or point to it in case of reference variables), are said to represent the state of an object (that may be created out of the class), and the methods constitute its behavior. Defining Classes A class is declared by using the keyword class. The general syntax for a class declaration is <modifier> class <classname> { <classname> specifies the name of the class, class is the keyword, and <modifier> specifies some characteristics of the class. The <modifier> specification is optional, but the other two elements in the declaration are mandatory. We can broadly group the modifiers into the following two categories: Access modifiers: Determine from where the class can be accessed: private, protected, and public. If you do not specify an access modifier, the default access is assumed. Other modifiers: Specify how the class can be used: abstract, final, and strictfp. As an example of an access modifier, consider the following class declaration: Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 42

43 class MyClass { Because no access modifier is declared in the preceding class declaration, the default access is assumed. As an example of a non-access modifier, we can declare an abstract class by specifying the abstract modifier, as in the following: abstract class MyClass { The class code that contains the class members (variables and methods) is written inside two curly braces. Program below presents an example of a full definition (declaration plus code) of a simple class. Program: Class class ClassRoom { private String roomnumber; private int totalseats = 60; private static int totalrooms = 0; void setroomnumber(string rn) { roomnumber = rn; String getroomnumber() { return roomnumber; void settotalseats(int seats) { totalseats = seats; int gettotalseats() { return totalseats; The class defined in above program has the following class members: The instance variables roomnumber and totalseats The class (static) variable totalrooms Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 43

44 The methods setroomnumber( ), getroomnumber(), settotalseats( ), and gettotalseats() In object-oriented programming, a problem is solved by creating objects in a program that correspond to the objects in the real problem, such as student and classroom. A class is a template or a blueprint for creating objects. Creating Objects When we write a class, we must keep in mind the objects that will be created from it, which correspond to the objects in the problem that is being solved by the program. We may also look upon the classes as data types. We can declare a variable (a reference variable) of a class and assign it a value with the following syntax: <classname> <variablename> = new <classconstructor> <variablename> in this case is the name of the object reference that will refer to the object that we want to create, and we choose this name. <classname> is the name of an existing class, and <classconstructor> is a constructor of the class. The right side of the equation creates the object of the class specified by <classname> with the new operator, and assigns it to <variablename> (i.e. <variablename> points to it). Creating an object from a class this way is also called instantiating the class. For example, consider the following code fragment: class ClassRoomManager { public static void main(string[] args) { ClassRoom roomone = new ClassRoom(); roomone.setroomnumber("mh227"); roomone.settotalseats(30); System.out.println("Room number: " + roomone.getroomnumber()); System.out.println("Total seats: " + roomone.gettotalseats()); This program instantiates the ClassRoom class presented in above program: Class, and invokes its methods. If we compile both classes, ClassRoom and ClassRoomManager, and execute ClassRoomManager, the following will be the output: Room number: MH227 Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 44

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

These two items are all you'll need to write your first application reading instructions in English.

These two items are all you'll need to write your first application reading instructions in English. IFRN Instituto Federal de Educação, Ciência e Tecnologia do RN Curso de Tecnologia em Análise e Desenvolvimento de Sistemas Disciplina: Inglês Técnico Professor: Sandro Luis de Sousa Aluno(a) Turma: Data:

More information

CS11 Java. Fall Lecture 1

CS11 Java. Fall Lecture 1 CS11 Java Fall 2006-2007 Lecture 1 Welcome! 8 Lectures Slides posted on CS11 website http://www.cs.caltech.edu/courses/cs11 7-8 Lab Assignments Made available on Mondays Due one week later Monday, 12 noon

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

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

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

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

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

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

4 Programming Fundamentals. Introduction to Programming 1 1

4 Programming Fundamentals. Introduction to Programming 1 1 4 Programming Fundamentals Introduction to Programming 1 1 Objectives At the end of the lesson, the student should be able to: Identify the basic parts of a Java program Differentiate among Java literals,

More information

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson Introduction History, Characteristics of Java language Java Language Basics Data types, Variables, Operators and Expressions Anatomy of a Java Program

More information

Lecture 1: Overview of Java

Lecture 1: Overview of Java Lecture 1: Overview of Java What is java? Developed by Sun Microsystems (James Gosling) A general-purpose object-oriented language Based on C/C++ Designed for easy Web/Internet applications Widespread

More information

Outline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors

Outline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors Outline Overview history and advantage how to: program, compile and execute 8 data types 3 types of errors Control statements Selection and repetition statements Classes and methods methods... 2 Oak A

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

1 Lexical Considerations

1 Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2013 Handout Decaf Language Thursday, Feb 7 The project for the course is to write a compiler

More information

Basics of Java Programming

Basics of Java Programming Basics of Java Programming Lecture 2 COP 3252 Summer 2017 May 16, 2017 Components of a Java Program statements - A statement is some action or sequence of actions, given as a command in code. A statement

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

Java Language Basics: Introduction To Java, Basic Features, Java Virtual Machine Concepts, Primitive Data Type And Variables, Java Operators,

Java Language Basics: Introduction To Java, Basic Features, Java Virtual Machine Concepts, Primitive Data Type And Variables, Java Operators, Java Language Basics: Introduction To Java, Basic Features, Java Virtual Machine Concepts, Primitive Data Type And Variables, Java Operators, Expressions, Statements and Arrays. Java technology is: A programming

More information

Language Fundamentals Summary

Language Fundamentals Summary Language Fundamentals Summary Claudia Niederée, Joachim W. Schmidt, Michael Skusa Software Systems Institute Object-oriented Analysis and Design 1999/2000 c.niederee@tu-harburg.de http://www.sts.tu-harburg.de

More information

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: JAVA OPERATORS GENERAL Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: Arithmetic Operators Relational Operators Bitwise Operators

More information

A variable is a name that represents a value. For

A variable is a name that represents a value. For DECLARE A VARIABLE A variable is a name that represents a value. For example, you could have the variable myage represent the value 29. Variables can be used to perform many types of calculations. Before

More information

13 th Windsor Regional Secondary School Computer Programming Competition

13 th Windsor Regional Secondary School Computer Programming Competition SCHOOL OF COMPUTER SCIENCE 13 th Windsor Regional Secondary School Computer Programming Competition Hosted by The School of Computer Science, University of Windsor WORKSHOP I [ Overview of the Java/Eclipse

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

Lexical Considerations

Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Fall 2005 Handout 6 Decaf Language Wednesday, September 7 The project for the course is to write a

More information

Java Overview An introduction to the Java Programming Language

Java Overview An introduction to the Java Programming Language Java Overview An introduction to the Java Programming Language Produced by: Eamonn de Leastar (edeleastar@wit.ie) Dr. Siobhan Drohan (sdrohan@wit.ie) Department of Computing and Mathematics http://www.wit.ie/

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

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments. Java How to Program, 9/e Education, Inc. All Rights Reserved. } Java application programming } Use tools from the JDK to compile and run programs. } Videos at www.deitel.com/books/jhtp9/ Help you get started

More information

Lexical Considerations

Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2010 Handout Decaf Language Tuesday, Feb 2 The project for the course is to write a compiler

More information

Programming. Syntax and Semantics

Programming. Syntax and Semantics Programming For the next ten weeks you will learn basic programming principles There is much more to programming than knowing a programming language When programming you need to use a tool, in this case

More information

Introduction To Java. Chapter 1. Origins of the Java Language. Origins of the Java Language. Objects and Methods. Origins of the Java Language

Introduction To Java. Chapter 1. Origins of the Java Language. Origins of the Java Language. Objects and Methods. Origins of the Java Language Chapter 1 Getting Started Introduction To Java Most people are familiar with Java as a language for Internet applications We will study Java as a general purpose programming language The syntax of expressions

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

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal Expressions and Data Types CSC 121 Spring 2017 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

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

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail. OOP in Java 1 Outline 1. Getting started, primitive data types and control structures 2. Classes and objects 3. Extending classes 4. Using some standard packages 5. OOP revisited Parts 1 to 3 introduce

More information

Java+- Language Reference Manual

Java+- Language Reference Manual Fall 2016 COMS4115 Programming Languages & Translators Java+- Language Reference Manual Authors Ashley Daguanno (ad3079) - Manager Anna Wen (aw2802) - Tester Tin Nilar Hlaing (th2520) - Systems Architect

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

Java Notes. 10th ICSE. Saravanan Ganesh

Java Notes. 10th ICSE. Saravanan Ganesh Java Notes 10th ICSE Saravanan Ganesh 13 Java Character Set Character set is a set of valid characters that a language can recognise A character represents any letter, digit or any other sign Java uses

More information

Object-Oriented Programming

Object-Oriented Programming Object-Oriented Programming Java Syntax Program Structure Variables and basic data types. Industry standard naming conventions. Java syntax and coding conventions If Then Else Case statements Looping (for,

More information

Operators. Java operators are classified into three categories:

Operators. Java operators are classified into three categories: Operators Operators are symbols that perform arithmetic and logical operations on operands and provide a meaningful result. Operands are data values (variables or constants) which are involved in operations.

More information

Data Types, Variables and Arrays. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

Data Types, Variables and Arrays. OOC 4 th Sem, B Div Prof. Mouna M. Naravani Data Types, Variables and Arrays OOC 4 th Sem, B Div 2016-17 Prof. Mouna M. Naravani Identifiers in Java Identifiers are the names of variables, methods, classes, packages and interfaces. Identifiers must

More information

Java Basic Datatypees

Java Basic Datatypees Basic Datatypees Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in the memory. Based on the data type of a variable,

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

Introduction to Java & Fundamental Data Types

Introduction to Java & Fundamental Data Types Introduction to Java & Fundamental Data Types LECTURER: ATHENA TOUMBOURI How to Create a New Java Project in Eclipse Eclipse is one of the most popular development environments for Java, as it contains

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

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

Java language. Part 1. Java fundamentals. Yevhen Berkunskyi, NUoS

Java language. Part 1. Java fundamentals. Yevhen Berkunskyi, NUoS Java language Part 1. Java fundamentals Yevhen Berkunskyi, NUoS eugeny.berkunsky@gmail.com http://www.berkut.mk.ua What Java is? Programming language Platform: Hardware Software OS: Windows, Linux, Solaris,

More information

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I BASIC COMPUTATION x public static void main(string [] args) Fundamentals of Computer Science I Outline Using Eclipse Data Types Variables Primitive and Class Data Types Expressions Declaration Assignment

More information

Chapter 3: Operators, Expressions and Type Conversion

Chapter 3: Operators, Expressions and Type Conversion 101 Chapter 3 Operators, Expressions and Type Conversion Chapter 3: Operators, Expressions and Type Conversion Objectives To use basic arithmetic operators. To use increment and decrement operators. To

More information

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

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

UNIT- 3 Introduction to C++

UNIT- 3 Introduction to C++ UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . $, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage

More information

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Dr. Marenglen Biba (C) 2010 Pearson Education, Inc. All rights reserved. Java application A computer program that executes when you use the java command to launch the Java Virtual Machine

More information

Java is an objet-oriented programming language providing features that support

Java is an objet-oriented programming language providing features that support Java Essentials CSCI 136: Spring 2018 Handout 2 February 2 Language Basics Java is an objet-oriented programming language providing features that support Data abstraction Code reuse Modular development

More information

Zheng-Liang Lu Java Programming 45 / 79

Zheng-Liang Lu Java Programming 45 / 79 1 class Lecture2 { 2 3 "Elementray Programming" 4 5 } 6 7 / References 8 [1] Ch. 2 in YDL 9 [2] Ch. 2 and 3 in Sharan 10 [3] Ch. 2 in HS 11 / Zheng-Liang Lu Java Programming 45 / 79 Example Given a radius

More information

Course Outline. Introduction to java

Course Outline. Introduction to java Course Outline 1. Introduction to OO programming 2. Language Basics Syntax and Semantics 3. Algorithms, stepwise refinements. 4. Quiz/Assignment ( 5. Repetitions (for loops) 6. Writing simple classes 7.

More information

JAVA Programming Fundamentals

JAVA Programming Fundamentals Chapter 4 JAVA Programming Fundamentals By: Deepak Bhinde PGT Comp.Sc. JAVA character set Character set is a set of valid characters that a language can recognize. It may be any letter, digit or any symbol

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

The Arithmetic Operators. Unary Operators. Relational Operators. Examples of use of ++ and

The Arithmetic Operators. Unary Operators. Relational Operators. Examples of use of ++ and The Arithmetic Operators The arithmetic operators refer to the standard mathematical operators: addition, subtraction, multiplication, division and modulus. Op. Use Description + x + y adds x and y x y

More information

The Arithmetic Operators

The Arithmetic Operators The Arithmetic Operators The arithmetic operators refer to the standard mathematical operators: addition, subtraction, multiplication, division and modulus. Examples: Op. Use Description + x + y adds x

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

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

Visual C# Instructor s Manual Table of Contents

Visual C# Instructor s Manual Table of Contents Visual C# 2005 2-1 Chapter 2 Using Data At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class Discussion Topics Additional Projects Additional Resources Key Terms

More information

Fundamentals of Programming. By Budditha Hettige

Fundamentals of Programming. By Budditha Hettige Fundamentals of Programming By Budditha Hettige Overview Exercises (Previous Lesson) The JAVA Programming Languages Java Virtual Machine Characteristics What is a class? JAVA Standards JAVA Keywords How

More information

Work relative to other classes

Work relative to other classes Work relative to other classes 1 Hours/week on projects 2 C BOOTCAMP DAY 1 CS3600, Northeastern University Slides adapted from Anandha Gopalan s CS132 course at Univ. of Pittsburgh Overview C: A language

More information

Review of the C Programming Language for Principles of Operating Systems

Review of the C Programming Language for Principles of Operating Systems Review of the C Programming Language for Principles of Operating Systems Prof. James L. Frankel Harvard University Version of 7:26 PM 4-Sep-2018 Copyright 2018, 2016, 2015 James L. Frankel. All rights

More information

Contents. Jairo Pava COMS W4115 June 28, 2013 LEARN: Language Reference Manual

Contents. Jairo Pava COMS W4115 June 28, 2013 LEARN: Language Reference Manual Jairo Pava COMS W4115 June 28, 2013 LEARN: Language Reference Manual Contents 1 Introduction...2 2 Lexical Conventions...2 3 Types...3 4 Syntax...3 5 Expressions...4 6 Declarations...8 7 Statements...9

More information

Language Reference Manual simplicity

Language Reference Manual simplicity Language Reference Manual simplicity Course: COMS S4115 Professor: Dr. Stephen Edwards TA: Graham Gobieski Date: July 20, 2016 Group members Rui Gu rg2970 Adam Hadar anh2130 Zachary Moffitt znm2104 Suzanna

More information

Course information. Petr Hnětynka 2/2 Zk/Z

Course information. Petr Hnětynka  2/2 Zk/Z JAVA Introduction Course information Petr Hnětynka hnetynka@d3s.mff.cuni.cz http://d3s.mff.cuni.cz/~hnetynka/java/ 2/2 Zk/Z exam written test zápočet practical test in the lab max 5 attempts zápočtový

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

Simple Java Reference

Simple Java Reference Simple Java Reference This document provides a reference to all the Java syntax used in the Computational Methods course. 1 Compiling and running... 2 2 The main() method... 3 3 Primitive variable types...

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

Programming with Java

Programming with Java Programming with Java Data Types & Input Statement Lecture 04 First stage Software Engineering Dep. Saman M. Omer 2017-2018 Objectives q By the end of this lecture you should be able to : ü Know rules

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

Object-Oriented Programming. Topic 2: Fundamental Programming Structures in Java

Object-Oriented Programming. Topic 2: Fundamental Programming Structures in Java Electrical and Computer Engineering Object-Oriented Topic 2: Fundamental Structures in Java Maj Joel Young Joel.Young@afit.edu 8-Sep-03 Maj Joel Young Java Identifiers Identifiers Used to name local variables

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

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

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

COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan

COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan COSC 123 Computer Creativity Introduction to Java Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca Key Points 1) Introduce Java, a general-purpose programming language,

More information

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program Objectives Chapter 2: Basic Elements of C++ In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

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

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

History of Java. Java was originally developed by Sun Microsystems star:ng in This language was ini:ally called Oak Renamed Java in 1995

History of Java. Java was originally developed by Sun Microsystems star:ng in This language was ini:ally called Oak Renamed Java in 1995 Java Introduc)on History of Java Java was originally developed by Sun Microsystems star:ng in 1991 James Gosling Patrick Naughton Chris Warth Ed Frank Mike Sheridan This language was ini:ally called Oak

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

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 1 Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers

More information

Getting started with Java

Getting started with Java Getting started with Java Magic Lines public class MagicLines { public static void main(string[] args) { } } Comments Comments are lines in your code that get ignored during execution. Good for leaving

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

JME Language Reference Manual

JME Language Reference Manual JME Language Reference Manual 1 Introduction JME (pronounced jay+me) is a lightweight language that allows programmers to easily perform statistic computations on tabular data as part of data analysis.

More information

Room 3P16 Telephone: extension ~irjohnson/uqc146s1.html

Room 3P16 Telephone: extension ~irjohnson/uqc146s1.html UQC146S1 Introductory Image Processing in C Ian Johnson Room 3P16 Telephone: extension 3167 Email: Ian.Johnson@uwe.ac.uk http://www.csm.uwe.ac.uk/ ~irjohnson/uqc146s1.html Ian Johnson 1 UQC146S1 What is

More information

Certified Core Java Developer VS-1036

Certified Core Java Developer VS-1036 VS-1036 1. LANGUAGE FUNDAMENTALS The Java language's programming paradigm is implementation and improvement of Object Oriented Programming (OOP) concepts. The Java language has its own rules, syntax, structure

More information

Java: framework overview and in-the-small features

Java: framework overview and in-the-small features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Java: framework overview and in-the-small features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer

More information

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York CSc 10200! Introduction to Computing Lecture 2-3 Edgardo Molina Fall 2013 City College of New York 1 C++ for Engineers and Scientists Third Edition Chapter 2 Problem Solving Using C++ 2 Objectives In this

More information

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure C Overview Basic C Program Structure C OVERVIEW BASIC C PROGRAM STRUCTURE Goals The function main( )is found in every C program and is where every C program begins speed execution portability C uses braces

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

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

1 Introduction Java, the beginning Java Virtual Machine A First Program BlueJ Raspberry Pi...

1 Introduction Java, the beginning Java Virtual Machine A First Program BlueJ Raspberry Pi... Contents 1 Introduction 3 1.1 Java, the beginning.......................... 3 1.2 Java Virtual Machine........................ 4 1.3 A First Program........................... 4 1.4 BlueJ.................................

More information

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language 1 History C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC

More information

JAVA OPERATORS GENERAL

JAVA OPERATORS GENERAL JAVA OPERATORS GENERAL Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: Arithmetic Operators Relational Operators Bitwise Operators

More information

The Java language has a wide variety of modifiers, including the following:

The Java language has a wide variety of modifiers, including the following: PART 5 5. Modifier Types The Java language has a wide variety of modifiers, including the following: Java Access Modifiers Non Access Modifiers 5.1 Access Control Modifiers Java provides a number of access

More information

Unit-II Programming and Problem Solving (BE1/4 CSE-2)

Unit-II Programming and Problem Solving (BE1/4 CSE-2) Unit-II Programming and Problem Solving (BE1/4 CSE-2) Problem Solving: Algorithm: It is a part of the plan for the computer program. An algorithm is an effective procedure for solving a problem in a finite

More information

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath UNIT - I Introduction to C Programming Introduction to C C was originally developed in the year 1970s by Dennis Ritchie at Bell Laboratories, Inc. C is a general-purpose programming language. It has been

More information