
Java Programming Essentials: Classes, Objects, and Data Types
"Explore the fundamentals of Java programming including classes, objects, reserved words, data types, and variable declaration. Learn about the key concepts needed to kickstart your Java programming journey."
Download Presentation

Please find below an Image/Link to download the presentation.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.
You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.
E N D
Presentation Transcript
What is Java? What is Java? Java is a programming language Created by Sun Microsystems Often used for web programming Initially marketed as a web development system Java is not only for web programming General purpose programming language Very similar to C++ simplified! By Sara Almudauh
Java Program! Java Program! class HiThere { /** * This is the entry point for an application. * @param astrArgs the command line arguments. */ public static void main(String[] astrArgs) { // Starting of the main method System.out.println("Hello World!"); } // main() } // end class HiThere By Sara Almudauh
Reserved words & Reserved words & Identifiers Identifiers class HiThere { public static void main(String[] astrArgs) { System.out.println("Hello World!"); } // main() } // end class HiThere Reserved words or keywords are part of the language class used to define a class public access keyword - public, private, protected and default static type related to belonging void special return type Java is case sensitive By Sara Almudauh
Data Type The data type defines what kinds of values a space memory is allowed to store. All values stored in the same space memory should be of the same data type. All constants and variables used in a Java program must be defined prior to their use in the program. 5
Primitive Data Types Size (bits) Type Range Description boolean true, false Stores a value that is either true or false. Stores a single 16-bit Unicode character. Stores an integer. char 16 0 to 65535 byte 8 -128 to +127 short 16 -32768 to +32767 Stores an integer. int 32 bits -2,147,483,648 to +2,147,483,647 -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807 accurate to 8 significant digits Stores an integer. long 64 bits Stores an integer. float 32 bits Stores a single-precision floating point number. Stores a double-precision floating point number. double 64 bits accurate to 16 significant digits 6
Variable/Constant Declaration When the declaration is made, memory space is allocated to store the values of the declared variable or constant. The declaration of a variable means allocating a space memory which state (value) may change. The declaration of a constant means allocating a space memory which state (value) cannot change. 7
Variable Declaration A variable may be declared: With initial value. Without initial value Variable declaration with initial value; dataType variableIdentifier = literal | expression; double avg = 0.0; int i = 1; int x =5, y = 7, z = (x+y)*3; Variable declaration without initial value; dataType variableIdentifier; double avg; int i; 8
More declaration examples String declaration with initial value: String word="Apple"; without initial value: String word; char declaration with initial value: char symbol ='*'; without initial value: char symbol; Boolean declaration: with initial value: boolean flag=false; boolean valid=true; without initial value: boolean flag; 9
Arithmetic Arithmetic Arithmetic Unary Operators int iNum = 7; += addition iNum += 2; iNum -= 2; iNum *= 2; iNum /= 2; iNum %= 2; 9 5 1 4 3 1 -= subtract *= multiply /= divide %= remainder By Sara Almudauh
Operators Operators Equality and Relational Operators int iNum = 7; == equal to if (iNum == 1) { != not equal to if (iNum != 1) { > greater than if (iNum > 1) { >= greater than or equal to if (iNum >= 1){ < less than 1) { if (iNum < <= less than or equal if (iNum == 1) { By Sara Almudauh
Decision Making Decision Making Conditions result in boolean values Condition can be A boolean Expressions that result in a boolean Combination of Rational Operators and Method that return boolean By Sara Almudauh
Decision Making Decision Making Rational Operators == is equal to != is not equal to > is bigger than >= is bigger or equal to < is smaller than <= is smaller or equal to || logical OR && logical AND counterA == counterB counterA != counterB counterA > counterB counterA >= counterB counterA < counterB counterA <= counterB (counterA > counterB) || (counterA < counterB) (counterA > counterB) && (counterA < counterB) By Sara Almudauh
Decision Making Decision Making switch Statement A way to simulate multiple if statements int iCounter = 0; // initialisation int iValue; ... if (iCounter == 0) { iValue = -1; } else if (iCounter == 1) { iValue = -2; } else if (iCounter == 2) { iValue = -3; } else { iValue = -4; } int iCounter = 0; // initialisation int iValue; ... switch (iCounter) { case 0: iValue = -1; break; case 1: iValue = -2; break; case 2: iValue = -3; break; default: iValue = -4; } // end switch By Sara Almudauh
Two-Way Selection Example 4-13 if (hours > 40.0) wages = 40.0 + rate * hours; else wages = hours * rate;
Switch Structures Expression is also known as selector. Expression can be an identifier. Value can only be integral. switch (expression) { casevalue1: statements1 break; casevalue2: statements2 break; ... case value n: statements n break; default: statements }
Control Structures Control Structures Loops while do for Loop Control break continue By Sara Almudauh
Control Structures Control Structures Initialisation - Condition - Increment int iIndex = 0; // initialise int iIndex = 0; // initialise for (int iIndex = 0; iIndex < 4; iIndex += 2) { System.out.println(iIn dex); } // end for System.out.println(iIndex ); ... do { while (iIndex < 4) { System.out.println(iIn dex); iIndex += 2; } // end while System.out.println(iIndex ); ... System.out.println(iInd ex); iIndex += 2; } while (iIndex < 4); System.out.println(iIndex); ... By Sara Almudauh
Arrays Arrays Group of data items All items of the same type, e.g. int Items accessed by integer indexes Starting index with zero Last index is one less than the length Of pre-determinate size The length of an array is the number of items it contains The length is fixed at creation time By Sara Almudauh
Arrays Arrays double[] myList = new double[10]; myList reference 5.6 myList[0] myList[1] 4.5 3.3 Array reference variable myList[2] 13.2 myList[3] 4 myList[4] Array element at index 5 34.33 myList[5] Element value 34 myList[6] 45.45 myList[7] 99.993 myList[8] 11123 myList[9] By Sara Almudauh
Declaring Array Variables Declaring Array Variables Arrays are variables Arrays must be declared <type>[] <identifier>; or <type> <identifier>[]; Examples: String[] astrCityNames; or String astrCityNames[]; int[] aiAmounts; or int aiAmounts[]; double myList[]; By Sara Almudauh
Creating Arrays Creating Arrays arrayRefVar = new datatype[arraySize]; Example: myList = new double[10]; myList[0] references the first element in the array. myList[9] references the last element in the array. By Sara Almudauh
Declaring and Creating Declaring and Creating in One Step in One Step datatype[] arrayRefVar = new datatype[arraySize]; double[] myList = new double[10]; datatype arrayRefVar[] = new datatype[arraySize]; double myList[] = new double[10]; By Sara Almudauh
Example Example double[] myList = {1.9, 2.9, 3.4, 3.5}; This is equivalent to the following statements: double[] myList = new double[4]; myList[0] = 1.9; myList[1] = 2.9; myList[2] = 3.4; myList[3] = 3.5; By Sara Almudauh
Initializing arrays with input values Initializing arrays with input values Scanner input = new Scanner(System.in); System.out.print("Enter " + myList.length + " values: "); for (int i = 0; i < myList.length; i++) myList[i] = input.nextDouble(); By Sara Almudauh
Object Software objects are modeled after real-world objects in that they, too, have state and behavior. A software object maintains its state in variables and implements its behavior with methods. An object combines data and operations on the data into a single unit.
Object An approach to the solution of problems in which all computations are performed in the context of objects. The objects are instances of classes, which: are data abstractions contain procedural abstractions that operate on the objects A running program can be seen as a collection of objects collaborating to perform a given task
Object vs. Class A class could be considered as a set of objects having the same characteristics and behavior. An object is an instance of a class. Introduction to OOP Dr. S. GANNOUNI & Dr. A. TOUIR Page 28
Classes User-defined data types Contain Variables Often called properties , members or attribute of the class Contain blocks of program code methods Instance variables and methods This is the default Each instance of the class has their own copy Class variables and methods Declared using the reserved word static Only one copy for all instances of the class
Object vs. Class A class could be considered as a set of objects having the same characteristics and behavior. An object is an instance of a class.
Declaring a Class with Java ClassName - att1: dataType1 - - atti: dataTypei Attributes + m1( ): dataType1 + ... + mj( ): dataTypej Methods (Services) public class ClassName { // Attributes // Methods (services) } Introduction to OOP Dr. S. GANNOUNI & Dr. A. TOUIR Page 31
Declaring Attributes With Java <modifiers> <data type> <attribute name> ; Modifiers Data Type Name public String studentName ; Introduction to OOP Dr. S. GANNOUNI & Dr. A. TOUIR Page 32
Example of a Class Declaration with Java Course +studentName : string +courseCode : string public class Course { // Attributes public String studentName; public String courseCode ; // No method Members } Introduction to OOP Dr. S. GANNOUNI & Dr. A. TOUIR Page 33
Objects An instance of a class Created when the class is instantiated with the new reserved word Generally classes must be instantiated before they can be used For example class Stuff is instantiated as follows: Stuff myStuff = new Stuff(); The exception Static variables and methods may be used without instantiating a class Naming convention class names should start with an uppercase letter
Object Creation A. The instance variable is allocated in memory. crs Object: Course B. The object is created A studentName courseCode B Course crs; C. The reference of the object created in B is assigned to the variable. crs crs new Course( ) crs = ; Object: Course studentName courseCode Code State of Memory Introduction to OOP Dr. S. GANNOUNI & Dr. A. TOUIR Page 35
Instance VS. Primitive Variables Primitive variables hold values of primitive data types. Instance variables hold references of objects: the location (memory address) of objects in memory. Introduction to OOP Dr. S. GANNOUNI & Dr. A. TOUIR Page 36
Assigning Objects References to the same Instance Variable crs Course Course A A. The variable is allocated in memory. B Course crs; crs = new Course( ); crs = new Course( ); B. The reference to the new object is assigned to crs. C. The reference to another object overwrites the reference in crs. State of Memory Code Introduction to OOP Dr. S. GANNOUNI & Dr. A. TOUIR Page 37
Assigning an Object Reference From One Variable to Another crs1 crs2 A Course B A. Variables are allocated in memory. Course crs1, crs2, crs1 = new Course( ); B. The reference to the new object is assigned to crs1. crs2 = crs1; C C. The reference in crs1 is assigned to crs2. State of Memory Code Introduction to OOP Dr. S. GANNOUNI & Dr. A. TOUIR Page 38
Assigning an Object Reference From One Variable to Another crs1 crs2 A. Variables are allocated in memory. B. Variables are assigned references of objects. A C. The reference in crs2 is assigned to crs1. Course Course B Course crs1, crs2, crs1 = new Course( ); crs2 = new Course( ); crs1 crs1 = crs2; Course crs2 Course C Introduction to OOP Dr. S. GANNOUNI & Dr. A. TOUIR Page 39
Accessing Instance Attributes In order to access attributes of a given object: use the dot (.) operator with the object reference (instance variable) to have access to attributes values of a specific object. instanceVariableName.attributeName course1.StudentName= Sara AlKebir ; course2.StudentName= Maha AlSaad ; course2 course1 Object: Course Object: Course studentName Fahd AlAmri studentName Majed AlKebir courseCode courseCode Introduction to OOP Dr. S. GANNOUNI & Dr. A. TOUIR Page 40
class Course { Course // Instance attributes public String studentName; public String courseCode ; +studentName : string +courseCode : string } public class CourseRegistration { public static void main(String[] args) { Course course1, course2; //Create and assign values to course1 course1 = new Course( ); course1.courseCode= new String( CSC112 ); course1.studentName= new String( Sara AlKebir ); //Create and assign values to course2 course2 = new Course( ); course2.courseCode= new String( CSC107 ); course2.studentName= new String( Maha AlSaad ); course1.courseCode); System.out.println(course2.studentName + " has the course + course2.courseCode); } } CourseRegistration +main() System.out.println(course1.studentName+ " has the course + Introduction to OOP Dr. S. GANNOUNI & Dr. A. TOUIR Page 41
Practical hint Class Course will not execute by itself It does not have method main CourseRegistration uses the classCourse. CourseRegistration, which has method main, creates instances of the class Course and uses them. uses CourseRegistration Course +studentName : string +courseCode : string +main() Introduction to OOP Dr. S. GANNOUNI & Dr. A. TOUIR Page 42
Class and Objects UML Graphical notation for classes Circle radius: double findArea(): double UML Graphical notation for fields UML Graphical notation for methods new Circle() new Circle() UML Graphical notation for objects circle1: Circle circlen: Circle radius = 2 ... radius = 5
Constructors Constructors are special methods that are executed automatically Executed once when the class is instantiated Constructors have the same name as the class They have no return value, but must not be declared void class Stuff { Stuff() { System.out.println( This is the constructor ); } }
Use of constructors Constructors are run once when a class is instantiated useful for initialising the object - any code that needs to be run to set things up in memory useful for passing data into the object from the calling program in graphical programs the user interface is usually defined in the constructor of a window object the fact that they are only run once is useful - this is a good place for any code that must be run only once
Constructors Constructors are a special kind of methods that are invoked to construct objects. Circle() { } Circle(double newRadius) { radius = newRadius; } 46
Default Constructor A class may be declared without constructors. In this case, a no-arg constructor with an empty body is implicitly declared in the class. This constructor, called a default constructor, is provided automatically only if no constructors are explicitly declared in the class. 47
Modifiers static Public+ Private - Protected #
Static It used to define class attributes and methods. Class attributes (and methods): live in the class can also be manipulated without creating an instance of the class. are shared by all objects of the class. do not belong to objects states. <modifiers> <data type> <attribute name> ; Modifiers Data Type Name public static int studentNumber ; Introduction to OOP Dr. S. GANNOUNI & Dr. A. TOUIR Page 49
Class Attributes Access Class attributes (and methods) can also be manipulated without creating an instance of the class. <class name>.<attribute name> Class Name Attribute Name Course.studentNumber = 0 ; Introduction to OOP Dr. S. GANNOUNI & Dr. A. TOUIR Page 50