0% found this document useful (0 votes)
9 views42 pages

OOP Chapter 2

The document provides an overview of the basics of Java programming, focusing on object-oriented programming concepts. It covers Java syntax, variable types, identifiers, literals, arrays, and operators, along with examples of local, instance, and class/static variables. The content is structured to guide beginners in understanding Java's fundamental principles and coding practices.

Uploaded by

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

OOP Chapter 2

The document provides an overview of the basics of Java programming, focusing on object-oriented programming concepts. It covers Java syntax, variable types, identifiers, literals, arrays, and operators, along with examples of local, instance, and class/static variables. The content is structured to guide beginners in understanding Java's fundamental principles and coding practices.

Uploaded by

kerimadafis
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 42

Object Oriented

Programming Language
Basics in Java
Programming

IS_Dept@AU Waliso Object Oriented Programming – INSY2042 1


Contents
 Java syntax, Variable and Identifiers,
Data types, and Constant
 Output and Input Statement in Java
 Types Conversion /Casting
 Decision and Repetition Statements
 If else statements
 Switch statements
 Loop statements

IS_Dept@AU_Waliso Object Oriented Programming – INSY2042 2


Basics Java Syntax
 Java syntax.
 Java uses a curly brace ({}) to define blocks
of code.
 Statements end with a semicolon (;).
 Java is case-sensitive, so "myVariable" and
"myvariable" are treated as different
identifiers.
 The entry point of a Java program is the main
public static void main(String[] args) {
method, which
// Code goeshashere the following syntax:
}

IS_Dept@AU_Waliso Object Oriented Programming – INSY2042 3


Basics Java Syntax
 Class Names − For all class names the first
letter should be in Upper Case. If several words
are used to form a name of the class, each inner
word's first letter should be in Upper Case.
Example: class MyFirstJavaClass
• Method Names − All method names should start
with a Lower Case letter. If several words are
used to form the name of the method, then each
inner word's first letter should be in Upper Case.
Example: public void myMethodName()

IS_Dept@AU_Waliso Object Oriented Programming – INSY2042 4


Basics Java Syntax
 Program File Name − Name of the program
file should exactly match the class name.
Example: Assume 'MyFirstJavaProgram' is
the class name. Then the file should be saved
as 'MyFirstJavaProgram.java‘
 public static void main(String args[]) −
Java program processing starts from the
main() method which is a mandatory part of
every Java program.

IS_Dept@AU_Waliso Object Oriented Programming – INSY2042 5


Basics Java Syntax
• Lexical Structure
 The lexical structure of a language refers to the
elements of code that make the code easy for us
to understand, but have no effect on the compiled
code.
 Comments: Comments make your code easy to
understand, modify, and use.
• COMMENT STYLE #1: /* Comments here... */
– This style of commenting comes to us directly from C.
• COMMENT STYLE #2: // Comment here...
– This style of commenting is borrowed from C++.
• COMMENT STYLE #3: /** Doc Comment here... */

IS_Dept@AU_Waliso Object Oriented Programming - INSY2042 6


Identifiers
• Identifiers
 Identifiers are the names used for variables,
classes, methods, packages, and interfaces to
distinguish them to the compiler.
 Identifiers in the Java language should always
begin with a letter of the alphabet, either upper
or lower case.
 The only exceptions to this rule are the underscore
symbol (_) and the dollar sign ($), which may also
be used.
 After the initial character you are allowed to use
numbers, but not all symbols.
 You must also be careful not to use any of the
IS_Dept@AU_Waliso Object Oriented Programming – INSY2042 7
special Java keywords.
Identifiers
 Here are some examples of valid identifiers:
HelloWorld $Money TickerTape
_ME2 Chapter3 ABC123
• Keywords
 These are reserved for system use.
 They can’t be used as names for your classes,
variables, packages, or anything else.
 Keywords are used for a number of tasks such as
defining control structures (if, while, and for) and
declaring data types (int, char, and float).

IT_Dept@AU_Waliso Object Oriented Programming – INSY2042 8


Fundamentals of Java…
• Literals
 Literals are the values that you assign when
entering explicit values.
 For example, in an assignment statement like i =
10; the value 10 is a literal.
 Do not get literals confused with types.
• Types are used to define what type of data a variable can
hold, while literals are the values that are actually
assigned to those variables.
 Literals come in three flavors: numeric, character,
and boolean.
• Boolean literals are simply True and False.

IS_Dept@AU_Waliso Object Oriented Programming – insy2042 9


Fundamentals of Java…
• Separators
 Separators are used in Java to delineate blocks of code.
 For example, you use curly brackets
• to enclose a method’s implementation, and
• you use parentheses to enclose arguments being sent to a
method.
 For Example:
