🎧 New: AI-Generated Podcasts Turn your study notes into engaging audio conversations. Learn more

DSA-Module-1-Intro-to-Java-Programming.pdf

Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Full Transcript

Unit 1: Introduction to JAVA Programming Unit 1 Introduction to JAVA Programming Introduction Java is a general-purpose programming language that is class- based, object -oriented, and designed to have as few implementation dep...

Unit 1: Introduction to JAVA Programming Unit 1 Introduction to JAVA Programming Introduction Java is a general-purpose programming language that is class- based, object -oriented, and designed to have as few implementation dependencies as possible. It is intended to let application developers write once, run anywhere (WORA), meaning that compiled Java code can run on all platforms that support Java without the need for recompilation. Java applications are typically compiled to bytecode that can run on any Java virtual machine (JVM) regardless of the underlying computer architecture. The syntax of Java is similar to C and C++, but it has fewer low- level facilities than either of them. As of 2019, Java was one of the most popular programming languages in use according to GitHub, particularly for client -server web applications, with a reported 9 million developers. Unit Learning Outcomes At the end of the unit, you will be able to: a. To learn how to read and write files in Java. Topic 1: JAVA Programming Time Allotment: 6 Hours Presentation of Contents JAVA BACKGROUND A little Bit of History Java was created in 1991 by James Gosling et al. of Sun Microsystems. Initially called Oak, in honor of the tree outside Gosling's window, its name was changed to Java because there was already a language called Oak. The original motivation for Java was the need for platform independent language that could be embedded in various consumer electronic products like toasters and refrigerators. One 1 Unit 1: Introduction to JAVA Programming of the first projects developed using Java was a personal hand- held remote control named Star 7. At about the same time, the World Wide Web and the Internet were gaining popularity. Gosling et. al. realized that Java could be used for Internet programming. About Java programs, it is very important to keep in mind the following points. Case Sensitivity - Java is case sensitive which means identifier Hello and hello would have different meaning in Java. Class Names - For all class names the first letter should be in Upper Case. If several words are used to form a name of the class each inner words first letter should be in Upper Case. Example class MyFirst JavaClass Method Names - All method names should start with a Lower Case letter. If several words are used to form the name of the method, then each inner word's first letter should be in Upper Case. Example public void myMet hodName() Program File Name - Name of the program file should exactly match the class name. When saving the file you should save it using the class name (Remember java is case sensitive) and append '.java' to the end of the name. (if the file name and the class name do not match your program will not compile). Example : Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved as 'MyFirst JavaProgram.java' public static void main(String args[]) - java program processing starts from the main() method which is a mandatory part of every java program.. Dissecting my first Java program Now, we’ll try to dissect your first Java program: public class Hello { public static void main (String [] args) { 2 Unit 1: Introduction to JAVA Programming // prints the string “Hello world!” on screen System.out.println (“Hello world”); } } The first line of the code, public class Hello indicates the name of the class which is Hello. In Java, all code should be placed inside a class declaration. We do this by using the class keyword. In addition, the class uses an access specifier public, which indicates that our class in accessible to other classes from other packages (packages are a collection of classes). We will be covering packages and access specifiers later. The next line which contains a curly brace { indicates the start of a block. In this code, we placed the curly brace at the next line after the class declaration; however, we can also place this next to the first line of our code. So we could actually write our code as: public classes Hello { Or public classes Hello { The next three lines indicate a Java comment. A comment is something used to document a part of a code. It is not a part of the program itself, but used for documentation purposes. It is good programming practice to add comments to your code. A comment is indicated by the delimiters “”. Anything within these delimiters is ignored by the Java compiler, and are treated as comments. The next line, public static void main (String [] args) { or can also be written as, public static void main (String [] args) { 3 Unit 1: Introduction to JAVA Programming Indicates the name of one method in Hello which is the main method. The main method is the starting point of a Java program. All programs except Applets written in Java start with the main method. Make sure to follow the exact signature. The next line is also a Java comment, // prints the string “Hello world” on screen Now, we learn two ways of creating comments. The first one is by placing the comment inside , and the other one is by writing // at the start of the comment. The next line, System.out.println (“Hello world!”); Prints the text “Hello world!” on the screen. The command System.out.println(), prints the text enclosed by the quotation on the screen. The last two lines which contain the two curly braces are used to close the main method and class respectively. Coding Guidelines: 1. Your Java program should always end with the.java extension. 2. Filenames should match the name of your public class. So, for example, if the name of your public is Hello, you should save it in a file called Hello.java. 3. You should write comments in your code explaining what a certain class does, or what a certain method do. JAVA STATEMENTS AND BLOCKS A statement is one or more lines of code terminated by a semicolon. An example of a single statement is, System.out.println(“Hello world”); A block is one or more statements bounded by an opening and closing curly braces that groups the statements as one unit. Block statements can be nested indefinitely. Any amount of white space is allowed. An example of a block is, 4 Unit 1: Introduction to JAVA Programming public static void main (String [] args ) { System.out.println (“Hello”); System.out.println (“world”); } Coding Guidelines: 1. In creating blocks, you can place the opening curly brace in line with the statement, like for example, public static void main (String [] args ) { or you can place the curly brace on the next line, like, public static void main (String [] args ) { 2. You should indent the next statement after the start of a block, for example, public static void main (String [] args ) { System.out.println (“Hello”); System.out.println (“world”); } JAVA IDENTIFIERS All java components require names. Names used for classes, variables and methods are called identifiers. In java there are several points to remember about identifiers. They are as follows: All identifiers should begin with a letter (A to Z or a to z ), currency character ($) or an underscore ( _ ). After the first character identifiers can have any combination of characters. A key word cannot be used as an identifier. Most importantly identifiers are case sensitive. Examples of legal identifiers: age, $salary, _value, __1_value Examples of illegal identifiers : 123abc, -salary 5 Unit 1: Introduction to JAVA Programming JAVA KEYWORDS Keywords are predefined identifiers reserved by Java for a specific purpose. You cannot use keywords as names for your variables, classes, methods…etc. here is a list of the Java keywords. abstract Double Int super boolean Else Interface switch break extends Long synchronize d byte False native this byvalue Final New threadsafe case finally Null throw catch Float package transient char For Private true class goto protected try const If public void continue implement return while s default import short do instanceof static Primitive data types The Java programming language defines eight primitive data types. The following are, boolean (for logical), char (for textual), byte, short, int, long (integral), double and float (floating point). 1. Logical - boolean A boolean data type represents two states: true and false. An example is, boolean result = true; The example shown above, declares a variable named result as boolean type and assigns it a value of true. 2. Textual – char A character data type (char), represents a single Unicode character. It must have its literal enclosed in single quotes(’ ’). For example, ‘a’ //The letter a ‘\t’ //A tab To represent special characters like ' (single quotes) or " (double quotes), use the escape character \. For example, 6 Unit 1: Introduction to JAVA Programming '\'' //for single quotes '\"' //for double quotes Although, String is not a primitive data type (it is a Class). A String represents a data type that contains multiple characters. It has it’s literal enclosed in double quotes(“”). For example, String message=“Hello world!” 3. Integral – byte, short, int & long Integer Name or Type Range 8 bits Byte -27 to 27-1 16 bits Short -215 to 215-1 32 bits Int -231 to 231-1 64 bits Long -263 to 263-1 4. Floating Point – float and double Floating point types has double as default data type. Floating-point data types have the following ranges: Float Length Name or Type Range 32 bits Float -231 to 231-1 64 bits Double -263 to 263-1 VARIABLES A variable is an item of data used to store state of objects. A variable has a data type and a name. The data type indicates the type of value that the variable can hold. The variable name must follow rules for identifiers. Declaring and Initializing Variables To declare a variable is as follows, [=initial value]; Note: Values enclosed in are required values, while those values enclosed in [] are optional. Here is a sample program that declares and initializes some variables, public class VariableSamples { public static void main( String[] args ){ 7 Unit 1: Introduction to JAVA Programming //declare a data type with variable name // result and boolean data type boolean result; //declare a data type with variable name // option and char data type char option; option = 'C'; //assign 'C' to option //declare a data type with variable name //grade, double data type and initialized //to 0.0 double grade = 0.0; } } Outputting Variable Data In order to output the value of a certain variable, we can use the following commands, System.out.println() System.out.print() Here's a sample program, public class OutputVariable { public static void main( String[] args ){ int value = 10; char x; x = ‘A’; System.out.println( value ); System.out.println( “The value of x=“ + x ); } } The program will output the following text on screen, 10 The value of x=A System.out.println() vs. System.out.print() What is the difference between the commands System.out.println() and System.out.print()? The first one appends a newline at the end of the data to output, while the latter doesn't. OPERATORS 8 Unit 1: Introduction to JAVA Programming In Java, there are different types of operators. These are arithmetic operators, relational operators, logical operators and conditional operators. Arithmetic Operators Here are the basic arithmetic operators that can be used in creating your Java programs, Operator Use Description + op1 + op2 Adds op1 and op2 - op1 – op2 Subtracts op2 from op1 * op1 * op2 Multiplies op1 by op2 / op1 / op2 Divides op1 by op2 % op1 % op2 Computes the remainder of dividing op1 by op2 Here's a sample program in the usage of these operators: public class ArithmeticDemo { public static void main(String[] args) { //a few numbers int i = 37; int j = 42; double x = 27.475; double y = 7.22; System.out.println("Variable values..."); System.out.println(" i = " + i); System.out.println(" j = " + j); System.out.println(" x = " + x); System.out.println(" y = " + y); //adding numbers System.out.println("Adding..."); System.out.println(" i + j = " + (i + j)); //subtracting numbers System.out.println("Subtracting..."); System.out.println(" i - j = " + (i - j)); //multiplying numbers System.out.println("Multiplying..."); System.out.println(" x * y = " + (x * y)); //dividing numbers System.out.println("Dividing..."); System.out.println(" i / j = " + (i / j)); //computing the remainder resulting from //dividing numbers System.out.println("Computing the //remainder..."); System.out.println(" i % j = " + (i % j)); 9 Unit 1: Introduction to JAVA Programming } } Here is the output of the program, Variable values... i = 37 j = 42 x = 27.475 y = 7.22 Adding... i + j = 79 Subtracting... i - j = -5 Multiplying... x * y = 198.37 Dividing... i/j=0 Computing the remainder... i % j = 37 Increment and Decrement operators Aside from the basic arithmetic operators, Java also includes a unary increment operator (++) and unary decrement operator ( -- ). Increment and decrement operators increase and decrease a value stored in a number variable by 1. For example, the expression count = count + 1; //increment the value of count by 1 is equivalent to, count++; Operator Use Description ++ op++ Increments op by 1; evaluates to the value of op before it was incremented ++ ++op Increments op by 1; evaluates to the value of op after it was incremented -- op-- Decrements op by 1; evaluates to the value of op before it was decremented -- --op Decrements op by 1; evaluates to the value of op after it was decremented 10 Unit 1: Introduction to JAVA Programming The increment and decrement operators can be placed before or after an operand. When used before an operand, it causes the variable to be incremented or decremented by 1, and then the new value is used in the expression in which it appears. For example, int i = 10; int j = 3; int k = 0; k = ++j + i; //will result to k = 4 + 10 = 14 When the increment and decrement operators are placed after the operand, the old value of the variable will be used in the expression where it appears. For example, int i = 10; int j = 3; int k = 0; k = j++ + i; //will result to k = 3 + 10 = 13 Example: public class Variables { public static void main(String[] args) { //a few numbers int i = 37; int j = 42; double x = 27.475; double y = 7.22; System.out.println(" i++ = " + i++); System.out.println(" --i = " + --i); System.out.println(" --j = " + --j); System.out.println(" x++ = " + x++); } } Output: i++ = 37 --i = 37 --j = 41 x++ = 27.475 Relational operators 11 Unit 1: Introduction to JAVA Programming Relational operators compare two values and determine the relationship between those values. The outputs of evaluation are the boolean values true or false. Operator Use Description > op1 > op2 op1 is greater than op2 >= op1 >= op2 op1 is greater than or equal to op2 < op1 < op2 op1 is less than op2 j = false k >= j = true k == j = true k != j = false 12 Unit 1: Introduction to JAVA Programming Logical operators Logical operators have one or two boolean operands that yield a boolean result. && (logical AND) Here is the truth table for &&, x1 x2 Result TRUE TRUE TRUE TRUE FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE Here's a sample source code that uses logical and boolean AND, public class TestAND { public static void main( String[] args ){ int i = 0; int j = 10; boolean test= false; //demonstrate && test = (i > 10) && (j++ > 9); System.out.println(i); System.out.println(j); System.out.println(test); } } The output of the program is, 0 10 false || (logical OR) Here is the truth table for ||, x1 x2 Result TRUE TRUE TRUE TRUE FALSE TRUE FALSE TRUE TRUE FALSE FALSE FALSE 13 Unit 1: Introduction to JAVA Programming Here's a sample source code that uses logical OR, public class TestOR { public static void main( String[] args ){ int i = 0; int j = 10; boolean test= false; //demonstrate || test = (i < 10) || (j++ > 9); System.out.println(i); System.out.println(j); System.out.println(test); } } The output of the program is, 0 10 True ! ( logical NOT) The logical NOT takes in one argument, wherein that argument can be an expression, variable or constant. Here is the truth table, x1 Result TRUE FALSE FALSE TRUE Conditional Operator (?:) The conditional operator ?: is a ternary operator. This means that it takes in three arguments that together form a conditional expression. The structure of an expression using a conditional operator is, exp1?exp2:exp3 wherein exp1 is a boolean expression whose result must either be true or false. If exp1 is true, exp2 is the value returned. If it is false, then exp3 is returned. For example, given the code, public class ConditionalOperator { public static void main( String[] args ){ String status = ""; int grade = 80; //get status of the student status = (grade >= 60)?70:90"; 14 Unit 1: Introduction to JAVA Programming //print status System.out.println( status ); } } The output of this program will be, Passed Operator Precedence Operator precedence defines the compiler’s order of evaluation of operators so as to come up with an unambiguous result. The following is the list of Java operators from highest to lowest precedence: () ++ -- ! * / % + - < > = == != & | ^ && || = The highest precedence is on top row and the lowest is on the bottom row. Given a complicated expression, 6%2*5+4/2+88-10 We can re-write the expression and place some parenthesis base on operator precedence, ((6%2)*5)+(4/2)+88-10; Java User Input (Scanner) Java User Input The Scanner class is used to get user input, and it is found in the java.util package. To use the Scanner class, create an object of the class and use any of the available methods found in the Scanner class documentation. In our example, we will use the nextLine() method, which is used to read Strings: Example 15 Unit 1: Introduction to JAVA Programming import java.util.Scanner; // Import the Scanner class class MyClass { public static void main(String[] args) { Scanner myObj = new Scanner(System.in); // Create a //Scanner object System.out.println("Enter username"); String userName = myObj.nextLine(); // Read user input System.out.println("Username is: " + userName); // Output user // input } } Input Types In the example above, we used the nextLine() method, which is used to read Strings. To read other types, look at the table below: Method Description nextBoolean() Reads a boolean value from the user nextByte() Reads a byte value from the user nextDouble() Reads a double value from the user nextFloat() Reads a float value from the user nextInt() Reads a int value from the user nextLine() Reads a String value from the user nextLong() Reads a long value from the user nextShort() Reads a short value from the user In the example below, we use different methods to read data of various types: 16 Unit 1: Introduction to JAVA Programming Example import java.util.Scanner; class MyClass { public static void main(String[] args) { Scanner myObj = new Scanner(System.in); System.out.println("Enter name, age and salary:"); // String input String name = myObj.nextLine(); // Numerical input int age = myObj.nextInt(); double salary = myObj.nextDouble(); // Output input by user System.out.println("Name: " + name); System.out.println("Age: " + age); System.out.println("Salary: " + salary); } } 17

Use Quizgecko on...
Browser
Browser