Refresher: Main Class
Refresher: Main Class
Main Class
- In creating a project, when the tickbox is checked for main class, ang
lalabas is may name na, name ng bagong class, and may public static
void na.
- Otherwise, wala.
Package
- Para magkasama lahat ng similar utilities
Classes
- Dapat same name ng project and package, dapat it depends sa
functionality
- Do not place java class in the default package
NAMING
Class
- Kapag class, upper case first letter, if 2 or more words, lagi uppercase
first letter.
- Class is a blueprint
Method
- Kapag method, lowercase first letter, if 2 or more words, next word would
be capital.
Sa may bond paper na may play button when class is created, it defines
kung main methodd or hindi yung nicreate depending kung tinick box or
hindi
DATA TYPES
1. Primitive
- lowercase
- They are predefined by the language itself and represent basic values
like numbers, characters, and true/false statements
- int, boolean, float, double, char, long
2. Non-primitive
- capital letter
Class type
- may mga methods na iccall
main() is public static void for accessibility and to serve as the program's entry
point without returning a value. public ensures that the method is accessible
from outside the class. static method belongs to the class, not an instance of
the class. void indicates that the main() method doesn't return any value.
VARIABLE TYPES
1. Global Variables/Class Variable
- declared inside a class but outsidde a method, have a default value
- String = null, int = 0, double = 0.0, float = 0, long = 0, char =wala
2. Local Variable
- It doesn’t have a default value
ln = line next
print = within the same line
scan.next();
- don't accept white spaces
scan.nextLine();
- accepts white spaces
1 tab = 8 spaces
The main difference between Class and Method is that class is a blueprint or
a template to create objects while method is a function that describes the
behavior of an object.
JAVA
- In 1991, SunMicrosystems (acquired by Oracle Corporation on January 27,2010) funded a research project to develop a programming
language that may be used for electronic consumer devices such as television and video cassette recorders.
- The project led by James Gosling resulted in a language called Oak. This was replaced with Java as the latter was already used.
- James Gosling is considered the Father of the Java programming language.
- On May 23, 1995 at Sun World San Francisco, Sun Microsystems, Inc., Java Technology was officially born.
- Java is initially used for developing games.
This product group allows the creation of enterprise applications such as e-commerce solutions.
Packages
- like a folder in a directory where we can throw all our related codes in the same directory
- lowercase first letter in first word, capital letter first letter in next word
Class
Data Type
- type of data inside our variable.
Identifiers
- name of the variable that the programmer indicated
- used to read and write the variable
Rules of Identifiers
1. can't use any special characters other than underscore and dollar sign.
2. can't use whitespaces
3. can't use numbers alone
4. can use numbers but with letters
Declaring variables
Syntax:
datatype identifier;
Reassigning Variable
identifier = value;
Printing
System.out.println();
- used to display something
Concatenation
- process of joining strings together with plus operator.
- anything that adds with string is string.
- you can concatenate inside a variable or print statement
Example:
"Hello" + "World";
JavawasoriginallydevelopedoutofSunMicrosystemsplantodevelopaprogramminglanguageforelectronicconsumerdevicelikevideocassetterecorders.
▪
Java Development Kit (JDK) is an application commonly used with a text editor to develop Java programs.
▪
NetBeans may be used to code, compile, and execute java programs. Both can be downloaded for free.
▪
NetBeans like JDK is an Integrated Development Environment where Java programs can be executed.
▪
Java technology Product Groups include Java Standard Edition (JSE), Java Micro Edition (JME), and Java Enterprise Edition (JEE).
▪
Platform Independent is a feature that allows Java programs to run on different operating systems or processors provided that a Java Virtual Machine is available.
A Java program is made up of classes. A class can be thought of as a collection of variables and subroutines (also known as methods). A subroutine is a
collection of program instructions that may be made up of the following essential program elements:
• Literals
• Identifiers
• Expressions
• Statement
Literals
Literals may be thought of as constants or fixed values. They could either be numeric, string or character in general.
Numeric
• literals that are of numeric type. Only the following symbols are allowed {D0,1,2,3….9,+,-,.}
Examples:
Invalid constants:
Identifiers
Identifiers are names given to variables and literals. Literals are constants or fixed values while variables are entities that can hold these literals.
Suppose we have
X=5, 5 is the literal while x is the variable holding the literal value 5.
Identifiers are also used to name sub-programs or methods and class names Methods and class names will become important in the latter chapters. What
is important at this point is how to name variables and literals.
A variable name may start with a letter, and underscore (_) or a dollar sign($)
It must not be a keyword, Keywords like if and while have special meaning to java
Subsequent characters may be letters, numbers, underscore or dollar sign.
In following Java’s coding guidelines, the first letter of variable name should be in lowercase. The first letter of the subsequent words should be
capitalized.
The same rules apply to method and class names, except that class names start with an uppercase letter.
Note: Java is Case Sensitive. It make a distinction between uppercase and lowercase letters. the totalBill variable where in the first letter is in lower case will
be treated differently with TotalBill. The same goes with all identifiers and keywords.
EXPRESSIONS
Expression is a group of elements with operators that determine how they may be evaluated. An expression could either be Arithmetic or a Boolean
expression. An expression either yields a numeric or logical value (i.e. true or false)
ARITHMETIC EXPRESSION
Unary Operators
The symbols
• ++ Increment (x+1)
• - - Decrement (x-1)
They are called Unary as they only require a single operand
When (++) and (--) are placed before a variable, they are called pre-increment and pre-decrement. On the other hand, if they are placed after the
variable, they are called post-increment and post-decrement.
Example:
int price = 5;
newPrice = ++price
6=6
Both variables have the value of 6 (final/changing value) due to the pre-increment which suggests it to happen.
int x1 = 5;
int x2 = – - x1;
4=4
Both variables have the value of 4 (final/changing value) due to the pre-decrement which suggests it to happen.
int y1 = 5;
int y2 = y1 - -;
5=4
The value of 5 will be stored in the variable y2 while variable y1 will have the value 4 due to the post-decrement operator.
Post-increment/decrement - assigns the value first into a variable before incrementing/ decrementing it.
Pre-increment/ decrement - increases/decreases the value of the variable prefixed with the unary operators before assigning it to another variable.
BOOLEAN EXPRESSION
A boolean expression consists of relational expressions with logical operators. A relation expression consists of operands and relational operators. These
operands may be literals, variables, or even arithmetic expressions. It always yields either true or false value.
Relational Operators
The answer is true only when both expressions are true; otherwise, it is false.
The answer is false only when both expressions are false; otherwise, it is true.
The | operator simply negates the result of expression; I True is false and false is true.
STATEMENTS
These are keywords that perform a predefined task. They are similar to sentences. A sentence as taught in the elementary level is a word or group of
words that expresses a complete thought. A statement in programming is a collection of keywords and elements that expresses a complete instruction. A
sentence ends with a period while a statement in Java ends with a semicolon (;).
Package Declaration:
package javaapplication1;
This line declares that the ‘JavaApplication1’ class is part of the ‘javaapplication1’ package. Packages are used to organize Classes into namespace and
provide a way to manage the class files.
Class Declaration:
public class JavaApplication1 {
This line declares a class named ‘JavaApplication1’. The class is declared as ‘public’, which means it can be accessed from Other classes. This class
contains the ‘main’ method, which serves as the entry point of the program.
Variable Declaration:
String name = "John";
This line declares a String variable names ‘name’ and initializes it with the value “John”. The variable is local to the ‘main’
method, which means it can only be accessed within this method.
Printing a Message:
System.out.println("Hello " + name);
This line prints the concatenated string “Hello” followed by the value of the ‘name’ variable. In this case, it will print
“Hello John” because the ‘name’ variable is initialized with the value “John”.
Built-In Packages
- pre-written classes to help the programmer manage input, database.
User Input
String x;
Scanner s = new Scanner(System.in);
x=s.nextLine();
Conditional Statements
- allows a program to take action based on the given condition.
- compares two values
- decision making
- will run if conditions are true.
RELATIONAL OPERATORS
Equals (==)
Not equals (!=)
Less Than (<)
Less Than or equals (<=)
Greater Thaan (>)
Greater Than or Equals (>=)
IF STATEMENT
- handles 1 conditional expression, it either does something or nothing
Syntax:
if(condition){
//do anything
}
if(age>=18){
System.out.println("LEGAL");
}
IF-ELSE STATEMENT
- handles 2 conditional exprression, it either does the first code block or second
Syntax:
if (condition){
//
}else{
//
Syntax:
if (condition){
//
}else if (condition){
// kahit ilang else if pwede
}else{
// laging nasa dulo
}
if (condition){
if (condition){
//
}
}
EQUALS FUNCTION
- compare strings more efficiently
Syntax:
String x="Hello";
if (x.equals("Hello")){
//
}
if (x.equalsIgnoreCase("Hello")){
//
}
SWITCH STATEMENTS
- similar to conditional statemenrs but checks for equality and only works with
strings, char, int, and enumerators
- the keyword switch starts the structure and is followed immediately by a test
expression enclosed in parentheses.
- the keyword case is followed by one possible value for the test expression and
a colon.
- the break keyword automatically terminates the switch statements after the
execution of that case.
- the default keyword optionally is used prior to any action that should occur if
the test variable does not match any case.
CASE keyword
- used to define a case in switch statement
Syntax:
switch(variable){
case value1;
//
break;
case value 2;
//
break;
}
DEFAULT Keyword
- handle values that are not on a case
- recommended to use on the end of the switch statement (serves as else
statement)
- di need ng break keyword under
Syntax:
switch(variable){
BREAK Keyword
- break out of a switch statement or loop without executing the whole block of
code inside it.
WHILE LOOP
- when u want a code block to run repeatedly while a condition is met.
Syntax:
while(condition){
//
}
ITERATING Arrays
- read every element inside an array and do something
- can be accessed through indeex
- index starts with 0
Array Length
- findd the size of the arrays
- .length();
DO WHILE LOOP
- same as the while loop but executes the code block before checking the condition.
Syntax:
do{
//
}while(condition){
//
}
BREAK Keyword
- break out of a loop earlier than it is expected to end
int i = 0;
while(condition){
// Soutprintln (i);
i++;
break;
}
FOR LOOP
- used when u want a code block to run repeatedly while a condition is met
- more compact format but more complicated version
- used to iterate through collections of arrays
Syntax:
for (intitialization, condition, operation){
//
}
Syntax:
for (datatype identifier : collection){
//
}
Result:
1
2
3
4
5
}
}
2D ARRAY
- arrays within an array, rows and columns
- stores one data type at a time
String users[][]={
{"David","david"},
{"Abby","abby"},
{"bene","Bene"},
{"Ivan","Ivan"},
}
ITERATING 2D ARRAYS
String users[][]={
//0 //1
//0 {"David","david"},
//1 {"Abby","abby"},
//2 {"bene","Bene"},
//3 {"Ivan","Ivan"},
}
Result:
David
david
Abby
abby
bene
Bene
Ivan
ivan
METHODS/FUNCTIONS
- used to divide and sort functionalities within a class so that the code will be readable even if it is long.
CREATING Methods
Syntax:
modifiers returntype methodName(){
//
}
CALLING Methods
- we need to call other methods to main method
/* multi-line comment */
VARIABLE SCOPING
Global Variables
- are variables declared within a class, it can be accessed within the whole class.
If declaring, it has to have modifier "static".
E.g: static num =100;
Local Variables
- Variables declared inside a method, condition, loops, any other block of code, and only accessible
within that block of code.
Arguments/Parameters
- Value that needs to be passed on a method so that method can use that value and perform various
operations on it.
- U can have as many arguments/parameters as u want. They at as local variable inside a
method/function.
Methods w/Arguments
//do anything
print("hello world");
}
Return keyword
- to return a value from the method. used when a method has result.
Return type
- type of the valiue that will be returned, returntype is similar to datatype
Methods w/ return
OVERLOADING Methods
- u can use the same method name but different parameters so that u will cater every possibility of a
method.
- 2 adding numbers and 3 add numbers
Soutprintln (add(5,2));
Soutprintln (add(5,2,3));
PACKAGES
- folder in our project where we can throw related codes in the same directory.
Creating packages
- we can create multiple packages in a java project.
Creating classes
- we can create classes inside a package and import it in our main class so that we can use that
class.
- Main class - un lang pinakanagrurun sa code
- subclasses - iniimport sa main class para magamit.
IMPORTING PACKAGES
CLASS Instantiation
- process of creating an instance of a class so we can use it in our program
ACCESS MODIFIERS
- used to modify where classes, variables and methods are accessible.
- Keywords kung hanggang saan visibility ng variables, classes and methods
- Ang local variables, hindi pede lagyan ng access modifiers
MODIFIERS (CLASSES)
1. default - the class can only be accessed by classes in the same package.
2. public - the class can be accessed anywhere as long as it is imported.
for class
1. final - the class can't be inherited by other classes.
2. abstract - can't be used to instantiate objects. we can only access an abstract class by
inheriting it from another class.
OOP
- it focused on implementing real world objects using classes to create variations of objects that
has attributes and purpose.
- it helps create flexible and efficient code than procedural programming.
CLASSES
- created by the programmer, act as a blueprint of an object that u want to implement
- contains attributes and methods that ur desired object should have.
OBJECTS
- created by instantiating a class
- anything that has an attribute and a purpose.
- example: food, person, furniture
ATTRIBUTES
- global variables declared inside the class of our object.
- papalitan lang value nng global variables.
- used to create variations of an objects using one class.
CLASS CREATION
PERSON
- first name
- last name
- sex
- age
CLASS INSTANTIATION
- the process of creating an object using a class so we can use it in our program.
ACCESSING ATTRIBUTES
WRITING Attributes
identifier.attribute = value;
READING Attributes
Soutprintln(identifier.attribute);
CONSTRUCTORS
- it is the method called when u instantiate a class/ create an object.
- to initialize attributes of object or run a block of code when an object is created.
className(){
//constructor
}
}
Written Exam and Hands-On exam - week after written exa, lab schedule
PACKAGE
- collection of related classes.
CLASSES
- blueprint kung san nagdedefine data and information/methods related to that
class.
OBJECT
- considered as real world object
METHOD
- action done by object.
- magbasa ng input.
String sayHello(){
return "hello";
}
5 MIN PRESENTATION
- user input
- 2 objects, data na need coming from user
OOP 1 Page 24
- 2 objects, data na need coming from user
- 2 class, different methods
Decimal Format:
W % in decimal format "0.00%" - multiplied to 100 + %
Random Class:
Automatically generate a random number, mula sa range ng integer whether
positive or negative.
OOP 1 Page 25
L2: PACKAGES AND CLASSES
Thursday, 12 September 2024 2:08 pm
PACKAGES
- folder in our project where we can throw related codes in the same directory.
- Collection of related classes.
Creating packages
- we can create multiple packages in a java project.
Creating classes
- we can create classes inside a package and import it in our main class so that
we can use that class.
- Main class - un lang pinakanagrurun sa code
- subclasses - iniimport sa main class para magamit.
IMPORTING PACKAGES
ACCESS MODIFIERS
- used to modify where classes, variables and methods are accessible.
- Keywords kung hanggang saan visibility ng variables, classes and methods
- Ang local variables, hindi pede lagyan ng access modifiers
MODIFIERS (CLASSES)
1. default - the class can only be accessed by classes in the same package.
2. public - the class can be accessed anywhere as long as it is imported.
OOP 1 Page 26
NON- ACCESS MODIFIERS
- add other functionalities for classes variables, methods, basically used for
specific situations
- pwede paghalu-haluin access and non-access modifiers, huwag lang yung
dalawang access modifiers sa isang method, pero 2 non-access pwede.
- Keywords that gives aditional meaning or functions to variables and methods
- Cant be added to local variables, for global only
Kung may local and global na same name pero gusto mo tawagin is global, call the
(classname.variable), uunahin kuhanin is local variable in short ibahin pangalan
To use instane variables to static methods, gawa class instantiation and objects
Di pwede tawagin instance variables directly sa static methods
OOP 1 Page 27
L3: ENCAPSULATION
Thursday, 19 September 2024 1:13 pm
Encapsulation: It is the process of hiding all the details of how a piece of software is
written and telling only what a programmer needs to know. Inside the "capsule" (can
be a class or interface). Encapsulation may hide the fine details. For this reason, it is
often called information hiding.
OOP 1 Page 28
L4: METHOD OVERLOADING
Tuesday, 24 September 2024 8:14 am
Bawal talaga gumawa ng same method but it is possible with method overloding
Method overloading : we can overload the same method name but list of the
parameters must be different.
SECOND RULE: method with same name but different returning value (also list must
be different)
Just changing the returning type is insufficient, list must be also different
OOP 1 Page 29
L5: CONSTRUCTOR
Tuesday, 24 September 2024 8:32 am
RULE 1; The name of constructor must be the EXACTLY same after class name (kung
lowercase lowercase, kung uppercase, uppercase)
It is executed after the keyword new
Through the use, u can initialize directly their calue
Through c, u can set the value
Final, pwede initialize pero dapat sa lahat ng methods nakalagay value, kahit
magkaiba iba pa
OOP 1 Page 30
OBJECT METHODS
Wednesday, 25 September 2024 7:26 pm
OOP 1 Page 31
L6: INHERITANCE
Wednesday, 2 October 2024 3:39 pm
• Sa inheritance, mas nagiging reusable yung attributes, if they have the same
attributes and methods
EXTENDS Keyword
- used after class name and it indicates that thhe certain class will inherit from
another class.
- nagagawa inheritance
Protected access modifier: its accessibility is within the same package and its
subclasses
Mas maraming kayang gawin ang subclass kaysa kay superclass. Yung pinakalast
na nagmana dhil nakuha nya lahat ng ininherit if multilevel.
Kayang mag instantiaate using parent class for the subclass pero di pwede
viceversa
Ex: Car d = new Motor(); *parameters must be based on the parameters of the
subclass
Hierarchical Inhertance: Class D, Class B, and Class C nag iinherit kay Class A.
OOP 1 Page 32
Hindi naiinherit constructor, but we can invoke by using super keyword
Kapag default access modifier, wala problem
Super- for invoking the constructor from the parent class, dito nagseset value, same
with keyword this in terms of, di sila pede gamitin parehas sa mga may keyword na
static.
In inheritance,
This keyword- pertains to the subclasses and parent class
Subclass must not be less restrictive pero kapag e.g parent class is protected tas
subclass is public pwede un since less restrictive un
OOP 1 Page 33