Separator Description
() Used to define blocks of arguments
[] Used to define arrays
{} Used to hold blocks of code
, Used to separate variables in a
declaration
; Used to terminate lines of contiguous
code
IS_Dept@AU_Waliso Object Oriented Programming – INSY2042 10
Fundamentals of Java…
• Types and Variables
 Variables are basically buckets that hold
information, while types describe what type of
information is in the bucket.
 A variable must have both a type and an
identifier.
 Types can be split into several different categories
including the numeric types - byte, short, int,
long, float, and double - and the char and
boolean types.

IS_Dept@AU_Waliso Object Oriented Programming – INSY2042 11


Fundamentals of Java…
• Variable declarations
 Declaring variables in Java is very similar to declaring
variables in C/C++ as long as you are using the
primitive data types.
 Almost everything in Java is a class - except the
primitive data types.
 Here is what a standard declaration for a primitive
variable might look like: int i;
• We have just declared a variable “i” to be an integer.
• Here are a few more examples:
byte i, j;
int a=7, b = a;
float f = 1.06;
String name = "Tony";
IS_Dept@Au_Waliso Object Oriented Programming – INSY2042 12
Kinds of Variable In java
• There are three kinds of variables in java
o Local variables
o Instance variables
o Class/Static variables
Local Varibale
• Local variables are declared in methods,
constructors, or blocks.
• Local variables are created when the method,
constructor or block is entered and the
variable will be destroyed once it exits the
method, constructor, or block
IS_Dept@AU_Waliso Object Oriented Programming – INSY2042 13
Example of Local
Variable
public class Test {
public void pupAge() {
int age = 0;
age = age + 7;
System.out.println("Puppy age is : " + age);
}
public static void main(String args[]) {
Test test = new Test();
test.pupAge();
}
} Output puppy age is : 7
IS_Dept@AU_Waliso Object Oriented Programming – INSY2042 14
Instance Variable
• Instance variables are declared in a class, but
outside a method, constructor or any block.
• Instance variables are created when an object
is created with the use of the keyword 'new'
and destroyed when the object is destroyed.
• Instance variables hold values that must be
referenced by more than one method,
constructor or block, or essential parts of an
object's state that must be present throughout
the class.

IS_Dept@AU_Waliso Object Oriented Programming – INSY2042 15


Example of Instance
import java.io.*;
Variable
public class Employee
{
// this instance variable is visible for any child class.
public String name;
// salary variable is visible in Employee class only.
private double salary;
// The name variable is assigned in the constructor.
public Employee (String empName) { name = empName; }
// The salary variable is assigned a value.
public void setSalary(double empSal) {
salary = empSal; }
// This method prints the employee details.
public void printEmp() {
System.out.println("name : " + name );
System.out.println("salary :" + salary); }
public static void main(String args[]) {
Employee empOne = new Employee("Ransika");
empOne.setSalary(1000);
empOne.printEmp();
}} Output name: Ransika
Salary: 1000.0

IS_Dept@AU_Waliso Object Oriented Programming – INSY2042 16


