Docsity

Java Programming Language Notes, Lecture notes of Object Oriented Programming

Toggle sidebar
bg1
1
ICS 2201 Object Oriented Programming II- JAVA
Course Description/Outline
In-depth study of Java. Development of large efficient and reusable systems: encapsulation,
templates, references, constructors and distructors, operator overloading, memory management,
exception handling , std templates, library, programming by contracts, configuration management,
documentation and testing.
Java Programming Language Notes
What is Java?
Java is a popular programming language, created in 1995.
It is owned by Oracle, and more than 3 billion devices run Java.
It is used for:
• Mobile applications (specially Android apps)
• Desktop applications
• Web applications
• Web servers and application servers
• Games
• Database connection
Why Use Java?
• Java works on different platforms (Windows, Mac, Linux, Raspberry Pi,
etc.)
• It is one of the most popular programming language in the world
• It is easy to learn and simple to use
• It is open-source and free
• It is secure, fast and powerful
• It has a huge community support (tens of millions of developers)
• Java is an objectoriented language which gives a clear structure to
programs and allows code to be reused, lowering development costs
it is possible to write Java in an Integrated Development Environment, such as
IntelliJ IDEA( recommended for this course), Netbeans or Eclipse, which are
particularly useful when managing larger collections of Java files
example
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a

Partial preview of the text

Download Java Programming Language Notes and more Lecture notes Object Oriented Programming in PDF only on Docsity!

ICS 2201 Object Oriented Programming II- JAVA

Course Description/Outline In-depth study of Java. Development of large efficient and reusable systems: encapsulation, templates, references, constructors and distructors, operator overloading, memory management, exception handling , std templates, library, programming by contracts, configuration management, documentation and testing. Java Programming Language Notes

What is Java?

Java is a popular programming language, created in 1995. It is owned by Oracle, and more than 3 billion devices run Java. It is used for:

  • Mobile applications (specially Android apps)
  • Desktop applications
  • Web applications
  • Web servers and application servers
  • Games
  • Database connection

Why Use Java?

  • Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.)
  • It is one of the most popular programming language in the world
  • It is easy to learn and simple to use
  • It is open-source and free
  • It is secure, fast and powerful
  • It has a huge community support (tens of millions of developers)
  • Java is an objectoriented language which gives a clear structure to programs and allows code to be reused, lowering development costs it is possible to write Java in an Integrated Development Environment, such as IntelliJ IDEA( recommended for this course), Netbeans or Eclipse, which are particularly useful when managing larger collections of Java files example

public class Main { public static void main(String[] args) { System.out.println("Hello World"); } }

  • Save the code in Notepad as "Main.java". Open Command Prompt (cmd.exe), navigate to the directory where you saved your file, and type "javac Main.java":
  • C:\Users>javac Main.java
  • his will compile your code. If there are no errors in the code, the command prompt will take you to the next line. Now, type "java Main" to run the file
  • C:\Users>java Main
  • Every line of code that runs in Java must be inside a class. In our example, we named the class Main. A class should always start with an uppercase first letter.
  • Note: Java is case-sensitive: "MyClass" and "myclass" has different meaning.
  • The name of the java file must match the class name. When saving the file, save it using the class name and add ".java" to the end of the filename.

The main Method

The main() method is required and you will see it in every Java program: public static void main (String[] args)

  • Any code inside the main() method will be executed.
  • For now, just remember that every Java program has a class name which must match the filename, and that every program must contain the main() method.

System.out.println()

Inside the main() method, we can use the println() method to print a line of text to the screen: public static void main(String[] args) {

Final Variables

However, you can add the final keyword if you don't want others (or yourself) to overwrite existing values (this will declare the variable as "final" or "constant", which means unchangeable and read-only): final int myNum = 15 ; myNum = 20 ; // will generate an error: cannot assign a value to a final variable nt myNum = 5 ; float myFloatNum = 5.99f; char myLetter = 'D'; boolean myBool = true; String myText = "Hello";

Display Variables

The println() method is often used to display variables. To combine both text and a variable, use the + character: String name = "John"; System.out.println("Hello " + name);

Java Identifiers

All Java variables must be identified with unique names. These unique names are called identifiers.

Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume). The general rules for constructing names for variables (unique identifiers) are:

  • Names can contain letters, digits, underscores, and dollar signs
  • Names must begin with a letter
  • Names should start with a lowercase letter and it cannot contain whitespace
  • Names can also begin with $ and _
  • Names are case sensitive ("myVar" and "myvar" are different variables)
  • Reserved words (like Java keywords, such as int or boolean) cannot be used as names

Java Data Types

Data types are divided into two groups:

  • Primitive data types - includes byte, short, int, long, float, double, boolean and char
  • Non-primitive data types - such as String, Arrays and Classes

Primitive Data Types

A primitive data type specifies the size and type of variable values, and it has no additional methods. There are eight primitive data types in Java:

Booleans

A boolean data type is declared with the boolean keyword and can only take the values true or false: boolean isJavaFun = true; boolean isFishTasty = false; System.out.println(isJavaFun); // Outputs true System.out.println(isFishTasty); // Outputs false

Characters

The char data type is used to store a single character. The character must be surrounded by single quotes, like 'A' or 'c': char myGrade = 'B'; System.out.println(myGrade);

Strings

The String data type is used to store a sequence of characters (text). String values must be surrounded by double quotes: String greeting = "Hello World"; System.out.println(greeting);

Non-Primitive Data Types

