0% found this document useful (0 votes)
27 views

4 Programming Fundamentals

The document discusses programming fundamentals in Java, including the basic parts of a Java program, primitive data types, variables, identifiers, operators, and coding guidelines. It provides an example of a simple Java program with a main method that prints "Welcome to ICT!" and explains each part of the program. It also covers topics like comments, statements, blocks, and naming conventions in Java code.

Uploaded by

May-ann Norico
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

4 Programming Fundamentals

The document discusses programming fundamentals in Java, including the basic parts of a Java program, primitive data types, variables, identifiers, operators, and coding guidelines. It provides an example of a simple Java program with a main method that prints "Welcome to ICT!" and explains each part of the program. It also covers topics like comments, statements, blocks, and naming conventions in Java code.

Uploaded by

May-ann Norico
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

20 | P a g e

IV. Programming Fundamentals 
 
Objectives: 
 
In this chapter, the basic parts of the Java program shall be discussed. We will also be discussing 
about  some  coding  guidelines  or  conventions  as  well  as  fundamental  items  in  Java 
programming. 
 
At the end of this lesson, the student should be able to: 
 Identify the basic parts of a Java program 
 Differentiate  among  Java  literals,  primitive  data  types,  variable  types,  identifiers,  and 
operators. 
 Develop a simple valid Java program. 
 
Dissecting My First Java Program 
 
  public class MyFirstJavaProgram
{
public static void main(String[] args)
{
System.out.println(“Welcome to ICT!”);
}
}
 
The first line of code, 
 
  public class MyFirstJavaProgram 
 