Class /Static Variables
• Class variables also known as static variables are
declared with the static keyword in a class, but
outside a method, constructor or a block.
• There would only be one copy of each class variable
per class, regardless of how many objects are created
from it.
• Static variables are rarely used other than being
declared as constants. Constants are variables that are
declared as public/private, final, and static. Constant
variables never change from their initial value.
• Static variables are stored in the static memory. It is
rare to use static variables other than declared final
and used as either public or private constants.
IS_Dept@Au_Waliso Object Oriented Programming – INSYA2042 17
Class /Static Variables…
• Static variables are created when the program
starts and destroyed when the program stops.
• Visibility is similar to instance variables. However,
most static variables are declared public since they
must be available for users of the class.
• Static variables can be accessed by calling with
the class name ClassName.VariableName.
• When declaring class variables as public static
final, then variable names (constants) are all in
upper case. If the static variables are not public
and final, the naming syntax is the same as
instance and local variables.
IS_Dept@AU_Waliso Object Oriented Programming – INSY2042 18
Class /Static Variables…
import java.io.*;
public class Employee
{
// salary variable is a private static variable
private static double salary;
// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";
public static void main(String args[]) {
salary = 1000;
System.out.println(DEPARTMENT + "average salary:" +
salary);
} Output: Development average salary: 1000
IS_Dept@AU_Waliso Object Oriented Programming – iINSY2042 19
Fundamentals of Java…
• Using Arrays
 Java uses arrays in a much different manner than
other languages.
 Arrays in Java are actually objects that can be
treated just like any other Java object.
 Because arrays are objects that are derived from
a class, they have methods you can call to
retrieve information about the array or to
manipulate the array.
 One of the drawbacks to the way Java implements
arrays is that they are only one dimensional.

IS_Dept@AU_Waliso Object Oriented Programming – INSY2042 20


Fundamentals of Java…
• Declaring Arrays
 Since arrays are actually instances of classes
(objects), we need to use constructors to create
arrays much like we do with strings.
• First, we need to pick a variable name and declare it as an
array object and also specify which data type the array will
hold.
• Note that an array can only hold a single data type - you
can’t mix strings and integers within a single array.
• Here are a few examples of how array variables are
declared:
int intArray[];
String Names[];
• You could also put the brackets after the data type if you
think this approach makes your declarations more readable.
IS_Dept@AU_Waliso Object Oriented Programming – INSY2042 21
Fundamentals of Java…
• Sizing Arrays
 There are three ways to set the size of arrays.
• Taking a previously declared variable and setting the size
of the array.
intArray[] = new int[10];
Names[] = new String[100];
• You can size the array object when you declare it.
int intArray[] = new int[10];
String Names[] = new String[100];
• Finally, you can fill in the array with values at declaration
time:
String Names[] = {"Tony", "Dave", "Jon", "Ricardo"};
int[] intArray = {1, 2, 3, 4, 5};
IS_Dept@AU_Waliso Object Oriented Programming – INSY2042 22
Fundamentals of Java…
• Accessing Array Elements
 To access an array value, you simply need to know
its location.
 The indexing system used to access array elements
is zero-based, which means that the first value is
always located at position 0.
class MyArrays{
public static void main(String args[]){
int even[] = {2,4,6,8,10};
System.out.println("The second even is: " + even[0]);
}
}
• Displays the first item in the array list by its specific
location within the
IS_Dept@AU_Waliso
list.
Object Oriented Programming – INSY2042 23
Operators, Expressions and Control
Structures
• The tools for manipulating data fall into three
categories
 Operators
 Expressions, and
 Control structures
• Operators are used to perform computations
on one or more variables or objects.
 For Example:
Operator Description
+ Addition
++ Increment
!= Not equal to
+= Assignment with addition
IS_Dept@AU_Waliso Object Oriented Programming – INSY2042 24
Using Java Operators

Using Java Operators


• Operators allow you to perform tasks such as
addition, subtraction, multiplication, and
assignment.
• Operators can be divided into three main
categories: assignment, integer, and boolean
operators.

IS_Dept@AU_Waliso Object Oriented Programming – INSY2042 25


Java Operators…
• Assignment Operators
 The most important and most often used operator
is the assignment operator (=).
 This operator takes whatever variable is on the
left and sets it equal to the expression on the
right:
• i = 25;
 The expression on the right can be any valid Java
expression - a literal, an equation with operands
and operators, a method call, and so on.
• When using an assignment operator, you must be careful
that the variable you are using to receive the expression
is the correct size and type to receive the result of the
expression on the right side.
IS_Dept@AU_2042 Object Oriented Programming - 2042 26
Java operators…
 An assignment statement like this num *= 5;
would be equivalent to this expression: num =
num * 5;
• Integer Operators
 In the category of integer operators, there are two
flavors to choose from: unary and binary.
 A unary operator performs a task on a single
variable at a time. Eg. – (negation), ++
(Increment), -- (Decrement)
 Binary operators, on the other hand, must work
with two variables at a time. Eg. + (addition), %
(Modulo)
• IS_Dept@AU_Waliso
Boolean OperatorsObject Oriented Programming – INSY2042 27

Java Operators…
• Ternary Operator
 This powerful little operator acts like an extremely
condensed if..then statement.
// op1 = True op2 = False
op1 ? (x=1):(x=2); // Answer: x=1
op2 ? (x=1):(x=2); // Answer: x=2

IS_Dept@AU_Waliso Object Oriented Programming – INSY2042 28


Java Separators
• Separators
 Separators are used in Java to delineate blocks of code.
 For example, you use curly brackets
• to enclose a method’s implementation, and
• you use parentheses to enclose arguments being sent to a
method.
 For Example:
Separator Description
() Used to define blocks of arguments
[] Used to define arrays
{} Used to hold blocks of code
, Used to separate variables in a declaration
; Used to terminate lines of contiguous code

IS_Dept@Au_Waliso Object Oriented Programming – INSY2042 29


Output and Input Statement in
Java
• In Java, you can use the System.out object for
output statements and the Scanner class for
input statements.
Output Statements:
• Use the System.out.println() method to print
output to the console. It adds a newline
character after the output.
• Use the System.out.print() method to print
output without adding a newline character.

IS_Dept@AU_Waliso Object Oriented Programming – INSY2042 30


Example
public class OutputExample {
public static void main(String[] args) {
int age = 25;
String name = "John Doe";

// Output with newline character


System.out.println("Name: " + name);
System.out.println("Age: " + age);

// Output without newline character


System.out.print("Name: " + name);
System.out.print(", Age: " + age);
}
} Name: John Doe
Age: 25
Name: John Doe, Age:
25 IS_Dept@AU_Waliso Object Oriented Programming – INSY2042 31
Output and Input Statement in
Java…
Input Statements
o To read a user input from the console, you
need to use the Scanner class fro the java.util
package.
o First, create an instance of scanner class
using the new keyword.
o Then, use the various methods provided by
the scanner class to read different types of
input.

IS_Dept@AU_Waliso Object Oriented Programming – INSY2042 32


Examples
import java.util.Scanner;

public class InputExample {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Read a string
System.out.print("Enter your name: ");
String name = scanner.nextLine();

// Read an integer
System.out.print("Enter your age: ");
int age = scanner.nextInt();

// Output the input values


System.out.println("Name: " + name);
System.out.println("Age: " + age);

// Remember to close the scanner


scanner.close();
}
} Output: Enter your name: John Doe
Enter your age: 25
Name: John Doe
Age: 25
IS_Dept@Au_Waliso Object Oriented Programming – INSY2042 33
Type Conversion /

