0% found this document useful (0 votes)
7 views7 pages

Java Object-Oriented Programming Basics

The document discusses various mathematical operators, functions, and concepts related to object oriented programming in Java including arrays, methods, classes, and objects. Mathematical operators like addition, subtraction, multiplication, and modulus are covered. Functions such as random, round, touppercase, and tolowercase are also discussed.

Uploaded by

abu.boitech
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views7 pages

Java Object-Oriented Programming Basics

The document discusses various mathematical operators, functions, and concepts related to object oriented programming in Java including arrays, methods, classes, and objects. Mathematical operators like addition, subtraction, multiplication, and modulus are covered. Functions such as random, round, touppercase, and tolowercase are also discussed.

Uploaded by

abu.boitech
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

OBJECT ORIENTED PROGRAMMING IN JAVA.

MATHEMATICAL OPERATORS.
These operators are used to handle arithmetic expressions in a program. They are used as
discussed below.
Addition operator (+).
It is used to add two or more operands together. The operands could be the real values like 4 + 6,
or represented by variables like x + y. To output the results of the program, the output statement
could be written as, [Link] (“x + y =” + (x + y));
Subtraction operator (+).
It is used to subtract one operand from another, for example 6 – 4 or y – x. The output statement
of subtraction is written as, [Link] (“y – x =” + (y – x));
Multiplication operator (*)
It is used to multiply two or more operands that are assigned in the program or are supplied by
the user. To output the results of the program, the output statement could be written as,
[Link] (“x * y = ” + (x * y));
Division operator (/).
The division operator is used to divide a numerator operand by the denominator operand as 6/4
or x/y. To output the results of the program, the output statement could be written as,
[Link] (“x / y = ” + (x / y));
Modulus operator (%).
It is an operator that is used to return the remainder of the division of two operands, for example
5%2 =1, because 5/2 = 2 remainder 1. To output the results of the program, the output statement
could be written as, [Link] (“x % y =” + (x % y));
MATHEMATICAL FUNCTIONS.
Math. Pow()function.
It is a function that is used to return the power of a number, i.e. a base operand is raised with a
exponent operand. The function can be declared in the program as followed;
type pow( type x, type y); where type is the data type, x is the base number and y is the exponent.
For example suppose x = 2 and y = 3, thus int pow(int x, int y) =23 =8. The ouput of the above
program can be written as; [Link]("POW: " + i_a + " power " + i_b + ");
Math. Random ( ) function.
Random function is a function that generates any random numbers between 0.0 and 1.0. For
example a program to display any numbers at random could be written as;
[Link]("Some random numbers are: " + Math. Random ( )); this could output
anything like 0.123456789.
Math. Round ( ) function.
Round function is a function that Rounds off a functional parameter value by first adding 0.5 to it
and then returning the largest value that is less than or equal to that new value. Round function
can take different parameters as follows:
round( float x) - returns the closest float number to the argument x.
round( double x) - returns the closest long float number to the argument x.
CHARACTER AND STRING FUNCTIONS.
String Functions are functions that manipulate strings to behave in different forms. They include:
touppercase( ) function.
Toppercase function is a function that is used to convert all strings or characters to uppercase.
For example, suppose a string store = “check this case”, then
[Link]([Link]()); - will display “CHECK THIS CASE”
tolowercase( ) function.
tolowercase function is a function that is used to convert all strings or characters to lower case.
For example, suppose a string store = “CHECK THIS CASE”, then
[Link](store. toUpperCase()); - will display “check this case”
SUB STRINGS.
indexOf()function.
indexOf () function is use to return index of given sub string character values starting from 0,
upon which if it fails will return -1. It comprises of four types as discussed below.
int indexOf(int character) - returns position index for a given character value.
int indexOf(int character, int StartIndex) - returns index position of a given character value and
the index starting from.
int indexOf(String substr) – returns position index of given substring.
int indexOf(String substr, int StartIndex) - returns position index of a given substring and the
index starting from.
ASCII Characters and Strings.
Java supports all most types of characters and strings including that of American Standard Code
for Information Interchange. There are up to 128 characters supported by ASCII java e.g.? @ $
% 0 1 3 a c etc. To display all of these characters the program in the following format.
for (int n=1;i<=127;n++)
[Link]("Number: " + n + " Character = " +(char)n);
You can achieve file processing in Java by use of various classes. The main class used to handle
files is the File. The File class is among the [Link] libraries. You can use it by importing it to the
file. i.e.
import [Link];
For you to use a file you need to declare it first. A file is declared by use of one of its
constructors. The constructor takes the argument as a string, the file name or its path. The file
extension must be included. For example:
File fileStore = new File("[Link]");
FILE OBJECTS.
File object is a tool that is created so as to help in manipulation of a file. The manipulation will
include opening of the file for reading from and writing to. The file is opened for reading and
writing by use of a scanner. Therefore, in each instance a scanner is needed it must be created.
You can create the scanner as follows:
Scanner <name> = new Scanner(new File("<file name>"));
Scanner myscanner = new Scanner(new File("[Link]"));
File Methods.
Exists( ) method is used to find if the file exists an if it can be read. You can write a program to
determine the existence of the file as follows.
while ([Link]()) { [Link]("File successfully found! ");}
else { [Link]("File not found! Try again: ");}
Next Methods.
Methods that uses next determines the nature of the next input parameter from the scanner. They
include:
next( ) determines whether more parameters are remaining.
nextInt( ) determines whether the next parameter to be read is an integer.
nextdouble( ) determines whether the next parameter to be read is a double.
nextline( ) determines whether there are more lines remaining to be read.
Close( ) method.
Close( ) method is used to close an open file after it has outputted its contents e.g. [Link]();

ARRAYS.
Arrays are storage locations that store collection of data with similar data types. Array
declaration takes the format: type ArrayName[subscript]; eg int StoreInt[6];
Array sizes.
Arrays are of varying sizes. The determining factor of an array size are its data types and its
dimension. There are different dimensions of an array, as discussed below.
Single Dimensional Array.
Single dimensional array is an arra
int[][] board = new int[ROWS][COLS];
Looping In an Array.
To generate a set of data automatically in a pro y with only one subscript eg. int StoreInt[6];
Two-dimensional Array.
Two-dimensional array is an array with two subscripts. It is used to handle data that is in two
dimensions such as that of rows and columns. For example, an array of a table with 5 rows and 4
columns could be declared as follows:
int ROWS = 5, int COLS = 4;
gram through an array, looping statements are used. For example:
for ( i = 0 ; i < 10 ; i++ ){ // Print column j in row i
for ( j = 0 ; j < a[i]; j++ )
{ [Link]( a[i][j] + " " ); }
METHODS.
A method is a collection of statements that are grouped together to perform a given operation.
Method Header.
Method header is just a declaration of a method to be used in the program. Method header just
introduces the type, name and the scope where the method will be used i.e. whether public or
private. For example: public int Calc(int x, int y);
Method Calling.
After the method declaration, any statement or another function can call it. When a method is
called, arguments are supplied for it to act on them. After the method has acted on the arguments,
it returns them to the calling program. Illustration:
public int Calc(int x, int y) { int a = 4; int b = 6; int c = Calc(int x, int y)
[Link]("Result = " + c); }
Passing and Returning an Array to and from a Method.
Arrays can also be passed as arguments to a method, after which a a method will return the
results to the calling program. Illustration:
public int Average(int[] array ) { int total =0, int Avg = 0; for(int n=0; n < 10; n++) {total =
total + array[n];
Avg = total / 10; } return Avg;
SCOPE OF VARIABLES.
Local and Field variables.
Local variables are variables declared and used within a given method only. For example:
Int Calculate(int x, int y ) { int LocalVar1 , int LocalVar2; }
Field variables.
Field variables are variables declared and used all over in the general program. For example:
Public void main ( ) { int Field Var1 , int FieldVar2; }
CLASSES.
A class is a blueprint through which an object is derived from it. An object therefore is an
instance of a class.
Class Access Specifiers.
Access specifiers are class regulators that monitors the visibility of class members in the
program. They include public, private and protected.
Public Access Specifier declares class member data to be open and can be accessed by other
classes within the same program project.
Private Access specifier limit access of class member data only to the class that it was declared
in.
Protected Access Specifier limits and hide some of the class member data that carry sensitive
information.
Illustration:
Class Account{ public GetuserName( ); public GetPassword( ); private UserName;
protected Password; };
Accessor Method - Get( ).
Accessor Method is a function that adds functionality to a method by enabling it to obtain a
value. For example: getArea( );
Mutator Method – Set( ).
Mutator method adds functionality to a method by enabling it to change an existing parameter to
a new parameter. For example int setArea( );
INSTANTIATING OBJECTS
Object instantiation is creation of a new object from a class. The new key word is used to
instantiate an object. For example if there was a a class named shapes, then a real shape object
like rectangle will be generated as: Shape = new Rectangle( );
CONSTRUCTORS AND DESTRUCTORS.
Constructors are methods that brings a class into existence while destructors clears the classs
after it has accomplished its purpose in the program.
Constructors that are generated by automatically by the compiler are known as default
constructors. They use the same name as that of the class.
Copy constructors are constructors that are used to generate a copy of objects and that needs to
be reproduced more than once.
GUI PROGRAMMING.
GUI Programming is developing applications that in the Graphical User Interface platform. GUI
Programming facilitate such features as menus, files, icons and buttons.
Stage Class.
Stage class is a class library function with properties that are used to set the appearance of an
application. The stage class styles include decorated, undecorated, transparent and utility.
Pane Class.
Pane class exposes the derived class as public so that the users of the subclass are free to use
them.
Scene.
The Scene interface is a set of functions used to extract Java 3D scene graph information from a
file. It gives loaders of various file formats a common public interface.
STEPS IN CREATING A GUI APPLICATION.
1. Inserting a form.
2. Placing and arranging objects in the form.
3. Assigning properties to the form.
4. Writing codes to drive the objects.
5. Making forms to be functional.
6. Previewing forms.
[Link]( ).
[Link]( )method is used to start an application that has been build and is ready to
run. It takes the form: public static void main(String[] args) { launch(args);}
Start( ) Method.
Start( ) method is used to prepare the a process to be executed by a run( ) method. It takes the
format: public void start()
Handle()Method.
Handle method is used to get a reference to another Method.
How to Create A Line.

public class DrawLine2D extends JApplet { Graphics2D line = (Graphics2D);


[Link](new [Link](x, y, 200, 200));
How to Create A Circle.
public void DrawCircle(Graphics2D g, int x, int y, int r) { x = x-(r/2); y = y-(r/2); }
How to Create A Rectangle.
void drawPolygon(int x[], int y[], int numOfPoints)

Common questions

Powered by AI

String manipulation functions in Java, such as 'toUpperCase()' and 'toLowerCase()', change the case of strings. 'toUpperCase()' converts strings to uppercase, exemplified by converting 'check this case' to 'CHECK THIS CASE'. Conversely, 'toLowerCase()' changes strings to lowercase. Moreover, 'indexOf()' functions locate the first occurrence index of characters or substrings within a string, with variations allowing specifying starting index for the search .

Access specifiers in Java classes are crucial for defining the visibility and access level of class members, contributing significantly to encapsulation and data protection. The 'public' specifier allows class data to be accessed by any other class within the same project, enhancing interoperability. The 'private' specifier restricts access only to the class where the member is declared, helping to safeguard sensitive data. The 'protected' specifier provides a middle ground, where member data can be accessed within its package and by subclasses, enabling controlled inheritance. Together, these specifiers help in building secure and robust Java applications .

Constructors in Java are special methods that are invoked to instantiate objects from classes. They share the same name as their class and initialize object state. Default constructors are generated automatically by the compiler if no other constructor is present. Copy constructors help in creating a new object as a copy of another. On the other hand, destructors, though implicit in Java through garbage collection, are envisioned as cleanup operations after an object has served its purpose. Proper use of constructors and understanding the role of destructors is vital for robust resource management and object lifecycle control in Java applications .

Creating a GUI application in Java involves several steps. Initially, a form is inserted to serve as the application's visual interface. Objects are then placed and arranged on this form. Subsequently, properties are assigned to enhance functionality and appearance. Codes are written to drive these objects' interactions and behaviors, forming the business logic. Next, the form is made fully functional for user interaction. Finally, previewing the form helps ensure everything operates smoothly before deployment. The Stage class sets the application's appearance, offering styles such as decorated or undisguised, while the Pane class structures subclass elements for user interaction .

In Java, arrays can be passed to methods and returned to handle bulk data processing efficiently. When passing an array to a method, the method receives the reference to the array, allowing modifications within the method to affect the original array. For instance, a method designed to calculate an average might iterate over elements to compute the total, then return the average. This behavior facilitates data manipulations in methods without needing to copy the array, thus conserving memory and optimizing performance .

The Scanner class in Java provides a flexible and convenient way of reading input from various sources, including files, which is beneficial for file handling operations. Using 'new Scanner(new File("filename.txt"))', it allows the program to parse primitive types and strings using regular expressions. However, the Scanner class is primarily designed for parsing simple, presentational data and might not efficiently handle complex file manipulations or binary files, which require more specialized I/O classes. Despite its limits, its simplicity makes it an excellent choice for beginners and straightforward text processing tasks .

Java methods facilitate operations by grouping statements to perform tasks or computations, enhancing modularity and readability of code. Method headers play a critical role as they declare the method's return type, name, and parameters, along with its access scope (public, private). They serve as an interface to the implementation details, ensuring that other parts of the program can call and use the method efficiently. Method headers streamline code maintenance and collaboration by clearly defining what a method does and how to interact with it .

In Java, mathematical operators handle arithmetic expressions by performing operations on operands. The addition operator (+) adds two or more operands, which can be constants or variables, as in 'x + y'. The subtraction operator (-), though mistakenly indicated as (+) in the source, subtracts one operand from another. The multiplication operator (*) multiplies two operands, while the division operator (/) divides a numerator operand by a denominator operand. The modulus operator (%) returns the remainder of dividing two operands .

The Math.round() function in Java rounds its functional parameter by first adding 0.5 to it and then returning the largest integer less than or equal to that value. It handles different data types by offering overloads: one for a float type, returning a closest integer, and another for a double type, returning the closest long integer. This dual handling ensures compatibility with various numeric types encountered in mathematical computations within Java programs .

The Application.launch() method is critical in initializing Java applications as it sets up the main application environment and threads needed for running the JavaFX program, handling platform-specific details. It is typically called from the main method, where it prepares the program's stage and associated graphical user interface (GUI). Related methods such as 'start()' prepare processes for execution, emphasizing separation of initialization logic from execution. These methods together streamline starting and managing a JavaFX application's lifecycle, ensuring smoother runtime behavior and interaction readiness .

You might also like