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

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

Document Details

HospitableLosAngeles

Uploaded by HospitableLosAngeles

Tags

java programming object-oriented programming software development computer science

Full Transcript

SE101.3 Object Oriented Programming using Java General Module Aims  To introduce some object-oriented.  To develop object-oriented programming skills using the Java language. How the module works ~  Create a solid foundation by looking closely at classes and obj...

SE101.3 Object Oriented Programming using Java General Module Aims  To introduce some object-oriented.  To develop object-oriented programming skills using the Java language. How the module works ~  Create a solid foundation by looking closely at classes and objects.  Use a professional approach – coding style, testing, design.  Learn how to create a graphical user interface to interact with the objects in the system. Lecture 01 Java Basics Java – Originally for intelligent consumer- electronic devices (cell phones) – Then used for creating Web pages with dynamic content – Now also used for: Develop large-scale enterprise applications The Java Programming Language A high-level language that can be characterized by all of the following: Object-orientated programming language Platform independent Strongly-typed programming language Interpreted and compiled language Automatic memory management The Java Platform The Java Platform differs from most of the other platforms.. Because it’s a software only platform. Which will run on the top of other Hardware based platforms. Terminology: The Java Application Programming Interface (API) A large collection of ready-made software components. It is grouped into packages of related classes and interfaces Java Virtual Machine (JVM) JVM is the foundation of the Java Platform. The environment in which java runs. The JVM is responsible for executing the byte codes and responsible for fundamental capabilities of java. Byte codes are platform independent therefore will not depend on a particular hardware platform. So these byte codes may execute on any platform containing a JVM. Write application once, runs on any………!!! Java life cycle:- Java programs normally undergo four phases – Edit Programmer writes program (and stores program on disk) – Compile Compiler creates bytecodes from program (.class) – Load Class loader stores bytecodes in memory – Execute Interpreter: translates bytecodes into machine language In the Java programming language, all source code is first written in plain text files ending with the FileName.java extension. Those source files are then compiled into.class files by the javac compiler. FileName.class file does not contain code that is native to your processor; it instead contains bytecodes — the machine language of the Java Virtual Machine (Java VM). The java launcher tool then runs your application with an instance of the Java Virtual Machine. package helloworldapp; public class HelloWorldApp { public static void main(String[] args) { System.out.println("Hello World!"); // Display the string. } } Identify: Package declaration Class Declaration Starts with a Capital letter. Method Declaration Comments (3 types) Source Code Comments Comments are ignored by the compiler but are useful to other programmers. The Java programming language supports three kinds of comments: The compiler ignores everything from. This indicates a documentation comment (doc comment, for short). The compiler ignores this kind of comment, just like it ignores comments that use. 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 As shown above, the most basic form of a class definition is: class ClassName {... } 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. For now it is enough to know that every application begins with a class definition. The main Method 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. You can name the argument anything you want, but most programmers choose "args" or "argv". The main method is similar to the main function in C and C++; it's the entry point for your application and will subsequently invoke all the other methods required by your program. Compile and Execute Your First Program First Save your file with.java extension in known location. e.g. HelloWorldApp.java Compile your code as follows: javac HelloWorldApp.java Both the compiler (javac) and launcher tool (java) are case- sensitive, To run your program: java HelloWorldApp Output: Hello World! Java is case-sensitive! This means that a variable named as Count, for example, would NOT be the same as a variable named as count or COUNT. So, if you get an error message telling you that an identifier has not been declared, and you think you have declared it, check the case! Identifiers These are the words that define statements, variable names, function names, and so on. The rules for making up identifiers are: you may use only letters, digits and underscore they must start with a letter or underscore (but avoid starting with underscore as this may be used for system functions and constants) any length, but only first 32 characters significant?? certain identifiers are reserved as keywords Conventions variable names - mostly in lower case, using camelCase, i.e. start with lower case, and if multiple words are used, start each subsequent word with a capital, e.g. grandTotal, numberOfLines. Underscores are not commonly used in variable names. You should not need to be reminded to use meaningful names! function names – same as for variable names, e.g. changeStatus , getTotal. class names – same as for variable names but with the first letter as a capital, e.g. Person, Car, User. keywords (i.e. those that represent statements, like if and while, and data types) – always in lower case – you have no choice. If you use the wrong case for a keyword it will not be recognised! names for constants – all upper case Coding style Statements are terminated by ; characters. Blocks start with { and end with } A statement can be split over several lines – you can help make the code clearer and avoid untidy word wrap! Blank lines between statements improve clarity. Use indenting within structures for clarity. Use indenting within structures for clarity. Which of the following do you prefer? text=studentName;if (totalMark>=40) {text=text+"has passed";grade =1;} else {text=text+"has failed";grade=0;} or text=studentName; if (totalMark>=40) { text=text+"has passed"; grade=1; } else { text=text+"has failed Using comments: Introduce every program with a comment - giving name, date written, outline of purpose. Add comments to your code as you write it (so that later on you will remember why you did it that way!). Don’t under-comment and don’t over-comment. It is better to put two or three lines at the start of several lines of code, giving a general description, rather than add comments to the ends of lines which can make code difficult to read and difficult to modify! For example: // Loop through the array, calculating // the sum of the values, then calculate the // average. for (int i = 0; i < noOfValues; i++) sum = sum + value[i]; average = sum / noOfValues; NEXT….. Refresher ☺ DATA TYPES OPERATORS CONTROL FLOW STATEMENTS Data Types In java there are 8 Primitive data types: Integers byte 8bits short 16bits int 32bits long 64bits Real float 32bits double 64bits Character char 16bits Boolean boolean 1bit Operators:- Perform a function on operands 5+3 8 Operand 1 Operand 2 Result Operator Operators can take ▪ One operand (unary operators) ▪ Two operands (binary operators) ▪ Three operands (ternary operators) Operators: Operators can be divided into categories: ▪ Arithmetic ▪ Increment & Decrement ▪ Assignment ▪ Shorthand ▪ Comparison ▪ Relational Variables: Declaration: To declare a variable, give the type, then one or more spaces, then the name, then a semicolon. int total; String name; double rate; Initialisation: Variables are usually but not necessarily automatically initialised to zero, but you can specify an initial value when declaring the variable, e.g. int value = 0; Constants Literal constants - for strings and characters, it is important to use the correct punctuation. For a character constant use single quotes, e.g. 'a' For a string constant use double quotes, e.g. "Hello world" Symbolic constants The keyword final is used, and the name is all capitals: final int MAXRECORDS = 100; Casting Used to carry out temporary conversion of a value to another type, for example converting an integer type to a floating point type in order to avoid integer division. To cast the value of an expression to another type, precede the expression with the required type name, enclosed in round brackets, e.g. average = sum / (float)noOfValues; int num1 = 4; int num2 = 7; num2 / num1 num2 / 2 num2 / 2.0 (double)num2 / 2 (double)num2 / num1 (double)num2 / (double)num1 num2 / (double)num1 int num1 = 4; int num2 = 7; num2 / num1 would give the answer 1 (1.75, truncated) num2 / 2 would give the answer 3 (3.5, truncated) num2 / 2.0 would give the answer 3.5 (double)num2 / 2would give the answer 3.5 (double)num2 / num1 (double)num2 / (double)num1 num2 / (double)num1 would give the answer 1.75 Shorthand Operator: invoiceTotal += itemTotal; Increment and decrement Operator: int x=10,y; y = x ++; System.out.println(x +" "+ y); y = ++ x; System.out.println(x +" "+ y); Control Flow Statements Looping statements (for, while, do-while, for each) Decision-making statements (if-then, if-then-else, switch) Branching statements (break, continue, return) Looping statements (for, while, do-while, for each) Ex: // Class will dispaly the function of a while Loop public class TestWhileLoop{ public static void main(String args[]){ int loop=0; while(loop1); } } Ex: // Class will display the function of a for Loop public class TestForLoop{ public static void main(String args[]){ for(int loop = 0; loop < 5; loop+=1){ System.out.println(“Executing Loop " + loop ); } } } Result: Executing Loop 0 Executing Loop 1 Executing Loop 2 Executing Loop 3 Executing Loop 4 The enhance for Loop :- As of java 5 the enhanced for loop was introduced. This is mainly used for Arrays. Syntax: for(declaration : expression){ //statement to be print } Ex: // Class will dispaly the function of a Enhance For Loop class TestEnhanceForLoop { public static void main(String args[]){ int [] numbers = {10, 20, 30, 40, 50}; for(int x : numbers ){ System.out.print( x ); System.out.print(","); } System.out.print("\n"); String [] names ={“James”, "Larry", "Tom", "Lacy"}; for( String name : names ) { System.out.print( name ); System.out.print(","); } } } Branching statements (break, continue, return) Ex. public class TestBreak { public static void main(String args[]){ int [] numbers = {10, 20, 30, 40, 50}; for(int x : numbers ){ if( x == 30 ){ break; } System.out.print( x ); System.out.print("\n"); } System.out.print(“I’m out of the Loop now"); } } Result: 10 20 Now Out of the Loop Ex. // Class will display the function of a Continue statement public class TestContinue { public static void main(String args[]){ int [] numbers = {10, 20, 30, 40, 50}; for(int x : numbers ){ if( x == 30 ){ continue; } System.out.println( x ); } } } Decision-making statements (if-then, if-then-else, switch) Ex: // Class will dispaly the function of a if Loop public class TestIfCondition { public static void main(String args[]){ int x = 30; if( x < 20 ){ System.out.print("This is if statement"); }else{ System.out.print("This is else statement"); } } } Ex: public class TestIfElseIfCondition { public static void main(String args[]){ int x = 30; if( x == 10 ){ System.out.print("Value of X is 10"); }else if( x == 20 ){ System.out.print("Value of X is 20"); }else if( x == 30 ){ System.out.print("Value of X is 30"); }else{ System.out.print("This is else statement"); } } } Ex: public class TestNestedIfCondition { public static void main(String args[]){ int x = 30; int y = 10; if( x == 30 ){ if( y == 10 ){ System.out.print("X = 30 and Y = 10"); } } } Ex: public class Test { public static void main(String args[]){ char grade =‘A’; switch(grade) { case 'A' : System.out.println("Excellent!"); break; case 'D' : System.out.println("You passed"); case 'F' : System.out.println("Better try again"); break; default : System.out.println("Invalid grade"); } System.out.println("Your grade is " + grade); } } Result: Excellent! Your grade is a A NEXT CLASS: Methods Array/ String OOP Before Next Class: Complete the lab schedule Thank You

Use Quizgecko on...
Browser
Browser