Casting
In some applications you may need to transfer
one type of variable to another.
• Casting refers to the process of transforming one
variable of a certain type into another data type.
• Casting is accomplished by placing the name of
the data type you wish to cast a particular
variable into in front of that variable in
parentheses.
 Here is an example of how a cast can be set up to
convert a char into an int:
int a;
char b;
b = 'z';
a = (int) b;
IS_Dept@Au_Waliso Object Oriented Programming – INSY2042 34
Flow Control Statements
• Java provides several different types of
control flow structures.
• These structures provide your application
with direction.
• They take an input, decide what to do with it
and how long to do it, and then let
expressions handle the rest.
• Let us see them one by one how they work in
Java.

IS_Dept@AU_Waliso Object Oriented Programming – INSY2042 35


If…else statement
• The if..else structure performs this operation:
if this is true then do that otherwise do something else.
• Of course, the “otherwise” portion is optional.
• Here is the structure labeled with standard terms:
if (boolean)
statement;
else statement;
• Here is a sample of what an if..else statement might look
like with actual code:
if (isLunchtime) {
Eat = true;
Hour = 12;
}
else {
Eat = False;
Hour = 0;
}
IS_Dept@AU_Waliso Object Oriented Programming - 2042 36
If…else statement…
• You can also use nested if..else statements:
if (isLunchtime) {
Eat = true;
Hour = 12;
}
else if (isBreakfast) {
Eat = true;
Hour = 6;
}
else if (isDinner) {
Eat = true;
Hour = 18;
}
else {
Eat = false;
Hour = 0;
}
IS_Dept@AU_Waliso Object Oriented Programming – INSY2042 37
while and do…while

statements
The while and do..while loops perform the same
function. The only difference is that:
 The while loop verifies the expression before executing
the statement, and
 The do..while loop verifies the expression after
executing the statement.
• Here are the structures labeled with standard terms:
while (boolean) {
statement;
}

do {
statement
} while(boolean);
IS_Dept@AU_Waliso Object Oriented Programming – INSY2042 38
while...
• while and do..while loops are used if you want to
repeat a certain statement or block of statements until
a certain expression becomes false.
• Here is an example for both of the loop statements.
int n = 0;
while(n <= 5){
System.out.println(n);
n++;
}

int n = 0;
do{
System.out.println(n);
n++;
}while(n <=5);
IS_Dept@AU_Waliso Object Oriented Programming – INSY2042 39
switch statement
• The switch control flow structure is useful
when you have a single expression with
many possible options.
• The same thing can be done using recursed
if..else statements.
• The swtich statement is executed by
comparing the value of an initial expression
or variable with other variables or
expressions.

IS_Dept@AU_Waliso Object Oriented Programming – INSY2042 40


switch….
• Let’s look at the labeled structure:
switch(expression) {
case expression: statement;
break;
case expression: statement;
break;
case expression: statement;
break;
default: statement;
break;
}

IS_Dept@AU_Waliso Object Oriented Programming – INSY2042 41


for loop
• The idea behind a for loop is that we want to step
through a sequence of numbers until a limit is
reached.
• The loop steps through our range in whatever step increment
we want, checking at the beginning of each loop to see if we
have caused our “quit” expression to become true.
 Here is the labeled structure of a for loop:
• for (variable ; expression1 ; expression2)
 The variable we use can either be one we have
previously created, or it can be declared from within the
for structure
 Here is an example of a for loop that actually works:
for (int n = 0; n <=5; n++){
System.out.println(n);
}
IS_Dept@AU_Waliso Object Oriented Programming – INSY2042 42

You might also like