indicates  the  name  of  the  Java  program  which  is  MyFirstJavaProgram.  The  next  line  which 
contains  a  curly  brace  {  indicates  the  start  of  a  block,  which  will  be  discussed  later  in  this 
chapter. 
 
The next line, 
 
  public static void main(String[] args)
 
indicates  the  main  method  of  our  MyFirsJavaProgram  class.  The  main  method  is  the  starting 
point of a Java program. All Java programs except applets start with the main method. The next 
line which is a curly brace { indicates the start of the block of the main method. 
 
The next line, 
 
  System.out.println(“Welcome to ICT!”);
 
displays the text Welcome to ICT! to the screen. The command System.out.println(), prints the 
text enclosed by the quotations to the screen. 

Training-workshop on Object-oriented Programming using Java


21 | P a g e

 
The last two lines which contain the two curly braces are used to close the main method and 
the class MyFirstJavaProgram respectively. 
 
Coding Guidelines: 
 
1. Your Java programs should always end with the .java extension. 
 
2. Filenames should match the name of your public class. So for example, if the name of your 
public class is MyFirstJavaProgram, you should save it in a file called MyFirstJavaProgram.java. 
 
3. You should write comments in your code explaining what a certain class does, or what a 
certain method do. 
 
 
Java Comments 
To comprehend any programming language, there are several kinds of comments which 
are used. Comments are notes written to a code for documentation purposes. Those texts are 
not part of the program and do not affect the flow of the program. Java supports three types of 
comments:  C++‐style  single  line  comments,  C‐style  multi‐line  comments  and  special  javadoc 
comments. 
 
C++ ‐ style Comment 
C++ Style comments starts with //. All the text after // are treated as comments. We can 
write only a single line comment use these slashes. Example: 
 
// This is a single‐line comment in a java program. 
 
C‐style Comment 
C‐style comments or also called multi‐line comments starts with a /* and ends with a */. 
All texts in between the two delimiters are treated as comments. Unlike C++ style comments, it 
can span multiple lines. Example: 
 
/* This is a multiple line 
    comment in a java program */ 
 
Special Javadoc Comment 
Special  Javadoc  comments  are  used  for  generating  an  HTML  documentation  for  your 
Java  programs.  You  can  create  javadoc  comments  by  starting  the  line  with  /**  and  ending  it 
with  */.  Like  C‐style  comments,  it  can  also  span  lines.  It  can  also  contain  certain  tags  to  add 
more information to your comments. 
 
 
 
Training-workshop on Object-oriented Programming using Java
22 | P a g e

/**
This is an example of special java doc comment used for
generating an html documentation.
@Charles Jaranilla
@version 64.6
*/
 
Java Statements and Blocks 
A statement is one or more lines of code terminated by a semicolon. 
Example: 
 
System.out.println(“Welcome to ICT!”);
 
A block is one or more statements bounded by an opening and closing curly braces that 
groups the statements as one unit. Block statements can be nested indefinitely. Any amount of 
white space is allowed. 
 
public static void main( String[] args ){
System.out.println("Welcome ");
System.out.println("to ICT!");
}
 
Coding Guidelines: 
 
1. In creating blocks, you can place the opening curly brace in line with the statement. 
Example: 
public static void main( String[] args ){ 
 
Or you can place the curly brace on the next line. Example: 
public static void main( String[] args ) 

 
2. You should indent the next statements after the start of a block. Example: 
 
public static void main( String[] args ){ 
              System.out.println("Welcome "); 
              System.out.println("to ICT!"); 

 
Java Identifiers 
Identifiers are tokens that represent names of variables, methods, classes, etc. 
Naming Guidelines: 
 
 Identifiers must begin with a letter (A‐Z, a‐z), an underscore “_”, or a dollar sign 
“$”. 
 Letters may be lowercase or uppercase. Java identifiers are case sensitive. This 
means that Identifier1 is not the same as identifier1. 
Training-workshop on Object-oriented Programming using Java
23 | P a g e

 Subsequent characters may use number 0 to 9. 
 
Example of identifiers: 
 
    Hello, main, System, out, public
 
Coding Guidelines: 
1. For names of classes, capitalize the first letter of the class name. For names of methods and 
variables, the first letter of the word should start with a small letter. For example: 
ThisIsAnExampleOfClassName 
thisIsAnExampleOfMethodName 
 
2. In case of multi‐word identifiers, use capital letters to indicate the start of the word except 
the first word. For example, charArray, fileNumber, ClassName. 
 
3. Avoid using underscores at the start of the identifier such as _read or _write. 
 
Java Keywords 
Keywords are predefined identifiers reserved by Java for a specific purpose. You cannot 
use keywords as names for your variables, classes, methods …etc. 
Here is a list of the Java Keywords: 
 
 
abstract  continue  for    new    switch 
assert***  default   goto*    package  synchronized 
boolean  do    if    private   this 
break    double   implements  protected  throw 
byte    else    import   public    throws 
case    enum****  instanceof  return    transient 
catch    extends  int    short    try 
char    final    interface  static    void 
class    finally    long    strictfp**  volatile 
Const*   float    native    super    while 
 
      *  not used 
    **  added in 1.2 
  ***  added in 1.4 
****  added in 5.0 
 
 
Note: true, false, and null are not keywords but they are reserved words, so you cannot use 
them as names in your programs either. 
 
 
Training-workshop on Object-oriented Programming using Java
24 | P a g e

 
Primitive Data Types 
A data type is a set of values together with a set of operations. The Java programming 
language defines eight primitive data types. The following are: boolean (for logical), char (for 
textual), byte, short, int, long (integral), double and float (floating point). 
 
Logical – boolean 
It is a data type that deals with logical values. A boolean data type represents two 
states: true and false. 
Example: 
 
boolean result = true;
 
The example shown above, declares a variable named result as boolean type and 
assigns it a value of true. 
 
Textual – char 
A  character  data  type  (char),  represents  a  single  Unicode  character.  It  must  have  its 
literal enclosed in single quotes (’ ’). Example: 
 
‘a’   //The letter a 
‘\t’  //A tab 
 
To  represent  special  characters  like  '  (single  quotes)  or  "  (double  quotes),  use  the  escape 
character \. Example: 
 
'\''  //for single quotes 
'\"'  //for double quotes 
 
Although, String is not a primitive data type (it is a Class), we will just introduce String in this 
section. A String represents a data type that contains multiple characters. It is not a primitive 
data type, it is a class. It has it’s literal enclosed in double quotes(“”). Example: 
 
String message=“Hello world!”
 
Integral – byte, short, int and long 
It  is  a  data  type  that  deals  with  integers,  or  numbers  without  a  decimal  part.  Integral 
data types in Java uses three forms – decimal, octal or hexadecimal. 
 
Example: 
2    //The decimal value 2 
077    //The leading 0 indicates an octal value 
0xBACC  //The leading 0x indicates a hexadecimal value 
 

Training-workshop on Object-oriented Programming using Java


25 | P a g e

Integral types have int as default data type. You can define its long value by appending 
the letter l or L. 
 
Integer Length  Name or Type  Range 

8 bits  byte  ‐27    to   27‐1 

16 bits  short  ‐215  to    215‐1 

32bits  int  ‐231  to    231‐1 

64 bits  long  ‐263  to    263‐1 


Table 4.1: Integral types and their ranges 
 
Floating point – float and double 
It is a data type which deals with decimal numbers. Floating point types has double as 
default data type. Floating‐point literal includes either a decimal point or one of the following: 
 
E or e    //(add exponential value) 
F or f    //(float) 
D or d    //(double) 
 
Example: 
 
3.14      //A simple floating‐point value (a double) 
6.02E23    //A large floating‐point value 
2.718F    //A simple float size value 
123.4E+306D    //A large double value with redundant D 
 
In the example shown above, the 23 after the E in the second example is implicitly 
positive. That example is equivalent to 6.02E+23. 
 
Integer Length  Name or Type  Range 

32 bits  Float  ‐231    to   231‐1 

64 bits  Double  ‐263  to    263‐1 


Table 4.2: Floating point types and their ranges 
 
Allocating Memory 
  When you instruct the computer to allocate memory, you tell it what names to use for 
each  memory  location,  and  what  type  of  data  to  be  stored  into  those  memory  locations. 
Knowing the location of the data is essential because data stored in one memory location might 

Training-workshop on Object-oriented Programming using Java


26 | P a g e

be needed at several places in the program. It is critical to know whether the data must remain 
fixed throughout the program execution or whether it should change. 
 
Named Constants 
  A named constant is a memory location whose content is not allowed to change during 
program execution. To allocate memory, we use Java’s declaration statement. 
  Syntax: 
    static final dataType IDENTIFIER = value;
 
  In Java, static and final are reserved words. The reserved word final specifies that the 
value stored in the identifier is fixed and cannot be changed. The reserved word static may or 
may not appear when a named constant is declared. 
 
Coding Guidelines: 
  Notice that the identifier for a named constant is in upper case letters. This is because 
Java programmers typically use upper case letters to name a named constant. If the name of 
the  named  constant  is  more  than  one  word,  called  a  run‐together‐word,  then  the  words  are 
separated by an underscore. 
 
  Example: 
 
    final int RATE = 800;
final double CENTIMETERS_PER_INCH = 2.54;
 
Variables 
A  variable  is  an  item  of  data  used  to  store  state  of  objects.  It  is  a  memory  location 
whose content may change during program execution. It has a data type and a name. The data 
type indicates the type of value that the variable can hold. The variable name must follow rules 
for identifiers. 
Syntax for declaration: 
  dataType identifier1, identifier2, … , identifierN;
 
Example: 
  double amountDue;
int counter;
char ch; 
 
Primitive  variables  are  variables  with  primitive  data  types.  They  store  data  in  the  actual 
memory location of where the variable is. 
 
Reference  variables  are  variables  that  store  the  address  in  the  memory  location.  It  points  to 
another memory location of where the actual data is. When you declare a variable of a certain 
class, you are actually declaring a reference variable to the object with that certain class. 
  Example: 
    int num = 10;
String name = “Christi”;
Training-workshop on Object-oriented Programming using Java
27 | P a g e

 
Memory Address  Variable Name  Data   

1001  num  10   


:    :   
1563  name  Address(2000)   
:    :   
:    :   
2000    “Christi”   
 
 
Java Operators 
In Java, there are different types of operators. There are arithmetic operators, relational 
operators, logical operators and conditional operators. These operators follow a certain kind of 
precedence  so  that  the  compiler  will  know  which  operator  to  evaluate  first  in  case  multiple 
operators are used in one statement. 
 
Arithmetic Operators 
  One of the most important features of a computer is its ability to compute. We can use 
the standard arithmetic operators to manipulate integral and floating‐point data types in a Java 
program. There are five arithmetic operators: 
 
  + addition
- subtraction
* multiplication
/ division
% modulus (division remainder)
 
Example: 
public class ArithmeticOperatorsSample
{
public static void main(String[] args)
{
int a = 38;
int b = 47;
double c = 23.745;
double d = 8.19;
System.out.println("Variable values: ");
System.out.println(" a = " + a);
System.out.println(" b = " + b);
System.out.println(" c = " + c);
System.out.println(" d = " + d);
System.out.print("\nAdding: ");
System.out.println("a + b = " + (a + b));
System.out.println("c + d = " + (c + d));
System.out.print("Subtracting ");
System.out.println("a - b = " + (a - b));
System.out.println("c - d = " + (c - d));
System.out.print("Multiplying ");

Training-workshop on Object-oriented Programming using Java


28 | P a g e

System.out.println("a * b = " + (a * b));


System.out.println("c * d = " + (c * d));
System.out.print("Dividing ");
System.out.println("a / b = " + (a / b));
System.out.println("c / d = " + (c / d));

System.out.print("Remainder ");
System.out.println("a % b = " + (a % b));
System.out.println("c % d = " + (c % d));
System.out.print("Mixing types ");
System.out.println("a + b = " + (a + b));
System.out.println("c * d = " + (c * d));
}
}
 
Increment and Decrement Operators 
Java  includes  unary  increment  operator  (++)  and  unary  decrement  operator  (‐‐). 
Increment and decrement operators increase and decrease a value stored in a number variable 
by 1. 
Operator  Use  Description 
Increments op by 1; Evaluates to 
++  op++  the value of op before it was 
incremented 
 
 
Relational Operators 
  Relational operators compare two values and determine the relationship between those 
values. The outputs of evaluation are boolean values true or false. 
 
Operator  Use  Description 
>  op1>op2  op1  is greater than op2 
>=  op1>=op2  op1  is greater than or equal to op2 
<  op1<op2  op1 is less than op2 
<=  op1<=op2  op1 is less than or equal to op2 
==  op1==op2  op1 is equal to op2 
!=  op1!=op2  op1 is not equal to op2 
Table 4.4: Relational operators and their uses 
 
Example: 
public class RelationalOperatorsSample
{
public static void main(String[] args)
{
int a = 3;
int b = 5;
int c = 5;
System.out.print("Variable values: ");
System.out.println(" a = " + a);
Training-workshop on Object-oriented Programming using Java
29 | P a g e

System.out.println(" b = " + b);


System.out.println(" c = " + c);
System.out.println("\n is Greater than: ");
System.out.println(" a > b = " + (a > b));
System.out.println(" b > a = " + (b > a));
System.out.println(" c > b = " + (c > b));
System.out.println("\n is Greater than or Equal to: ");
System.out.println(" a >= b = " + (a >= b));
System.out.println(" b >= a = " + (b >= a));
System.out.println(" c >= b = " + (c >= b));
System.out.println("\n is Less than: ");
System.out.println(" a < b = " + (a < b));
System.out.println(" b < a = " + (b < a));
System.out.println(" c < b = " + (c < b));
System.out.println("\n is Less than or equal to: ");
System.out.println(" a <= b = " + (a <= b));
System.out.println(" b <= a = " + (b <= a));
System.out.println(" c <= b = " + (c <= b));
System.out.println("\n is Equal to: ");
System.out.println(" a == b = " + (a == b));
System.out.println(" b == c = " + (b == c));
System.out.println("\n is Not equal to: ");
System.out.println(" a != b = " + (a != b))
System.out.println(" b != c = " + (b != c));
}
}
 
 
Logical Operators 
Logical operators have one or two boolean operands that yield a boolean result. There 
are six logical operators: && (logical AND), & (boolean logical AND), || (logical OR), | (boolean 
logical inclusive OR), ^ (boolean logical exclusive OR), and ! (logical NOT). 
 
Truth table for Logical AND && and Boolean Logical AND &: 
 
op1  op2  Result 
TRUE  TRUE  TRUE 
TRUE  FALSE  FALSE 
FALSE  TRUE  FALSE 
FALSE  FALSE  FALSE 
Table 4.5: Truth table for Logical AND and Boolean Logical AND 
 
The  basic  difference  between  &&  and  &  operators  is  that  &&  supports  short‐circuit 
evaluations (or partial evaluations), while & doesn't. 
 
 
 

Training-workshop on Object-oriented Programming using Java


30 | P a g e

Example: 
public class ANDsample
{
public static void main( String[] args )
{
int a = 0;
int b = 10;
boolean test= false;
test = (a > 10) && (b++ > 9);
System.out.println(a);
System.out.println(b);
System.out.println(test);
test = (a > 10) & (b++ > 9);
System.out.println(a);
System.out.println(b);
System.out.println(test);
}
}
 
 
Truth table for Logical OR || and Boolean Logical OR |: 
 
op1  op2  Result 
TRUE  TRUE  TRUE 
TRUE  FALSE  TRUE 
FALSE  TRUE  TRUE 
FALSE  FALSE  FALSE 
Table 4.6: Truth table for Logical OR and Boolean Logical OR 
 
The  basic  difference  between  ||  and  |  operators  is  that  ||  supports  short‐circuit 
evaluations (or partial evaluations), while | doesn't. 
 
Example: 
public class ORsample
{
public static void main( String[] args )
{
int a = 0;
int b = 10;
boolean test= false;
test = (a < 10) || (b++ > 9);
System.out.println(a);
System.out.println(b);
System.out.println(test);
test = (a < 10) | (b++ > 9);
System.out.println(a);
System.out.println(b);
System.out.println(test);
}
}

Training-workshop on Object-oriented Programming using Java


31 | P a g e

Truth table for Boolean Logical Exclusive OR ^: 
 
op1  op2  Result 
TRUE  TRUE  FALSE 
TRUE  FALSE  TRUE 
FALSE  TRUE  TRUE 
FALSE  FALSE  FALSE 
Table 4.7: Truth table for Boolean Logical Exclusive OR 
 
The result of an exclusive OR operation is TRUE, if and only if one operand is true and 
the other is false. Note that both operands must always be evaluated in order to calculate the 
result of an exclusive OR. 
Example: 
public class XORsample
{
public static void main( String[] args )
{
boolean bol1 = true;
boolean bol2 = true;
System.out.println(bol1 ^ bol2);
bol1 = false;
bol2 = true;
System.out.println(bol1 ^ bol2);
bol1 = false;
bol2 = false;
System.out.println(bol1 ^ bol2);
bol1 = true;
bol2 = false;
System.out.println(bol1 ^ bol2);
}
}
 
Truth table for Logical NOT !: 
 
op1  Result 
TRUE  FALSE 
FALSE  TRUE 
Table 4.8: Truth table for Logical NOT 
 
The  logical  NOT  takes  in  one  argument,  wherein  that  argument  can  be  an  expression, 
variable or constant. 
 
Example: 
public class NOTsample
{
public static void main( String[] args )
{
boolean bol1 = true;
Training-workshop on Object-oriented Programming using Java
32 | P a g e

boolean bol2 = false;


System.out.println(!bol1);
System.out.println(!bol2);
}
}
 
Conditional Operator 
The  conditional  operator  ?:  is  a  ternary  operator.  This  means  that  it  takes  in  three 
arguments that together form a conditional expression. The structure of an expression using a 
conditional operator is, 
 
op1?op2:op3; 
 
wherein op1 is a boolean expression whose result must either be true or false. If op1 is 
true, op2 is the value returned. If it is false, then op3 is returned. 
Example: 
public class ConditionalOperatorSample
{
public static void main( String[] args )
{
String status = "";
int grade = 80;
status = (grade >= 60)?"Passed":"Failed";
System.out.println(status);
}
}
 
Operator Precedence 
 
Priority  Operator  Operation 
[ ]  Array Index 
1  ( )  Method Call 
.  Member Access 
++  Prefix or Posfix Increment 
‐‐  Prefix or Posfix Decrement 
+ ‐  Unary Plus, Minus 

!  Boolean (Logical) NOT 
type  Type Cast 
new  Object Creation 
Multiplication, Division, 
3  * / % 
Remainder 
+ ‐  Addition, Subtraction 

+  String Concatenation 
==  Equal to 

!=  Not Equal to 
6  &  Boolean Logical AND 
7  ^  Boolean Logical Exclusive OR 
8  |  Boolean Logical OR 
Training-workshop on Object-oriented Programming using Java
33 | P a g e

9  &&  Logical AND 
10  ||  Logical OR 
11  ?:  Conditional Operator 
12  =  Assignment 
Table 4.9: Java Operators operator precedence. 
 
Given a complicated expression: 
 
20%2*3+6/2+155‐11; 
 
we can re‐write the expression and place some parenthesis base on operator 
precedence: 
((20%2)*3)+(6/2)+155‐10; 
 
 
Test Yourself 
 
Declaring and printing variables 
Given  the  table  below,  declare  the  following  variables  with  the  corresponding  data 
types  and  initialization  values.  Output  to  the  screen  the  variable  names  together  with  the 
values. 
Variable name Data Type Initial value 
number integer 10 
letter character a 
result boolean true 
str String hello 
 
The following should be the expected screen output, 
Number = 10 
letter = a 
result = true 
str = hello 
 
 
Getting the average of three numbers 
Create a program that outputs the average of three numbers. Let the values of the three 
numbers be, 10, 20 and 45. The expected screen output is, 
number 1 = 10 
number 2 = 20 
number 3 = 45 
Average is = 25 
 
 
 
Training-workshop on Object-oriented Programming using Java
34 | P a g e

Output greatest value 
Given three numbers, write a program that outputs the number with the greatest value 
among the three. Use the conditional ?: operator that we have studied so far (HINT: You will 
need  to  use  two  sets  of  ?:  to  solve  this).  For  example,  given  the  numbers  10,  23  and  5,  your 
program should output, 
number 1 = 10 
number 2 = 23 
number 3 = 5 
The highest number is = 23 
 
Operator precedence 
Given  the  following  expressions,  re‐write  them  by  writing  some  parenthesis  based  on 
the sequence on how they will be evaluated. 
 
1. a / b ^ c ^ d – e + f – g * h + i 
2. 3 * 10 *2 / 15 – 2 + 4 ^ 2 ^ 2 
3. r ^ s * t / u – v + w ^ x – y++ 
 
**(Exercise items were taken from JEDI Introduction to Programming I Student’s Manual) 
 
 

Training-workshop on Object-oriented Programming using Java

You might also like