Introduction To Java and Object-Oriented Programming
Introduction To Java and Object-Oriented Programming
University of Pennsylvania
by Ahmad Nassar
Introduction to Java and Object-Oriented Programming
University of Pennsylvania
Course Introduction:
In this course you will learn:
a. Advanced ways of storing and manipulating different kinds of data
structures.
b. Java inheritance, including access modifiers and overriding methods.
c. Abstract Classes.
d. Read and Write to Files.
e. Use regular expression to parsing text.
f. Leveraging complex data structures like collections and maps.
g. Strategies for catching errors and debugging code.
h. Overview of Eclipse’s debugging tool.
Introduction to Java:
According to the TIOBE index, Java is the third most popular programming
language. Java’s syntax is verbose, explicit and strict. Java is also compiled, (while
Python, for example, is interpreted), allowing Java to run much faster and more
efficiently. It also allows the Java code to be inspected for different kinds of errors,
including syntax errors, type errors, and non-existing functions.
Compiled languages in general have many advantages over interpreted languages.
When your code is compiled, it’s optimized under the hood. Since your program
will be inspected for errors, many kinds of potential bugs will be caught early (e.g.,
using the same variable name twice). When Java is compiled, it’s converted to
binary code (or Java bytecode), allowing Java programs to be “portable” and run
on different machines and operating systems. Your program will not run if it is not
compiled! The IDE you will be using for Java development, Eclipse, will compile
the code for me on the fly as you save your work. It will also help me fix many
potential problems in your code.
you will only need a single package (the default “no” package) and only one or
very few classes. As Java is an object-oriented language, you will need to create at
least one class to write a Java program.
Java uses curly brace {} to surround code blocks. For purposes of style, the
opening brace should go at the end of a line, not on a line by itself.
You can also declare variables WITHOUT initial values, for instance:
double distance;
String color;
distance = 2.3;
color = “Red”.
It is common to use cameCase to name variables.
Strings:
There is a difference between a char (a single character) and a String (a character
string). To define a String, use double quotes. Whereas to define a char, you must
use single quotes. Here’s how:
String firstName = “Ahmad”;
char firstLetter = ‘A’;
You can concatenate Strings using the “+” operator:
Introduction to Java and Object-Oriented Programming
University of Pennsylvania
Printing:
There are two methods you can use for printing
//This prints something and ends the line:
System.out.println(something);
//This prints something and doesn’t end the line (next thing you print will
appear on the same line):
‘while’ Loops:
while loops in Java have a similar syntax to while loops in C#. Here is a simple
while loop that iterates 10 times:
Int I = 0;
while (i < 10) {
//do stuff here every time loop happens
i++; //manually increment 1
}
//i is initially set to 0
//i must be less than 10 in order to enter the loop each time
//code in the loop manually increment i by 1 at the end of each loop
‘for’ Loops:
for loops in Java have a similar syntax to for loops in C#. A for loop has 3 parts:
Setting the initial value
The condition for entering the loop
The change in the loop variable that happens at the end of each loop
Here is a for loop that iterates 10 times:
Introduction to Java and Object-Oriented Programming
University of Pennsylvania
Getting Input:
To get input in Java, we need to first import the Scanner class, this is how:
import java.util.Scanner;
Then create a scanner and assign it to variable, this is how:
Scanner scan = new Scanner(System.in);
Above, the name of the scanner is scan, new Scanner(…) tells Java to make a new
one, while System.in tells Java that the scanner is to take input from the keyboard.
Once done creating a scan, you can get input using the following method:
int myNumber = scan.nextInt(); //reads the next int
String myString = scan.next(); //reads the next String
String myLine = scan.NextLine(); //reads the next line as String
You should always close your scan using scan.close().
Comments:
There are two methods of writing comments in a Java program:
// Single line comment using double slashes
/* block comments
* either write forward slash then star at the comment’s start & end
*/ or write a forward slash and star, and then hit Enter and write
Javadocs:
Javadocs (Java documentation) are added before the definition of a variable,
method, or class. As a shortcut, you can type /** and then hit Enter to start writing,
it will add a Javadoc block and you can fill in the rest.
Introduction to Java and Object-Oriented Programming
University of Pennsylvania
When adding a Javadoc for a method, you should write a short description of what
the method does and briefly explain what parameters are used for and what the
return type is, if it has one, e.g.:
/**
* Returns the sum of two given numbers
* @param firstNum First value to add
* @param secondNum Second value to add
* @return Sum of values
public int getSum(int firstNum, int secondNum) {
return firstNum + secondNum
}
In the Javadoc above, we describe the method as returning the sum of two given
numbers. The first parameter (preceded by the @param) is “firstNum”, and is
described as the first value to add. The second parameter (also preceded by the
@param) is “secondNum”, and is described as the first value to add. Finally, as the
method returns a value, the Javadoc includes a return tag (@return), and describes
the return value as the sum of the two values.
Math Operators:
The + operator is used for addition.
The - operator is used for subtraction.
The * operator is used for multiplication.
The / operator is used for division.
The % is the modulus operator (it returns the remainder).
To raise a number x to the power b, use Math.Pow(x, b). Even if z was an
int, Math.Pow always returns a double.
int x = 7;
int y = 3;
int z = 9;
int a = 2;
int sum1 = x + y; //sum1 is 10
int diff1 = z – x; // diff1 is 2
int prod1 = y * x; //prod1 is 35
int div1 = z / y; //div1 is 3
int mod1 = x % y; //mod1 is 1
int pow1 = Math.Pow(z, a); //pow1 is 81
Introduction to Java and Object-Oriented Programming
University of Pennsylvania
When adding, subtracting, multiplying, or dividing two ints, the result will
be an int. (in case of multiplying, the remainder is dropped).
When adding, subtracting, multiplying, or dividing an int and a double, the
result will be a double.
When adding, subtracting, multiplying, or dividing two doubles, the result
will be a double.
Casting Data:
Int and to String conversion:
There are multiple ways to convert an int or a double variable to a String variable:
You can use Integer.toString(int) with int variables, and Double.toString(double)
with double variables, for example:
int num1 = 9;
double num2 = 9.41;
String str1 = Integer.toString(num1); //str1 is “9”
String str2 = Double.toString(num2); //str2 is “9.41”
Alternatively, you can use String.valueOf(int) and String.valueOf(double), for
example:
int num = 0;
String str = String.valueOf(num); //str is “0”
String to int or double conversion:
To convert a String variable to an int or a double, use Integer.parseInt(String) and
Double.parseDouble(String):
String str = “3”;
int num1 = Integer.parseInt(str); //num1 is 3
double x = Double.parseDouble(str); //x is 3.0
Char Operations:
To get a specific char in a String x by index, use x.charAt(int), for example:
String str = “sup”;
char firstChar = str.charAt(0); //firstChar is “s”
To convert a String x to an array of chars, use x.toCharArray(), for example:
String myString = “Hello”;
Introduction to Java and Object-Oriented Programming
University of Pennsylvania
String Operations:
When concatenating two Strings, the result type is String.
When concatenating a String and a char, the result type is String.
When concatenating a String and an int, the result type is String.
Introduction to Java and Object-Oriented Programming
University of Pennsylvania
Classes:
Everything in Java is object-oriented and class-based, this means you have to
create at least one class to write a Java program. A class describes an object, it’s
like a template for a new kind of object. When you define a class, you’re defining a
new data type. To use the object, you create an instance of the class.
A class include:
Fields (instance variables): Holds the data for each object.
Constructors: describes how to create a new object instance of the class.
Methods: describes the actions the object can perform.
Introduction to Java and Object-Oriented Programming
University of Pennsylvania
Defining a class:
The simple syntax for defining a sample class is:
public class ClassName {
// The fields (instance variables) of the object
// The constructors for creating the object
// The methods for communicating with the object
// These can be in any order
}
public is an access modifier that defines the visibility of the class. public
means that any other program in the Java project can use the class (i.e., create
instances or call methods).