Non-primitive data types are called reference types because they refer to objects. The main difference between primitive and non-primitive data types are:

  • Primitive types are predefined (already defined) in Java. Non-primitive types are created by the programmer and is not defined by Java (except for String).
  • Non-primitive types can be used to call methods to perform certain operations, while primitive types cannot.
  • A primitive type has always a value, while non-primitive types can be null.
  • A primitive type starts with a lowercase letter, while non-primitive types starts with an uppercase letter.
  • The size of a primitive type depends on the data type, while non-primitive types have all the same size. Examples of non-primitive types are Strings, Arrays, Classes, Interface, etc.

Java Type Casting

Type casting is when you assign a value of one primitive data type to another type. In Java, there are two types of casting:

  • Widening Casting (automatically) - converting a smaller type to a larger type size byte - > short - > char - > int - > long - > float - > double
  • Narrowing Casting (manually) - converting a larger type to a smaller size type double - > float - > long - > int - > char - > short - > byte Java divides the operators into the following groups:
  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Logical operators
  • Bitwise operators

Double

The double data type can store fractional numbers from 1.7e−308 to 1.7e+308. Note that you should end the value with a "d": double myNum = 19.99d; System.out.println(myNum);

String Length

A String in Java is actually an object, which contain methods that can perform certain operations on strings. For example, the length of a string can be found with the length() method: String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; System.out.println("The length of the txt string is: " + txt.length()); There are many string methods available, for example toUpperCase() and toLowerCase(): String txt = "Hello World"; System.out.println(txt.toUpperCase()); // Outputs "HELLO WORLD" System.out.println(txt.toLowerCase()); // Outputs "hello world"

Finding a Character in a String

The indexOf() method returns the index (the position) of the first occurrence of a specified text in a string (including whitespace): String txt = "Please locate where 'locate' occurs!"; System.out.println(txt.indexOf("locate")); // Outputs 7

String Concatenation

The + operator can be used between strings to combine them. This is called concatenation : String firstName = "John"; String lastName = "Doe"; System.out.println(firstName + " " + lastName); You can also use the concat() method to concatenate two strings: String firstName = "John "; String lastName = "Doe"; System.out.println(firstName.concat(lastName));

Special Characters

Because strings must be written within quotes, Java will misunderstand this string, and generate an error: String txt = "We are the so-called "Vikings" from the north."; The solution to avoid this problem, is to use the backslash escape character. The backslash () escape character turns special characters into string characters:

Boolean Expression

A Boolean expression is a Java expression that returns a Boolean value: true or false. You can use a comparison operator, such as the greater than (>) operator to find out if an expression (or a variable) is true:

Syntax

if ( condition ) { // block of code to be executed if the condition is true }

Syntax

if ( condition ) { // block of code to be executed if the condition is true } else { // block of code to be executed if the condition is false }

Syntax

if ( condition1 ) { // block of code to be executed if condition1 is true } else if ( condition2 ) { // block of code to be executed if the condition1 is false and condition2 is true } else { // block of code to be executed if the condition1 is false and condition2 is false }

Short Hand If...Else (Ternary Operator)

There is also a short-hand if else, which is known as the ternary operator because it consists of three operands. It can be used to replace multiple lines of code with a single line. It is often used to replace simple if else statements

Syntax

variable = (condition)? expressionTrue : expressionFalse;

Java Switch Statements

Use the switch statement to select one of many code blocks to be executed.

Syntax

switch( expression ) { case x: // code block break; case y: // code block break; default: // code block }

The break Keyword

When Java reaches a break keyword, it breaks out of the switch block. This will stop the execution of more code and case testing inside the block.

for (int i = 0 ; i < 5 ; i++) { System.out.println(i); }

For-Each Loop

There is also a " for-each " loop, which is used exclusively to loop through elements in an array :

Syntax

for ( type variableName : arrayName ) { // code block to be executed } String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; for (String i : cars) { System.out.println(i);

Java Arrays

Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value. To declare an array, define the variable type with square brackets : String[] cars;

Change an Array Element

To change the value of a specific element, refer to the index number:

Example

cars[ 0 ] = "Opel";

Example

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; cars[ 0 ] = "Opel"; System.out.println(cars[ 0 ]); // Now outputs Opel instead of Volvo

Array Length

To find out how many elements an array has, use the length property:

Example

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; System.out.println(cars.length); // Outputs 4

Loop Through an Array

You can loop through the array elements with the for loop, and use the length property to specify how many times the loop should run. The following example outputs all elements in the cars array:

Example

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; for (int i = 0 ; i < cars.length; i++) { System.out.println(cars[i]); }

methods, such as System.out.println(), but you can also create your own methods to perform certain actions: public class Main { static void myMethod() { // code to be executed } }

  • myMethod() is the name of the method
  • static means that the method belongs to the Main class and not an object of the Main class.
  • void means that this method does not have a return value
  • To call a method in Java, write the method's name followed by two parentheses () and a semicolon ;
  • Inside main, call the myMethod() method: public class Main { static void myMethod() { System.out.println("I just got executed!"); } public static void main(String[] args) { myMethod(); } } // Outputs "I just got executed!"

Parameters and Arguments

Information can be passed to methods as parameter. Parameters act as variables inside the method. Parameters are specified after the method name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma. The following example has a method that takes a String called fname as parameter. When the method is called, we pass along a first name, which is used inside the method to print the full name:

public class Main { static void myMethod(String fname) { System.out.println(fname + " Kamau"); } public static void main(String[] args) { myMethod("Liam"); } } // Liam Kamau When a parameter is passed to the method, it is called an argument. So, from the example above: fname is a parameter , while Lilian is an argument.

Multiple Parameters

You can have as many parameters as you like: public class Main { static void myMethod(String fname, int age) { System.out.println(fname + " is " + age); } public static void main(String[] args) { myMethod("John", 4 ); myMethod("Jenny", 8 ); myMethod("Auma", 21 ); }