Introduction to Java & Fundamental Data Types
|
|
- Melinda Stokes
- 5 years ago
- Views:
Transcription
1 Introduction to Java & Fundamental Data Types LECTURER: ATHENA TOUMBOURI
2 How to Create a New Java Project in Eclipse Eclipse is one of the most popular development environments for Java, as it contains everything you need to build a Java project from scratch. Before you can start working on your new project, you'll need to create it first. Creating a new Java project in Eclipse is fairly straightforward.
3 Declare your class and your main method. The main method public static void main(string[] args) is the method that will be executed when the programming is running. This main method will have the same method declaration in every Java program.
4 Write the line of code that will print out "Hello World." Wrong!!
5 Put it all together. Your final Hello World program should look like the following:
6 Run your program!!!!!
7 Let's look at the components of this line: System tells the system to do something. out tells the system that we are going to do some output stuff. println stands for "print line," so we are telling the system to print a line in the output. The parentheses around ("Hello World.") means that the method System.out.println() takes in a parameter, which, in this case, is the String "Hello World." Note that there are some rules in Java that we have to adhere to: You must always add a semicolon at the end of every line. Java is case sensitive, so you must write method names, variable names, and class names in the correct case or you will get an error. Blocks of code specific to a certain method or loop are encased between curly brackets.
8 Data Types 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, the operating system allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals, or characters in these variables. There are two data types available in Java: Primitive Data Types Reference/Object Data Types
9 Primitive data types: Primitive data types are those datatypes which are defined by java language itself. Reference data types: Reference data types are those data types which are provided as class by Java API or by class that you create. String is example of Reference data types provided by java.
10 Data Types Integer Double / Float Char Boolean String Primitive types Reference type
11 Integer Int data type is a 32-bit signed two's complement integer. Minimum value is - 2,147,483,648 (-2^31) Maximum value is 2,147,483,647(inclusive) (2^31-1) Integer is generally used as the default data type for integral values unless there is a concern about memory. The default value is 0 Example: int a = , int b =
12 String Is not a primitive type! It is an Object! The String class represents character strings. All string literals in Java programs, such as "ABC", are implemented as instances of this class. Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example: String str = "ABC"; String str = ; That string is empty because there is nothing inside of the quotation marks, not even a space
13 Double / Float float Float data type is a single-precision 32-bit IEEE 754 floating point Float is mainly used to save memory in large arrays of floating point numbers Default value is 0.0f Float data type is never used for precise values such as currency Example: float f1 = 234.5f double double data type is a double-precision 64-bit IEEE 754 floating point This data type is generally used as the default data type for decimal values, generally the default choice Double data type should never be used for precise values such as currency Default value is 0.0d Example: double d1 = 123.4
14 double number = 4.67; in this example the name of the variable is called number (it can be called anything you want, by the way) and the type is double. We're setting this value to 4.67, although the number does not have to be written as a decimal. double number = 4; This is also valid, because 4 is the same as 4.0 in decimal.
15 Char Char data type is used to store any character Example: char lettera = 'A'
16 char Char c = g ; Before I continue, let me say that 'g' and 'G' are NOT THE SAME THING. These two characters are not equal because computers do not recognize them as the same symbol. More specifically, they have different ASCII values, but that's beyond what we're trying to learn in this lesson. Just remember that capital letters are not the same as lower case letters and vice versa.
17 Boolean Boolean data type represents one bit of information There are only two possible values: true and false This data type is used for simple flags that track true/false conditions Default value is false Example: Boolean one = true;
18 Boolean Boolean x = true; This is how a Boolean variable is created. In Java, the type of variable has to go before the variable's name. In this case the variable's name is x, and it's type is Boolean. We're also setting the variable equal to something, and here we're setting it to true. We could have easily just said: Boolean x;
19 Set Variables to a program There re some rules we have to follow when picking variable names. In general, you can name your variables whatever you want, as long as they follow these simple guidelines: Java variables cannot start with a number or special symbol. Java variables cannot be a keyword already.
20 Operators (+, *, /, -) Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra.
21 Operator + (Addition) Adds values on either side of the operator. Example: A = 10 and B = 20 A + B will give 30
22 Operator - (Subtraction) Subtracts right-hand operand from left-hand operand. Example: A = 10 and B = 20 A - B will give -10
23 Operator * (Multiplication) Multiplies values on either side of the operator. Example: A = 10 and B = 20 A * B will give 200
24 Operator / (Division) Divides left-hand operand by right-hand operand. Example: A = 10 and B = 20 B / A will give 2
25 Also, assume integer variable A holds 10 and variable B holds 20, then
26 The Logical Operators The following table lists the logical operators Assume Boolean variables A holds true and variable B holds false, then:
27 The Relational Operators There are following relational operators supported by Java language. Assume variable A holds 10 and variable B holds 20, then:
28 Assignment Following are the assignment operators supported by Java language
29 Exercise: Write a program to print Hello World Write a program to print your name! Write a program to print the result 5*20
30 Output To output to the command line, we use either System.out.print () or System.out.println() or System.out.printf() Examples using println: System.out.println( One ); System.out.println( Two ); System.out.println( Buckle My Shoe );
31 Output Examples using print & println System.out.print( One ); System.out.print( Two ); System.out.print( Buckle my shoe ); System.out.println();
32 printf int number1, number2, sum; number1=10; number2=30; sum = number1 + number2; System.out.printf( The sum of %d + %d = %d, number1, number2, sum);
33 Change Line System.out.println -> change line System.out.print-> print in the same line
34 Command line Input The Scanner class is used for input from the command line. The Scanner class is in the package java.util so any program using the Scanner class must first include an import statement that is used to help the compiler locate the class. All import statements appear first in a java program before the class definition or any other statement (other than comments).
35 Import java.util.scanner; public class AddTwoNumbers{ public static void main(string[] str){ int x, y; //create a Scanner object to get input //System.in refers to standard input object Scanner input = new Scanner(System.in); //Prompt for and read the first integer //using the Scanner object s nextint method. //The program waits for the user to type in //an integer and press the ENTER key System.out.println( Enter the first integer: ); x = input.nextint(); System.out.println( Enter the next integer: ); y = input.nextint(); sum = x + y; System.out.println ( Sum is %d\n, sum); } //end of main } //end of class AddTwoNumbers
36 Exercise Write a program in Java which asked one number and then return the square of this number. For example: if I give the number 3 as input, the program will return the number 9.
37 -Conditional statements -Nested Decisions and switch statement
38 what is a conditional statement? Alternatively referred to as a conditional expression and conditional processing, a conditional statement is a set of rules performed if a certain condition is met. It is sometimes referred to as an If-Then statement, because IF a condition is met, THEN an action is performed
39 Conditional statements in physical language
40 Conditional operators The Equality and Relational Operators The equality and relational operators determine if one operand is greater than, less than, equal to, or not equal to another operand. The majority of these operators will probably look familiar to you as well. Keep in mind that you must use "==", not "=", when testing if two primitive values are equal. == equal to!= not equal to > greater than >= greater than or equal to < less than <= less than or equal to
41 AND OPERATOR- && Called Logical AND operator. If both the operands are non-zero, then the condition becomes true.
42 OR OPERATOR- Called Logical OR Operator. If any of the two operands are non-zero, then the condition becomes true.
43 NOT OPERATOR-! Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.
44 Conditional statement in java A conditional statement in Java is one which checks for a condition and the course of program flow that it takes would depend on the outcome of the condition. If - else - is the most common conditional construct used in Java.
45 if statement: The if statement is the most basic of all the control flow statements. The if statement tells our program to execute a certain section of code only if a particular test evaluates to true.
46 Nested if statement: An if statement inside another the statement. If the outer if condition is true then the section of code under outer if condition would execute and it goes to the inner if condition. If inner if condition is true then the section of code under inner if condition would execute.
47 if-else statement: If a condition is true then the section of code under if would execute else the section of code under else would execute.
48 if-else-if statement:
49
50 Switch Case: The switch statement in Java is a multi branch statement. We use this in Java when we have multiple options to select. It executes particular option based on the value of an expression. Switch works with the byte, short, char, and int primitive data types. It also works with enumerated types, the String class, and a few special classes that wrap certain primitive types such as Character, Byte, Short, and Integer.
51 Example switch-case with break
52 Example switch-case without break
53 Create programs using if and if else statements Write a program in java which reads two numbers. If the first number is bigger than the second then the program will calculate and print the difference. Write a program in java which read the grade of a student and print: 8: GOOD 9: VERY GOOD 10: EXCELLENT o(solve the second exercise using if and after solve it using switch case)
54 While loop
55 What are the loops? In computer programming, a loop is a sequence of instruction s that is continually repeated until a certain condition is reached. Typically, a certain process is done, such as getting an item of data and changing it, and then some condition is checked such as whether a counter has reached a prescribed number.
56 Why use loops? Loops are used to repeat one statement or set statements more than one time. Most real programs contain some construct that loops within the program, performing repetitive actions on a stream of data or a region of memory.
57 While Loop In most computer programming languages, a while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement.
58 Java while loop Java while loop is used to execute statement(s) until a condition is true. In this tutorial, we will learn to use while loop with examples. First of all, let's discuss while loop syntax: while (condition(s)) { // Body of loop } If the condition(s) holds true then the body of the loop is executed, after execution of the loop body condition is tested again and if the condition is still true then the body of the loop is executed again, and the process repeats until the condition(s) becomes false. The condition evaluates to true or false and if it is a constant, for example, while (c) { }, where c is a constant, then any non zero value of c is considered to be true, and zero is considered false.
59 You can test multiple conditions such as while (a > b && c!= 0) { // Loop body } Loop body is executed till value of variable a is greater than value of variable b and variable c isn't equal to zero. A body of a loop can contain more than one statement. For multiple statements, you need to place them in a block using {}, and if the body of a loop contains only one statement, you can optionally use {}. It is always recommended to use braces to make your program easy to read and understand.
60 Simple while-loop example
61
62 Java while loop break program We can write above program using a break statement. We test a user input and if it is zero then we use "break" to exit or come out of the loop.
63 Java while loop break continue program
64 Infinite while loop This loop would never end, its an infinite while loop. This is because condition is i >1 which would always be true as we are incrementing the value of i inside while loop
65 Example of infinite while loop
66 Create programs using while statement Write a program in java which reads numbers until the user give the number -1. Write a program in java that asked a user to give numbers and prints hello world until the user give odd number. Write a program in java that checks if the grade of test is between you must to read 70 grades.
67 For Loop
68 What is for loop In computer science a for-loop (or simply for loop) is a programming language control statement for specifying iteration, which allows code to be executed repeatedly.
69 Java For Loop The Java for loop is used to iterate a part of the program several times. If the number of iteration is fixed, it is recommended to use for loop. There are three types of for loops in java. Simple For Loop For-each or Enhanced For Loop Labeled For Loop
70 Java Simple For Loop We can initialize the variable, check condition and increment/decrement value. It consists of four parts: Initialization: It is the initial condition which is executed once when the loop starts. Here, we can initialize the variable, or we can use an already initialized variable. It is an optional condition. Condition: It is the second condition which is executed each time to test the condition of the loop. It continues execution until the condition is false. It must return boolean value either true or false. It is an optional condition. Statement: The statement of the loop is executed each time until the second condition is false. Increment/Decrement: It increments or decrements the variable value. It is an optional condition.
71 Flowchart:
72 Java example //Java Program to demonstrate the example of for loop //which prints table of 1 public class ForExample { public static void main(string[] args) { //Code of Java for loop for(int i=1; i<=10; i++){ System.out.println(i); } } }
73 what is the output of previous example??
74 Java for-each Loop The for-each loop is used to traverse array or collection in java. It is easier to use than simple for loop because we don't need to increment value and use subscript notation. It works on elements basis not index. It returns element one by one in the defined variable.
75
76 what is the output of previous example??
77 Java Labeled For Loop We can have a name of each Java for loop. To do so, we use label before the for loop. It is useful if we have nested for loop so that we can break/continue specific for loop. Usually, break and continue keywords breaks/continues the innermost for loop only.
78
79 what is the output of previous example??
80 Java Infinitive For Loop If you use two semicolons ;; in the for loop, it will be infinitive for loop.
81 Infinite for loop
82
83 Do while loop
84 do while loop In most computer programming languages, a do while loop is a control flow statement that executes a block of code at least once, and then repeatedly executes the block, or not, depending on a given boolean condition at the end of the block.
85 A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time. Notice that the Boolean expression appears at the end of the loop, so the statements in the loop execute once before the Boolean is tested. If the Boolean expression is true, the control jumps back up to do statement, and the statements in the loop execute again. This process repeats until the Boolean expression is false Following is the syntax of a do...while loop
86 Example do while
87 What is the output?
88 Java Infinitive do-while Loop
89
90
91
92 Nested Loops and Good Programming Style
93 Nested Loops java The placing of one loop inside the body of another loop is called nesting. When you "nest" two loops, the outer loop takes control of the number of complete repetitions of the inner loop. While all types of loops may be nested, the most commonly nested loops are for loops.
94 When working with nested loops, the outer loop changes only after the inner loop is completely finished
95 Example 1: The far-right number, however, is not the only number that is moving. All of the other numbers are moving also, but at a much slower pace. For every 10 numbers that move in the column on the right, the adjacent column is incremented by one. The two nested loops shown below may be used to imitate the movement of the two far-right numbers of a web counter or an odometer:
96 Example 2: Program to create a pattern
97 Example 3: Java Nested for Loop
98 Common Errors
99 Example: nested loop: A loop placed inside another loop. for (int i = 1; i <= 5; i++) { for (int j = 1; j <= 10; j++) { System.out.print("*"); } System.out.println(); // to end the line } Output: ********** ********** ********** ********** ********** The outer loop repeats 5 times; the inner one 10 times. "sets and reps" exercise analogy
100 Exercise 1: What is the output of the following nested for loops? for (int i = 1; i <= 5; i++) { for (int j = 1; j <= i; j++) { System.out.print("*"); } System.out.println(); }
101 Exercise 2: What is the output of the following nested for loops? for (int i = 1; i <= 5; i++) { for (int j = 1; j <= i; j++) { System.out.print(i); } System.out.println(); }
102 Guidelines for good programming 1 Formatting Indentation All indents are four spaces. All indenting is done with spaces, not tabs. Matching braces always line up vertically in the same column as their construct. All if, while and for statements must use braces even if they control just one statement.
103 1.2 - Spacing All method names should be immediately followed by a left parenthesis. All array dereferences should be immediately followed by a left square bracket. Binary operators should have a space on either side. Unary operators should be immediately preceded or followed by their operand. Commas and semicolons are always followed by whitespace. All casts should be written with no spaces. The keywords if, while, for, switch, and catch must be followed by a space.
104 1.3 - Class Member Ordering class Order { // fields // constructors // methods } Maximum Line Length Avoid making lines longer than 120 characters. 1.5 Parentheses Parentheses should be used in expressions not only to specify order of precedence, but also to help simplify the expression. When in doubt, parenthesize
105 2 - Identifiers All identifiers use letters ('A' through 'Z' and 'a' through 'z') and numbers ('0' through '9') only. No underscores, dollar signs or non-ascii characters Classes and Interfaces All class and interface identifiers will use mixed case. The first letter of each word in the name will be uppercase, including the first letter of the name. All other letters will be in lowercase, except in the case of an acronym, which will be all upper case Packages Package names will use lower case characters only. Try to keep the length under eight (8) characters. Multi-word package names should be avoided All Other Identifiers All other identifiers, including (but not limited to) fields, local variables, methods and parameters, will use the following naming convention. This includes identifiers for constants. The first letter of each word in the name will be uppercase, except for the first letter of the name. All other letters will be in lowercase, except in the case of an embedded acronym, which will be all uppercase. Leading acronyms are all lower case. Hungarian notation and scope identification are not allowed. Test code is permitted to use underscores in identifiers for methods and fields
106 3 - Coding Constructs to Avoid Never use do..while Never use return in the middle of a method Never use continue. Never use break other than in a switch statement Do Not Compound Increment Or Decrement Operators Use a separate line for an increment or decrement. Never use pre-increment or predecrement Initialization Declare variables as close as possible to where they are used Access All fields must be private, except for some constants.
107 Use of Comments In programming, comments are portion of the program intended for you and your fellow programmers to understand the code. They are completely ignored by Java compilers. In Java programming language, there are two types of comments:
108 Traditional comment /*... */ This is a multiline comment that can span over multiple lines. The Java compiler ignores everything from /*... */. For example:
109 End of Line Comment // The compiler ignores everything from // to the end of the line. For example:
110 Use Comments the Right Way Comments shouldn't be the substitute for a way to explain poorly written code in English. Write well structured and readable code, and then use comments. In most cases, use comments to explain 'why' rather than 'how' and you are good to go.
111 Parts of Java Program Java programs are made up of different parts. We ll begin by looking at a simple example: Comments Class Definition Main Method
112 The Class Definition FirstProgram is the name of the Java class. Note that the file must be named to class name with.java extension. It means that this program must be saved as FirstProgram.java The second line of the program consists of the left brace, which is matched with the second right brace (the very last brace). These braces together mark the beginning and end of (the body of) the class FirstProgram. Later we ll discuss class in details, for now it is enough to know that every application begins with a class definition.
113 The main Method In Java, every application must contain a main method whose signature is: The JVM starts running any program by executing this method first. Finally, the line: prints the characters between quotes to the console.
114 Arrays
115 What are the arrays? An array is a series of data elements that, in most programming languages, is stored in consecutive memory locations. The datum held in an array is called an element, and each element occupies a position in the array known as an index N-1
116 Why use Arrays in a program? Array reduce the number of variable names in the program Sales[K] versus Sales1, Sales2, SalesN,. Arrays increase the flexibility of the program. Arrays reduce the number of If-Then statements needed in selection processing. if Sales[K] Then rather than Sales1 Then Sales2 Then Sales3 Then Arrays improve efficiency by allowing data to be read into the program once but processed as many time as necessary.
117 Arrays in Java: An array is a group of like-typed variables that are referred to by a common name. Following are some important point about Java arrays: I. In Java all arrays are dynamically allocated.(discussed below) II. III. Since arrays are objects in Java, we can find their length using member length. A Java array variable can also be declared like other variables with [] after the data type. IV. The variables in the array are ordered and each have an index beginning from 0. V. Java array can be also be used as a static field, a local variable or a method parameter. VI. The size of an array must be specified by an int value and not long or short.
118 Declaring Array Variables: To use an array in a program, you must declare a variable to reference the array, and you must specify the type of array the variable can reference. The general form of a one-dimensional array declaration is: type var-name[]; or Example type[] var-name; //preferred way The following code snippets are examples of this syntax
119 Creating Arrays You can create an array by using the new operator with the following syntax: The above statement does two things: 1. It creates an array using new datatype[arraysize]. 2. It assigns the reference of the newly created array to the variable arrayrefvar.
120 Declaring an array variable, creating an array, and assigning the reference of the array to the variable can be combined in one statement, as shown below: Alternatively you can create arrays as follows : The array elements are accessed through the index. Array indices are 0-based; that is, they start from 0 to arrayrefvar.length-1
121 Example Following statement declares an array variable, mylist, creates an array of 10 elements of double type and assigns its reference to mylist: Following picture represents array mylist. Here, mylist holds ten double values and the indices are from 0 to 9.
122 Processing Arrays When processing array elements, we often use either for loop because all of the elements in an array are of the same type and the size of the array is known. Print all the array elements: public class TestArray { public static void main(string[] args) { } } double[] mylist = {1.9, 2.9, 3.4, 3.5}; for (int i = 0; i < mylist.length; i++) { System.out.println(myList[i] + " "); }
123 Summing all elements public class TestArray { public static void main(string[] args) { double[] mylist = {1.9, 2.9, 3.4, 3.5}; double total = 0; for (int i = 0; i < mylist.length; i++) { total += mylist[i]; } } } System.out.println("Total is " + total);
124 Finding the largest element public class TestArray { public static void main(string[] args) { double[] mylist = {1.9, 2.9, 3.4, 3.5}; double max = mylist[0]; for (int i = 1; i < mylist.length; i++) { if (mylist[i] > max) max = mylist[i]; } System.out.println("Max is " + max); } }
125 The foreach Loops Enables you to traverse the complete array sequentially without using an index variable. Example:
126 The previous program will produce the following result: Prints all the elements in the Array!!!
127 Passing Arrays to Methods Just as you can pass primitive type values to methods, you can also pass arrays to methods. For example, the following method displays the elements in an int array. Example:
128 Returning an Array from a Method A method may also return an array. For example, the following method returns an array that is the reversal of another array:
129 Exercises: Write a Java program to calculate the average value of array elements. (Average = sum / count) Write a Java program to test if an integer array contains the number 5. Write a Java program to find the maximum and minimum value of an array.
130 Parallel arrays and multidimensional arrays
131 Parallel arrays In computing, a group of parallel arrays (also known as structure of arrays or SoA) is a form of implicit data structure that uses multiple arrays to represent a singular array of records. Simply, Parallel arrays are several arrays with the same number of elements that work in tandem to organize data.
132 Why we use them? It keeps a separate, homogeneous data array for each field of the record, each having the same number of elements. The advantage of parallel arrays in Java is as an measure to reduce object allocation. For a large enough collection of objects, 3 arrays will occupy less space AND use fewer objects than a single array of instances of some custom class.
133 Example: The first array is the dog's name, the second array is the dog's score in round 1 of the competition, and the third array is the dog's score in round 2 of the competition. The arrays are parallel, in that the dog in the first element of the first array has the scores represented in the first elements of the second and third arrays
134 //Printing the dog competition information: for(int i = 0; i < dogname.length; i++) { System.out.println(dogname[i]); System.out.println(round1[i]); System.out.println(round2[i]); }
135 Program with parallel arrays
136 ..Output?
137 Exercise: You have the following Arrays:
138 Representing the properties of many different students To represent the student ID of a number of students, we can use an array of int To represent the name of a number of students, we can use an separate array of String To represent the major of a number of students, we can use an separate array of String To represent the level of a number of students, we can use an separate array of int
139 information on 3 students
140 How can I print the major of John Doe, if I don t know that the John Doe is first in the Array?
141 Multidimensional arrays A multidimensional array in Java is really an array within an array (and as more dimensions are added, the hall of mirrors continues).
142 So, It's also possible to create an array of arrays known as multidimensional array. For example:
143 ***Remember, Java uses zero-based indexing, that is, indexing of arrays in Java starts with 0 and not 1.
144 TWO FOR LOOP Example: Print all elements of 2d array Using Loop
145 EXERCISES: 1) Write a Java program to find and print all EVEN numbers in 2d Array 5x6.
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 information12/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 informationProgramming 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 informationAssoc. 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 informationExpressions 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 informationCourse 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 informationExpressions 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 informationPace 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 informationSelec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal
Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program
More informationMobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02
Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02 Hello, in this lecture we will learn about some fundamentals concepts of java.
More informationEntry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process
Entry Point of Execution: the main Method Elementary Programming EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG For now, all your programming exercises will
More informationAP Computer Science A
AP Computer Science A 1st Quarter Notes Table of Contents - section links Click on the date or topic below to jump to that section Date : 9/8/2017 Aim : Java Basics Objects and Classes Data types: Primitive
More informationWentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics
WIT COMP1000 Java Basics Java Origins Java was developed by James Gosling at Sun Microsystems in the early 1990s It was derived largely from the C++ programming language with several enhancements Java
More information2.5 Another Application: Adding Integers
2.5 Another Application: Adding Integers 47 Lines 9 10 represent only one statement. Java allows large statements to be split over many lines. We indent line 10 to indicate that it s a continuation of
More informationObjectives. 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 informationChapter 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 informationIntroduction to Java Applications; Input/Output and Operators
www.thestudycampus.com Introduction to Java Applications; Input/Output and Operators 2.1 Introduction 2.2 Your First Program in Java: Printing a Line of Text 2.3 Modifying Your First Java Program 2.4 Displaying
More informationMr. Monroe s Guide to Mastering Java Syntax
Mr. Monroe s Guide to Mastering Java Syntax Getting Started with Java 1. Download and install the official JDK (Java Development Kit). 2. Download an IDE (Integrated Development Environment), like BlueJ.
More informationChapter 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 informationFundamental of Programming (C)
Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 3 Constants, Variables, Data Types, And Operations Department of Computer Engineering
More informationObject-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 informationCSc 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 informationIntroduction 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 informationUNIT- 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 informationObjectives. In this chapter, you will:
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 arithmetic expressions Learn about
More informationCOSC 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 informationUniversità degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M
Università degli Studi di Bologna Facoltà di Ingegneria Principles, Models, and Applications for Distributed Systems M tutor Isam M. Al Jawarneh, PhD student isam.aljawarneh3@unibo.it Mobile Middleware
More informationProgramming for Engineers Introduction to C
Programming for Engineers Introduction to C ICEN 200 Spring 2018 Prof. Dola Saha 1 Simple Program 2 Comments // Fig. 2.1: fig02_01.c // A first program in C begin with //, indicating that these two lines
More informationTester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time
Tester vs. Controller Elementary Programming EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG For effective illustrations, code examples will mostly be written in the form of a tester
More informationElementary Programming
Elementary Programming EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG Learning Outcomes Learn ingredients of elementary programming: data types [numbers, characters, strings] literal
More informationJava-Array. This tutorial introduces how to declare array variables, create arrays, and process arrays using indexed variables.
-Array Java provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful
More informationChapter 3. Selections
Chapter 3 Selections 1 Outline 1. Flow of Control 2. Conditional Statements 3. The if Statement 4. The if-else Statement 5. The Conditional operator 6. The Switch Statement 7. Useful Hints 2 1. Flow of
More information4 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 informationCOMP 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 informationBasics 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 informationLecture Set 2: Starting Java
Lecture Set 2: Starting Java 1. Java Concepts 2. Java Programming Basics 3. User output 4. Variables and types 5. Expressions 6. User input 7. Uninitialized Variables 0 This Course: Intro to Procedural
More informationGetting 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 informationCS5000: 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 informationSelec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal
Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program
More informationJava+- 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 informationRepe$$on CSC 121 Fall 2015 Howard Rosenthal
Repe$$on CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Learn the following three repetition methods, their similarities and differences, and how to avoid common errors when using them: while do-while
More informationObject 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 informationLecture Set 2: Starting Java
Lecture Set 2: Starting Java 1. Java Concepts 2. Java Programming Basics 3. User output 4. Variables and types 5. Expressions 6. User input 7. Uninitialized Variables 0 This Course: Intro to Procedural
More information2.8. Decision Making: Equality and Relational Operators
Page 1 of 6 [Page 56] 2.8. Decision Making: Equality and Relational Operators A condition is an expression that can be either true or false. This section introduces a simple version of Java's if statement
More informationChapter 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 informationExpressions 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 informationJava 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 informationCSE 142 Su 04 Computer Programming 1 - Java. Objects
Objects Objects have state and behavior. State is maintained in instance variables which live as long as the object does. Behavior is implemented in methods, which can be called by other objects to request
More informationIntroduction. C provides two styles of flow control:
Introduction C provides two styles of flow control: Branching Looping Branching is deciding what actions to take and looping is deciding how many times to take a certain action. Branching constructs: if
More informationEntry Point of Execution: the main Method. Elementary Programming. Compile Time vs. Run Time. Learning Outcomes
Entry Point of Execution: the main Method Elementary Programming EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG For now, all your programming exercises will be defined within the
More informationContents. 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 informationArray. Lecture 12. Based on Slides of Dr. Norazah Yusof
Array Lecture 12 Based on Slides of Dr. Norazah Yusof 1 Introducing Arrays Array is a data structure that represents a collection of the same types of data. In Java, array is an object that can store a
More informationLecture 05 I/O statements Printf, Scanf Simple statements, Compound statements
Programming, Data Structures and Algorithms Prof. Shankar Balachandran Department of Computer Science and Engineering Indian Institute of Technology, Madras Lecture 05 I/O statements Printf, Scanf Simple
More informationLecture Notes. System.out.println( Circle radius: + radius + area: + area); radius radius area area value
Lecture Notes 1. Comments a. /* */ b. // 2. Program Structures a. public class ComputeArea { public static void main(string[ ] args) { // input radius // compute area algorithm // output area Actions to
More informationSection 2.2 Your First Program in Java: Printing a Line of Text
Chapter 2 Introduction to Java Applications Section 2.2 Your First Program in Java: Printing a Line of Text 2.2 Q1: End-of-line comments that should be ignored by the compiler are denoted using a. Two
More informationInterpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled
Interpreted vs Compiled Python 1 Java Interpreted Easy to run and test Quicker prototyping Program runs slower Compiled Execution time faster Virtual Machine compiled code portable Java Compile > javac
More informationIntroduction to Java Applications
2 Introduction to Java Applications OBJECTIVES In this chapter you will learn: To write simple Java applications. To use input and output statements. Java s primitive types. Basic memory concepts. To use
More informationRepetition CSC 121 Fall 2014 Howard Rosenthal
Repetition CSC 121 Fall 2014 Howard Rosenthal Lesson Goals Learn the following three repetition methods, their similarities and differences, and how to avoid common errors when using them: while do-while
More informationProgramming Language Basics
Programming Language Basics Lecture Outline & Notes Overview 1. History & Background 2. Basic Program structure a. How an operating system runs a program i. Machine code ii. OS- specific commands to setup
More informationFull file at
Java Programming, Fifth Edition 2-1 Chapter 2 Using Data within a Program At a Glance Instructor s Manual Table of Contents Overview Objectives Teaching Tips Quick Quizzes Class Discussion Topics Additional
More informationRepe$$on CSC 121 Spring 2017 Howard Rosenthal
Repe$$on CSC 121 Spring 2017 Howard Rosenthal Lesson Goals Learn the following three repetition structures in Java, their syntax, their similarities and differences, and how to avoid common errors when
More informationLecture 3 Tao Wang 1
Lecture 3 Tao Wang 1 Objectives In this chapter, you will learn about: Arithmetic operations Variables and declaration statements Program input using the cin object Common programming errors C++ for Engineers
More informationChapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics
Java Programming, Sixth Edition 2-1 Chapter 2 Using Data At a Glance Instructor s Manual Table of Contents Overview Objectives Teaching Tips Quick Quizzes Class Discussion Topics Additional Projects Additional
More informationVisual 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 information13 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 informationJava 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 informationControl Statements: Part 1
4 Let s all move one place on. Lewis Carroll Control Statements: Part 1 The wheel is come full circle. William Shakespeare How many apples fell on Newton s head before he took the hint! Robert Frost All
More informationcis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1
topics: introduction to java, part 1 cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 cis20.1-fall2007-sklar-leci.2 1 Java. Java is an object-oriented language: it is
More informationChapter 2 Basic Elements of C++
C++ Programming: From Problem Analysis to Program Design, Fifth Edition 2-1 Chapter 2 Basic Elements of C++ At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class Discussion
More information\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 informationThe C++ Language. Arizona State University 1
The C++ Language CSE100 Principles of Programming with C++ (based off Chapter 2 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University
More informationData and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence
Data and Variables Data Types Expressions Operators Precedence String Concatenation Variables Declaration Assignment Shorthand operators Review class All code in a java file is written in a class public
More informationCOMP 202 Java in one week
CONTENTS: Basics of Programming Variables and Assignment Data Types: int, float, (string) Example: Implementing a calculator COMP 202 Java in one week The Java Programming Language A programming language
More informationJava 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 informationProgram 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 informationCONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2
CONTENTS: Compilation Data and Expressions COMP 202 More on Chapter 2 Programming Language Levels There are many programming language levels: machine language assembly language high-level language Java,
More informationFlow Control. CSC215 Lecture
Flow Control CSC215 Lecture Outline Blocks and compound statements Conditional statements if - statement if-else - statement switch - statement? : opertator Nested conditional statements Repetitive statements
More informationValues and Variables 1 / 30
Values and Variables 1 / 30 Values 2 / 30 Computing Computing is any purposeful activity that marries the representation of some dynamic domain with the representation of some dynamic machine that provides
More informationboolean, char, class, const, double, else, final, float, for, if, import, int, long, new, public, return, static, throws, void, while
CSCI 150 Fall 2007 Java Syntax The following notes are meant to be a quick cheat sheet for Java. It is not meant to be a means on its own to learn Java or this course. For that you should look at your
More informationChapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.
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 informationComputational Expression
Computational Expression Variables, Primitive Data Types, Expressions Janyl Jumadinova 28-30 January, 2019 Janyl Jumadinova Computational Expression 28-30 January, 2019 1 / 17 Variables Variable is a name
More informationARG! Language Reference Manual
ARG! Language Reference Manual Ryan Eagan, Mike Goldin, River Keefer, Shivangi Saxena 1. Introduction ARG is a language to be used to make programming a less frustrating experience. It is similar to C
More informationCS111: PROGRAMMING LANGUAGE II
1 CS111: PROGRAMMING LANGUAGE II Computer Science Department Lecture 1: Introduction Lecture Contents 2 Course info Why programming?? Why Java?? Write once, run anywhere!! Java basics Input/output Variables
More informationWhat did we talk about last time? Examples switch statements
Week 4 - Friday What did we talk about last time? Examples switch statements History of computers Hardware Software development Basic Java syntax Output with System.out.print() Mechanical Calculation
More informationSlide 1 CS 170 Java Programming 1 The Switch Duration: 00:00:46 Advance mode: Auto
CS 170 Java Programming 1 The Switch Slide 1 CS 170 Java Programming 1 The Switch Duration: 00:00:46 Menu-Style Code With ladder-style if-else else-if, you might sometimes find yourself writing menu-style
More informationBuilding Java Programs Chapter 2
Building Java Programs Chapter 2 Primitive Data and Definite Loops Copyright (c) Pearson 2013. All rights reserved. Data types type: A category or set of data values. Constrains the operations that can
More informationUniversità degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M
Università degli Studi di Bologna Facoltà di Ingegneria Principles, Models, and Applications for Distributed Systems M Control Structures Intro. Sequential execution Statements are normally executed one
More informationIntroduction 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 informationCSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI
CSCI 2010 Principles of Computer Science Data and Expressions 08/09/2013 CSCI 2010 1 Data Types, Variables and Expressions in Java We look at the primitive data types, strings and expressions that are
More informationChapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. A Guide to this Instructor s Manual:
Java Programming, Eighth Edition 2-1 Chapter 2 Using Data A Guide to this Instructor s Manual: We have designed this Instructor s Manual to supplement and enhance your teaching experience through classroom
More informationOct Decision Structures cont d
Oct. 29 - Decision Structures cont d Programming Style and the if Statement Even though an if statement usually spans more than one line, it is really one statement. For instance, the following if statements
More informationFirst Java Program - Output to the Screen
First Java Program - Output to the Screen These notes are written assuming that the reader has never programmed in Java, but has programmed in another language in the past. In any language, one of the
More information5/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 informationFundamentals of Programming
Fundamentals of Programming Lecture 3 - Constants, Variables, Data Types, And Operations Lecturer : Ebrahim Jahandar Borrowed from lecturer notes by Omid Jafarinezhad Outline C Program Data types Variables
More informationCS 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 informationExample: Monte Carlo Simulation 1
Example: Monte Carlo Simulation 1 Write a program which conducts a Monte Carlo simulation to estimate π. 1 See https://en.wikipedia.org/wiki/monte_carlo_method. Zheng-Liang Lu Java Programming 133 / 149
More informationImportant Java terminology
1 Important Java terminology The information we manage in a Java program is either represented as primitive data or as objects. Primitive data פרימיטיביים) (נתונים include common, fundamental values as
More informationJump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.
Jump Statements The keyword break and continue are often used in repetition structures to provide additional controls. break: the loop is terminated right after a break statement is executed. continue:
More informationLecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18
Assignment Lecture 9 Logical Operations Formatted Print Printf Increment and decrement Read through 3.9, 3.10 Read 4.1. 4.2, 4.3 Go through checkpoint exercise 4.1 Logical Operations - Motivation Logical
More informationChapter 2: Programming Concepts
Chapter 2: Programming Concepts Objectives Students should Know the steps required to create programs using a programming language and related terminology. Be familiar with the basic structure of a Java
More information