Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
26 views

Introduction To Java and Object-Oriented Programming

This document provides an introduction to Java and object-oriented programming through a university course. It covers topics like data structures, inheritance, abstract classes, files, regular expressions, collections, error handling, Eclipse debugging tools, and more. The document also provides examples of basic Java concepts like variables, data types, strings, printing, loops, user input, comments, and math operators.

Uploaded by

ahmadnassar137
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

Introduction To Java and Object-Oriented Programming

This document provides an introduction to Java and object-oriented programming through a university course. It covers topics like data structures, inheritance, abstract classes, files, regular expressions, collections, error handling, Eclipse debugging tools, and more. The document also provides examples of basic Java concepts like variables, data types, strings, printing, loops, user input, comments, and math operators.

Uploaded by

ahmadnassar137
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

Introduction to Java and Object-Oriented Programming

University of Pennsylvania

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.

Eclipse and Java:


Eclipse stores and manages projects in a workspace. When you use Eclipse to
create a project (a single “program”), it creates a directory with that name in your
workspace. Within the project, you create an optional package (a sub-directory).
Finally, withing the package, you create a class (a file). For the simplest program,
Introduction to Java and Object-Oriented Programming
University of Pennsylvania

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.

Introductory Java Program:


//Optional package declaration
package myPackage; //Should begin with a lowercase letter
//Class declaration
public class MyClass { //Should begin with a capital letter
//The Java file will be named (and saved in) ‘my Package/MyClass.java’
//Main method – the starting point of any Java program
//In Java, the name “main” is special and reserved for the main
method
public static void main(String[] args) {
System.out.println(“Hello World”); //Prints ‘Hello World’
}
}
 At the top, there is an optional package declaration. It should begin with a
lowercase and use camel case (each word in the middle of the phrase begins
with an uppercase).
 Then we have the class declaration, it should also begin with a lowercase
and use camel case.
 The Java file will be named and saved in (‘myPackage/MyClass.java’).
 Inside of the class definition, we have the Main method, the starting point of
any Java program. In Java, the name “Main” is special, and reserves for the
main method. It serves as the entering point to the program.

General Rules in Java:


 Individual statements end with a semicolon, always.
 New lines don’t mean anything. You could have an entire program in a
single line.
 Indentation doesn’t matter, but it’s recommended that you don’t stop
indenting. In Eclipse, you could use Ctrl + Shift + F shortcut to fix the
format of your code. Using Ctrl + A will select all of the code, you could
then use Ctrl + I to fix the indentation.
Introduction to Java and Object-Oriented Programming
University of Pennsylvania

 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.

Variables and Data Types:


Some primitive (simple) data types include:
 int: Integer.
 float: Floating point (decimal)
 boolean: true/false
 char: Single character
 double: Large and precise floating point
 byte, short, or long: Various integer sizes (8, 16, and 64 bits)
Another type is “string”, which is an object (not a primitive). It’s used to store a
character string.
You can declare variables WITH initial values, for instance:
int count = 0;
String firstName = “Brandon”;

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

String fullName = “Ahmad ” + “Nassar”; // fullName = “Ahmad Nassar”


Anything concatenated with a String is automatically converted to a String, for
example:
String firstName = “There are ” + appleCount + “ apples and ” +
orangeCount + “ oranges.”;

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

for (int i = 0; i < 10; i++ {


//do stuff here every time loop happens
}
//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

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

Char[] arrayOfChars = myString.toCharArray();


//arrayOfChars contains ‘H’, ‘e’, ‘l’, ‘l’, ‘o’
 To check whether a specified char value is a letter, use
Character.isLetter(char), for example:
boolean isLetter1 = Character.isLetter(‘q’); //isLetter1 is true
boolean isLetter2 = Character.isLetter(‘)’); //isLetter2 is
false
 To check whether a specified char value is an uppercase, use
Character.isUppercase(char), for example:
boolean isUppercase = Character.isUppercase(‘e’);
//isUppercase is flase
 Similarly, to check whether a specified char value is a lowercase, use
Character.isLowercase(char), for example:
boolean isLowercase = Character.isLowercase(‘o’);
//isLowercase is true
 To convert a character to uppercase, use Character.toUppercase(char), for
example:
char myChar = Character.toUppercase(‘j’); //myChar is ‘J’
 Similarly, to convert a character to lowercase, use
Character.toLowercase(char), for example:
char myChar = Character.toLowercase(‘f’); //myChar is ‘F’
 In Java, you can compare characters like you compare numbers using ==, <,
and >, for example:
char myChar1 = ‘s’;
char myChar2 = ‘t’;
boolean comparison = myChar1 < myChar2;
//comparison is true

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

String myString = “Hello”;


int myInt = 8;
char myChar = ‘!’;
String phrase = myString + myChar + myInt;
//phrase is “Hello!8” of type String
 To convert a String x to uppercase, use x.toUppercase()
 To convert a String x to lowercase, use x.toLowercase()
String myName = “Ahmad” + “ ” + “Nassar”;
String myNameUpper = myName.toUppercase();
String myNameLower = myName.toLowercase();
/* myName is “Ahmad Nassar”
* myNameUpper is “AHMAD NASSAR”
*/myNameLower is “ahmad nassar”

Primitive and Objects:


There are 8 primitive types in Java: boolean, byte, char, short, int, long, float and
double. Such types serve only one purpose: containing pure, simple values of a
kind. We can use (Object) to cast a primitive data type to its wrapper class (e.g. int
to Integer, double to Double). A wrapper class is a class whose object wraps or
contains a primitive data type.
You can get the class (type) of an object variable x using x.getClass(). Since this
method only works with objects, we need to use (Object)y.getClass() to get the
data type of a primitive value y.

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).

You might also like