Java Programming Notes PDF

Summary

These notes provide an introduction to Java programming, covering basic concepts like classes, objects, variables, and comments. They also discuss the Java programming language and how to work with programming objects.

Full Transcript

## JAVA into notes ### What is a class? - All Java programs are contained in a class. - The start of a class is indicated by the reserved word `class`. - There are about fifty (50) reserved words in Java. - **Brackets `{}`**: Brace brackets are used to indicate the beginning and end of any sec...

## JAVA into notes ### What is a class? - All Java programs are contained in a class. - The start of a class is indicated by the reserved word `class`. - There are about fifty (50) reserved words in Java. - **Brackets `{}`**: Brace brackets are used to indicate the beginning and end of any section of a Java program. - **Comments `//`**: Two slashes indicate a comment in Java. - Anything on a line after the `//` is ignored by the compiler. - It is also possible to enclose longer sections of code in a comment using the older style of comments: - `/* beginning of comments end of comments */` ### JAVA 1 #### What is Programming? What does a comp program do? - A computer program tells a computer in minute detail the sequence of steps that are needed to fulfill a task. - The act of designing and implementing these programs is called computer programming. #### The Java Programming Language - In 1991 a group led by James Gosling and Patrick Naughton at Sun Microsystems designed a language that they code named "Green" for use in consumer devices such as intelligent television "set-top boxes". - The language was designed to be simple and architecture-neutral, so that it could be executed on a variety of hardware. - Gosling realized in 1994 "We could write a really cool browser" - The HotJava browser was shown to an enthusiastic crowd at the SunWorld exhibition in 1995, and had one unique property. - It could download programs called Applets, from the web and run them. - Applets written in the language now called Java, let web developers provide a variety of animations and interaction that can greatly extend the capabilities of a web page. - In 1996 both Netscape and Microsoft supported Java. #### Java Programming - System.out.println Method - `System.out.print("\n")` - will take me to the next line (this is a reserved character in Java- there are many reserve characters - we will look at this later in the course) ### Object #### What is an object? - An Object is an entity that you can manipulate in your program by calling Methods. - For example you saw in yesterday's class that `System.out` refers to an Object and you saw manipulate it by using the Method (`println`). #### What are considered as 'black bones'? - You should think of the objects as a "black box" with a public interface (the methods that call) and a hidden implementation (the code and data that are necessary to make these methods work). #### What does a class do? - Every Object belongs to a class. - The class defines the methods for the objects. - There the String class defines the `length` method and many other methods. #### String class defines which method? - The `system.out` method is created automatically what a Java program loads the System class. #### system.out Method is related to which class? - Let us create an Object. - We are going to use the Rectangle Class in the Java library. **Note:** - The Rectangle object isn't a rectangular shape - it is a set of numbers that describe the rectangle. - Each rectangle is described by the x and y coordinates of its top left corner, its width and its height. - i.e. (5, 10, 20, 30) **To implement a rectangle object use the following:** - `System.out.println(new Rectangle ((5, 10, 20, 30));` - you can also use `Rectangle namer = new Rectangle (5, 10, 20, 30);` - this will give the object the name namer **Try both** #### What is your output for the System.out? #### What is the pro of creating new? #### New command causes the creation of what? - The `new` command causes the creation of an object of type Rectangle. - This process of creating a new object is called construction. - The four values 5,10,20,30 are called the construction parameters. - Different classes will require different construction parameters #### A class definition contains two types of elements: variables and methods - Variables are used to store the Objects information. - Methods are used to process the information. #### Instance field - A Variable defined in a class for which every object of the class has its own value. #### Variable - A Symbol in a program that identifies a storage location that can hold different values. ## Example: - `public class Rectangle` - `private double length;` // instance variables - `private double width;` - `public Rectangle (double I, double w){` - `ength =l;` - `vidth = w;` // rectangle constructor - `public double calculateArea()` - `return length*width;` ## Data Type #### What is a variable? - A variable is a named piece of memory that you use to store information in your java program. - Each variable has three important attributes: - **a name that you choose** (`Identifier`) - **a value that you give it and that you can change.** - **A type which limits what kind of value you can hold.** #### What 3 attributes a variable has? #### What is an identifier? - The name that you choose for a variable is called an identifier. - An identifier can be any length, but must start with a letter and underscore or a dollar sign. - An identifier must start with `Eg. int numberOfstudents = 98;` #### How many basic types of data type? #### categories of datatype? **Data Types - 8 basic types** **Defined in three categories.** 1. **Numeric** - `Integers` - `Placting points` - `int` - `short` - `long` - `float` - `double` - `Type char (single)` 2. **Boolean** - `true` - `false` - `Byte` 3. **Characters** #### How many kinds of numeric data type are there? - There are two kinds of numeric data types (integers (no fractions) and floating points - There are four types of integers (byte, Short, int and Long). - Within Floating point data type there are float and double) #### Name types of integers and floating points? ## Numeric Values that can be store from Numeric Data Type | Type | Storage | Min Value | Max Value | | :-------- | :-------------------- | :---------- | :---------- | | byte | 8 bits | -128 | 127 | | short | 16 bits | -32 768 | 32 767 | | int | 32 bits | -2 147 483 648 | 2 147 483 647 | | long | 64 bits | -9 223 372 036 854 | 9 223 372 036 854 | | float | 32 bit | -3.40E+038 | 3.40E+037 | | double | 64 bit | -1.70E+308 | 1.70E+308 | **Examples:** - `int intValue = 4;` - `double doubleValue =1.493233434;` ## Characters - A variable of type `char` holds a single character. **Example:** - `Char charValue = 'c';` - `Char charVall = '\t';` **Special Characters:** - `\b` = backspace - `\t` = tab - `\n` = newline - `\r` = Carriage return - `\"` = Double Quote - `\'` = Single Quote - `\\` = Backslash - **Is it possible to specify a character by quoting its number within the Unicode character set. The system runs from 0 to 65535, but it must be specified in hexadecimal following the prefix?** - `\u, so it runs from \u0000 to \uFFFF` **Example:** - `char CharValue2='\u0045';` ## Booleans - The Boolean data type has only two valid values: true and false. - A Boolean variable is usually used to indicate if a particular condition is true or not. **Example** - `boolean found = true;` ## Arithmetic Expressions - Programming statements often involve expressions which are combinations of operators and operands used to perform calculations. - All expressions are evaluated according to an operator precedence hierarchy that establishes the rules that govern the order in which the operations are evaluated. - **What is operator precedence hierarchy?** - Any arithmetic operator at the same level of precedence are performed left to right. - Any expression in parentheses is evaluated first. - Parentheses can be nested, and the innermost expressions are evaluated first. ## Constants - Constants are identifiers and are similar to variables except that they hold a particular value for the duration of their existence. - **What are constants and how are they different from variables?** **the syntax:** - `nal typeName variableName = expression.` **Example** - `nal double NickelValue = 0.98;` ## Java User Input - The `Scanner class` is used to get user input. - When using the Scanner class, create an object of the class and use one of the available methods. **Example:** - `mport java.util.Scanner; // Use this command to import the Scanner` - `class` - `class testing_input {` - `public static void main(String[] args) {` - `Scanner object = new Scanner(System.in); // This will create a Scanner object` - `System.out.println("Enter username");` - `String Name = object.nextLine(); // This will read the input by the user` - `System.out.println("Username is: " + Name); // This will output the Name` - `}` - `}` ## Method | 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 | ## Getting Started With Java – Variables - In order to create useful programs, we need the ability to store information and retrieve that information as needed. - Information is stored in the memory of the computer in specially reserved areas known as variables. - **Why are identifiers used?** - In order to keep track of these variables, we use identifier names (or simply identifiers) for each variable, method, or class in our program. - The rules for creating any type of identifier are: - Any character used in an identifier must be a letter or the alphabet, a digit (0, 1, ..., 9), or an underscore character (_). - The first character cannot be a digit - **By convention, classes are given identifiers using PascalCase, where each word begins with a capital letter.** - **By convention, variables and methods are given identifiers using camelCase, where the first letter is lowercase, and any other words in the identifier are uppercase.** - You cannot use any of the following reserved words, each of which has a predefined meaning in the Java language. | | | | | | | | | | | | :-------- | :---------- | :------- | :------ | :-------- | :------- | :-------- | :------ | :-------- | :-------- | | abstract | assert | boolean | break | byte | case | catch | const | continue | default | | double | do | else | enum | extends | false | final | for | goto | if | | implements | import | instanceof | int | interface | long | native | new | null | package | | private | protected | public | return | short | static | strictfp | super | switch | synchronized | | this | throw | throws | transient | true | try | void | volatile | while | | ## Declaring Variables - **Why do we need declaration statements?** - To reserve space in memory for variables, we need to write a declaration statement, where we specify the type of a variable and its identifier (i.e., name). - **What do you specify when declaring?** - A simple declaration might look like `<type> <identifier>;` **For example:** - `int count;` - `float area;` - `boolean finished;` - Note the a declaration statement, like any other statement in Java is terminated (i.e., ended) by the semicolon character. - It is possible to declare multiple variables of the same type using a single declaration statement of the form `<type> <identifier₁>, <identifier2>, .... <identifierk>;` **For example:** - `float radius, circumference, area;` ## Assigning Values to Variables - Declaring a variable reserves space in the computer's memory for information of a particular data type (e.g., int, or float, or char). - This variable does not become useful until we assign a value to it. - **How and what are the ways to assign variables?** - **Until when declaring variable becomes useful?** 1. **When declaring the variable** - `int total = 15;` 2. **Immediately after declaring the variable** - `int total;` - `total = 15;` 3. **After declaring the variable, but later in the program** - `int total;` - `total = 15;` 4. **Using the value from another variable** - `int a = 5;` - `int b;` - `b = a;` ## Converting Between (Numeric) Data Types - **What is important when assigning a value to a variable?** - The assigning a value to a variable, it is important that the data type match the value. - For numeric data types, it is possible to convert from a smaller data type to a larger data type, but not the reverse. - **What is the old of legal conversions ?** - **Is it possible to forme Java to accept a conversion?** - **legal conversions:** byte → short → char → int → long → float → double - It is possible to force Java to accept a conversion, even if it breaks Java's own rules. This is called a cast, and it is essentially a promise to the compiler that you know what you are doing. - It has the form: `<variable> = (<data type>) <questionable data>;` **For example,** - `short a;` - `a = (short) 75000;` - `System.out.println(a);` - // range of -30000 to +30000 - // 75000 doesn't fit in short - override! - // output will be 9464 since 75000 - // doesn't fit! ## Dutput of Variables - The `print` and `printin` methods can be used to output variables or combinations of variables. - Keep in mind that the variable must have been given a value before you try to output it, or you will get an error. ## Class PrintValue - `public static void main(String[] args)` - `{ - `int length = 5;` - `int width = 10;` - `System.out.print("The length is " + length); ` - `System.out.println(" and the width is " + width);` - `}` - The length is 5 and the width is 10 ## Constants - Java allows us to associate an identifier with a constant value through the use of the `final` modifier in the declaration of a variable. - By convention, constants are given identifiers which are all upper case, which helps easily identify them when reading code. - `final int CLASS_SIZE = 30;` - `final char TERMINATOR = '*';` - `final float PI = 3.1415;` - Once an identifier has been declared to be final, its value can never be changed. ## Numeric Operations | Order | Operator | Operation | | :---- | :------- | :----------------------------------- | | 1 | `()` | Parentheses | | 2 | `++ --` | Increment, Decrement | | 3 | `new` | Object creation | | 4 | `*/%` | Multiplication, Division, Modulus | | 5 | `+-` | Addition, Subtraction | | 6 | `><== >= =` | Relational Operators, Logical Operations | | 7 | `==!=` | Equality Operators | | 8 | `&` | Boolean AN | | 9 | `^` | Boolean XOR | | 10 | `\|` | Boolean OR | | 11 | `&&` | Logical AND | | 12 | `\|\|` | Logical OR | | 13 | `?:` | Conditional Operator | | 14 | `= += -= *= /= %=` | assignment | **Example:** - `9+6<=25*4+2 ` - `Step 1: (9+6) < = ((25 * 4) + 2 )` - `Step 2: (9+6)<= (100 + 2)` - `Step 3: 15 <= 102` - `Step 4: true` ## Arithmetic promotion - **What is arithmetic promotion?** - Occurs automatically when certain arithmetic operators need to modify their operands in order to perform the operation. **Example:** - `X=9+6/5` - `1. 16/5 = 3` - `2. 9+3=12` - `3. 12` - **What happens when 2 different types of are involved?** - In general when two different types are involved in a operation, the smaller type (the one with fewer bits) is converted to the larger type before the operation is performed. ## Class Library - **What is class library?** - The class library is made up of several clusters of related classes, which are called JAVA API. API stands for Application Programmer Interface. - The classes of the Java Standard class library are also grouped into packages, which like the APIs; lets us group related classes by one name. - The String class for example is part of the `java.lang` package. #### Examples: | Package | Provides support to: | | :---------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `Java.Applet` | Create programs (Applets) that are easily transported across the web | | `Java.awt` | Draw graphics and create graphical user interfaces | | `Java.io` | Perform a wide variety of input and output functions | - **Syntax:** `import java.Applet.*; // opens everything from Applet` #### Exiting an Application: - Use the following code: - `System.exit(0);` ## Reading Console Input/Alternative - **What does console input read?** - Console input reads from the `System.in` object, which can only read bytes. - Keyboard consists of characters. - **What do you have to do in order to read characters?** - To get a reader for characters, you have to turn `System.in` into an `InputStreamReader` object: **Syntax:** - `InputStreamReader reader = new InputStreamReader (System.in);`<br> - An input stream reader can read characters, but can't read a whole String at a time. - **How to overcome limitation of InputStreamReader?** - To overcome this limitation you turn an `InputStreamReader` into a `BufferReader..` **Syntax:** - `BufferedReader console = new BufferedReader(reader);` **Example Coding** - `import java.io.*; // opens everything from java.io` - `Public class ReadingInput` - `{` // open ReadingInput - `public static void main(String[] args) throws IOException` - `{` // open main - `InputStreamReader reader = new InputStreamReader(System.in);` ## The If Statement - **What does an if statement do?** - The if statement lets a program carry out different actions depending on outcome of a condition. - An if statement consist of ther reserved word `if` followed by a boolean expression, or condition. - The condition is enclosed in brackets and must evaluate true or false. - If the condition is true then the statement is executed - If the condition is false then the statement is skipped **Syntax** - `if (expression/condition )` - `statement;` - `next statement;` **Example:** - `ublic class example_1 {` - `ublic static void main (String args [])` - `{ - `int num = 5;` - `(num %2==1)` - `ystem.out.println(num + " is odd number");` - `(num%2 == 0)` - `System.out.println (num + " is even number");` - `}` - `}` ## The if - else Statement - **What does an if/else statement do?** - An if – else statement allows a program to do one thing if a condition is true and different thing if the condition is false. **Syntax** - `if (expression/condition)` - `{ - `Statement;` - `}` - `else` - `{` - `statement;` - `}` **Example:** - `public static void main (String args[])` - `{ - `int num = 5;` - `if (num % 2 == 1)` - `System.out.println (num + " is odd number");` - `else` - `System.out.println(num + “is even number");` - `}` - `}` ## If - Elseif **Syntax** - `If (condition/expression) // lower case if` - `{ - `statement;` - `}` - `elseif (condition/expression)` - `{ - `statement;` - `}` - `elseif (condition/expression)` - `{ - `statement;` - `}` - `else` - `{ - `statement;` - `}` - `} // close if` ## Iterations - **What is the purpose of a while loop?** - A while statement executes a block of code repeatedly. - A termination condition controls how often the loop is executed. **Syntax** - `while (expression)` - `{ - `// statements;` - `}` **Example:** - `public class example_1` - `{ - `public class static void main (String args[])` - `{ - `final int limit =5;` - `int count =0;` - `while (count<limit)` - `{ - `System.out.println(++count );` - `}` - `}` - `}` - **What happens when given logical expression becomes false?** - This loop executes as long as the given logical expression between brackets is true. - When the expression is false, execution continues with the next statement outside of the loop. **Example_2:** - `public class example2` - `{ - `public static void main(String args[])` - `{` - `int count =1;` - `while count <= 10)` - `{ - `String display = count % 2 == 1 ? " ****" : " ***";` - `System.out.println (display);` - `++ count;` - `}` - `}` - `}` ## The do Statement - **Difference b/w while and do loop?** - The do statement is similar to the while statement, except that its termination condition is at the end of the body of the loop. - Like the while loop, the do loop executes the statements in the loop body until the condition becomes false. - The condition is written at the end of the loop to indicate that is not evaluated until the body of the loop is executed. - Therefore the body of a do loop is always execuated at least once. **Example:** - `public class example3` - `{ - `public static void main(String args [])` - `{ - `final int limit =5;` - `int count =0;` - `do` - `{ - `System.out.println (++count);` - `}` - `while (count<limit)` - `}` - `}` **Syntax** - `do` - `{ - `// statements;` - `}` - `while (expression)` ## The for Statement - **What is the fundamental diff b/w while and do staments and for statement?** - The while and do statements are good to use when you don't initially know how many times you want to execute the loop body. - The for statement is another repetition statement that is particularly well suited for looping a specific number of times. **Syntax:** - `for (initialization_expression; loop_condition; incrament_expression)` - `{ - `//statements;` - `}` - **what are the 8 parts of for statement?** - The first part - initialization_expression: - This is executed before execution of the loop starts - `loop_condition` – loop will continue as long as this statement is true. The condition is checked at the beginning of each loop cycle - `incrament_expression` - used to incrament loop counter. **Example:** - `public class example_4` - `{ - `public static void main(String args [])` - `{ - `final int limit = 6;` - `for (int count =0; count < limit; count++) - `System.out.println (count);` - `}` - `}` - `}` **Example:** - `public class example_5` - `{ - `public static void main (String args[])` - `{ - `for (int i=0; <= 10; i++)` - `{ - `for (int j = 0; j <= 5; j++)` - `{ - `System.out.println("*");` - `}` - `System.out.println();` - `}` - `}` - `}` ## Arrays - **What is an array?** - An array is a data structure that defines an ordered collection of a fixed number of the same data type. - The size of an array is fixed and cannot increase to accommodate more elements. - In Java, arrays are objects. - **Simple arrays are one-dimensional arrays → simple list of values.** ### Declaring array variables **Syntax:** - `<elementType> [] arrayName;` - or - `<elementType><arrayname> [];` **where `<elementType>` is the variable type → int, String, long, float etc...** ### Examples - `int a [], b;` - `Rectangle [] medium, large;` - **Is variable b an array of type int?** - When `[]` follows the type, all variables in the declaration are arrays. - Otherwise the `[]` notation must follow each individual array name in the declaration. ### Constructing an Array - **How can an array be constructed?** - An array can be constructed for a specific number of elements type, using the `new` operator: - `<arrayname> = new <elementtype> [ <NumberofElements>]` - The minimum number of elements is 0. **Example:** - `int a [], b;` - `Rectangle [] medium, large;` **Array construction:** - `a= new int [10]; // array for 10 integers` - `medium = new Rectangle [5]; // array of 5 Rectangles;` **The array construction can be combined:** `<elementType> <arrayName> [] = new <elementType> [<numberOfElements>];` **Example:** - `Int a[] = new int [10];` - `Rectangle medium [] = new Rectangle [5];` ### Initializing an Array - `<elementType> [] <arrayName. = {< values>];` **Examples:** - `Int a [] = { 1, 256, 123};` - `String courses [] = {"com", "sci"};` - We can also assign values: - **How is the whole array referenced?** - **What are individual elements of an array called?** ### Using an Array - The whole array is referenced by the array name, but the individual array elements (index) are accessed using the `[]` operator. - **How are indexes accessed?** - The lower bound of any array is 0, the upper bound is one less than the number of elements. - **What are the upper and lower bounds of an array?** **Example:** - `Int a [] = new int [10];` - // has 10 elements - **To access the first element** - `a [0]` - **To access the last element** - `a [9]` - **There is no a [10];** - We can also assign values using our element index. - `Int a[] = new int [10];` - `a [0] = 10;` - `a [9] = 20;` - **This is very useful in a looping structure.** - **assigning values by using element index** ## Class Exercise: - Given the following, write a method within the Example class, called `Maximum` to determine the maximum value of the array `b`. - **Things to consider:** - Do I need an array? - Should I create another array to check and store the information? - **To determine the length of an array use the .length Method** **Example:** - `a.length` - where a is the array - `length` is the method which will return an int – make sure you save this a variable if needed. - `Public class Example` - `{ - `Public static void main (String[] args)` - `{ - `Example ex = new Example ();` - `double b [] ={10,12,5,-1,2};` - `System.out.println("The maximum is: + ex.Maximum(b));` - `}` - `}` ## Sorting Algorithms in Java - **Why programmers use sorting algorithms?** - There are many different sorting algorithms that programmers use to sort information in a list (array), most often in numerical or alphabetical order. - **Name one method to sort info in an away?** - One of the more common and easy to understand, although less efficient, methods for sorting information in a list is called the Bubble Sort. - **commen,** - **eary,** - **less efficient** - **How does Bubble Sort method work?** - Bubble Sort repeatedly compares side by side items in a list and swaps them if they are in the wrong order. This is repeated until no additional swaps are needed. **Example** - Here is an example of an array that we would like to sort in numerical order. - `8 4 6 3` - The bubble sort algorithm compares adjacent items from left to right. - Since we want to sort numerically, we want to check if the number on the right is greater than the number on the left. The program would check: - Is 8>4? - Since 8 is greater than 4, the program would swap the two numbers, making the new list appear as so: - `4 8 6 3` - The program would then keep checking the numbers, until it reaches the last item. - Is 8>6? Yes. Swap them! - Is 8>3? Yes. Swap them! - After the first iteration of the sort, the list would appear as follows: - `4 6 3 8` - At this point, the last number in the array will be the highest, but the rest of the array might not yet be sorted. - The algorithm will continue to compare values (except for the last one) until it has been sorted. ## Method - **When will a method run?** - A method will only run when it is called. - Within the construct of a method, you can pass data, which are referred to as parameters into a method. - They perform "actions" and they are commonly known as functions. - **What are parameters?** - Parameters. - **How do we create a Method?** - A method must be declared within the construct of a class. - It must be defined with a name followed by (). - Java has some pre-defined methods `System.out.println()` - **Example_Create your own method:** - `public class MyClass {` - `static void myMethod() { // method creation with myMethod being the name` - `// code to be executed` - `}` - `}` - **Example_explained:** - **What does static mean?** - 1. `static` means that the method belongs to the MyClass class and not an object of the MyClass class. - 2. `void` means that this method does not have a return value. - You will learn more about return values later in this chapter. - **What does void mean?** - **How do I call a method?** - To call a method, write the method's name followed by () and ; **Example:** - `public class MyClass {` - `static void myMethod() {` - `System.out.println("I just got executed!");` - `}` - `}` - `public static void main(String[] args) {` - `myMethod();` - `}` - `}` ## What are method parameters? - Method Parameters are information which can be passed into

Use Quizgecko on...
Browser
Browser