Vous êtes sur la page 1sur 52

Java

Programming
Fundamentals

by: JAYFEE D. RAMOS


Objectives
 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 using the
concepts learned in this chapter
Tools you will need:
For performing the examples discussed, you will need a at least
Pentium 200-MHz computer with a minimum of 64 MB of RAM
(128 MB of RAM recommended).

You also will need the following software's:


Linux 7.1 or Windows 95/98/2000/XP/7/10 operating system.
Java JDK
Microsoft Notepad or any other text editor (Netbeans)
Basic Syntax:
about Java programs, it is very important to
keep in mind the following points.
• Case Sensitivity - Java is case sensitive, which
means identifier Hello and hello would have
different meaning in Java.
• 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()
• 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..
When saving the file, you should save it using the class name (Remember Java is case
sensitive) and append '.java' to the end of the name (if the file name and the class name
do not match your program will not compile).
Java Comments
are notes written to a code for documentation
purposes. Those text are not part of the program
and does not affect the flow of the program.
Java supports three types of comments:
 C++-style single line comments,
 C-style multiline comments
 special javadoc comments.
C++-Style Comments
C++ Style comments starts with //. All the text after //
are treated as comments. For
example,

// This is a C++ style or single line comments


C-Style Comments
C-style comments or also called multiline comments
starts with a /* and ends with a */. All text in between
the two delimiters are treated as comments. Unlike C++
style comments, it can span multiple lines. For example,
/* this is an example of a
C style or multiline comments */
Special Javadoc Comments
Special Javadoc comments are used for generating an
HTML documentation for your Java programs. For
example,
/**
This is an example of special java doc comments used for \n
generating an html documentation. It uses tags like:
@author Florence Balagtas
@version 1.2
*/
Java Statements and blocks
A statement is one or more lines of code terminated by
a semicolon. An example of a single statement is,

System.out.println(“Hello world”);
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. An
example of a block is,
public static void main( String[] args ){
System.out.println("Hello");
System.out.println("world");
}
Java Identifiers
Your Subtitle
• Identifiers are tokens that represent names of variables,
methods, classes, etc.
– Examples of identifiers are: Hello, main, System, out.
• Java identifiers are case-sensitive. This means that the
identifier: Hello is not the same as hello. Identifiers
must begin with either a letter, an underscore “_”, or a
dollar sign “$”. Letters may be lower or upper case.
• Identifiers cannot use Java keywords like class, public,
void, etc.
All Java components require names. Names used for
classes, variables and methods are called identifiers.
In Java, there are several points to remember about
identifiers. They are as follows:
 All identifiers should begin with a letter (A to Z or a to z),
currency character ($) or an underscore (_).
 After the first character identifiers can have any
combination of characters.
 A key word cannot be used as an identifier.
 Most importantly identifiers are case sensitive.
 Examples of legal identifiers: age, $salary, _value, __1_value
 Examples of illegal identifiers: 123abc, -salary
Java 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.
BASIC DATA TYPES
Your Subtitle
Variables are nothing but reserved memory locations to
store values.
This means that when you create a variable you reserve
some space in memory. Based on the data type of a variable,
the operating system allocates memory and decides what
can be stored in the reserved memory. Therefore, by
assigning different data types to variables, you can store
integers, decimals, or characters in these variables.

There are two data types available in Java:


– Primitive Data Types
– Reference/Object Data Types
Primitive Data Types:
byte:
 Byte data type is an 8-bit signed two's complement integer.
 Minimum value is -128 (-2^7)
 Maximum value is 127 (inclusive)(2^7 -1)
 Default value is 0
 Byte data type is used to save space in large arrays, mainly in place of
integers,
since a byte is four times smaller than an int.
 Example: byte a = 100 , byte b = -50
Primitive Data Types:
short:
 Short data type is a 16-bit signed two's complement integer.
 Minimum value is -32,768 (-2^15)
 Maximum value is 32,767 (inclusive) (2^15 -1)
 Short data type can also be used to save memory as byte data type. A
short is 2 times smaller than an int.
 Default value is 0.
 Example: short s = 10000, short r = -20000
Primitive Data Types:
int:
 Int data type is a 32-bit signed two's complement integer.
 Minimum value is - 2,147,483,648.(-2^31)
 Maximum value is 2,147,483,647(inclusive).(2^31 -1)
 Int is generally used as the default data type for integral values unless
there is a
concern about memory.
 The default value is 0.
 Example: int a = 100000, int b = -200000
Primitive Data Types:
long:
 Long data type is a 64-bit signed two's complement integer.
 Minimum value is -9,223,372,036,854,775,808.(-2^63)
 Maximum value is 9,223,372,036,854,775,807 (inclusive). (2^63 -1)
 This type is used when a wider range than int is needed.
 Default value is 0L.
 Example: long a = 100000L, int b = -200000L
Primitive Data Types:
float:
 Float data type is a single-precision 32-bit IEEE 754 floating point.
 Float is mainly used to save memory in large arrays of floating point
numbers.
 Default value is 0.0f.
 Float data type is never used for precise values such as currency.
 Example: float f1 = 234.5f
Primitive Data Types:
double:
 double data type is a double-precision 64-bit IEEE 754 floating point.
 This data type is generally used as the default data type for decimal
values, generally the default choice.
 Double data type should never be used for precise values such as
currency.
 Default value is 0.0d.
 Example: double d1 = 123.4
Primitive Data Types:
char:
 char data type is a single 16-bit Unicode character.
 Minimum value is '\u0000' (or 0).
 Maximum value is '\uffff' (or 65,535 inclusive).
 Char data type is used to store any character.
 Example: char letterA ='A'
Reference Data Types:
Reference variables are created using defined
constructors of the classes. They are used to access
objects. These variables are declared to be of a specific
type that cannot be changed.
• For example, Employee, Puppy etc.
• Class objects, and various type of array variables come under
reference data type.
• Default value of any reference variable is null.
• A reference variable can be used to refer to any object of the
declared type or any compatible type.
Example: Animal animal = new Animal("giraffe");
Variables
- is an item of data used to store state of objects.
- a variable has a data type and a name. The data
type indicates the type of value that the variable
can hold.
- variable name must follow rules for identifiers.
Declaring and Initializing Variables
To declare a variable is as follows,
<data type> <name> [=initial value];

Note: Values enclosed in <> are required values, while


those values enclosed in [] are optional.
Here is a sample program that declares and initializes
some variables,
public class VariableSamples
{
public static void main( String[] args ){
//declare a data type with variable name
// result and boolean data type
boolean result;
//declare a data type with variable name
// option and char data type
char option;
option = 'C'; //assign 'C' to option
//declare a data type with variable name
//grade, double data type and initialized
//to 0.0
double grade = 0.0;
}
}
Coding Guidelines:
1. It always good to initialize your variables as you declare them.
2. Use descriptive names for your variables. Like for example, if
you want to have a variable that contains a grade for a student,
name it as, grade and not just some random letters you choose.
3. Declare one variable per line of code. For example, the variable
declarations,
– double exam=0;
– double quiz=10;
– double grade = 0;
is preferred over the declaration,
– double exam=0, quiz=10, grade=0;
Outputting Variable Data
In order to output the value of a certain variable, we can use the following
commands,
System.out.println()
System.out.print()

Here's a sample program,


public class OutputVariable {
public static void main( String[] args ){
int value = 10;
char x;
x = ‘A’;
System.out.println( value );
System.out.println( “The value of x=“ + x );
}
}

The program will output the following text on screen,


10
The value of x=A
System.out.println() vs. System.out.print()
What is the difference between the commands System.out.println() and
System.out.print()? The first one appends a newline at the end of the data to
output, while the latter doesn't. Consider the statements,

System.out.print("Hello ");
System.out.print("world!");

These statements will output the following on the screen,


Hello world!

Now consider the following statements,


System.out.println("Hello ");
System.out.println("world!");
These statements will output the following on the screen,
Hello
world!
Find out the statement if it is valid or
not valid:
1. int if = 100; 8. float 123abc = 88;
2. boolean –password = True; 9. short _salary=39;
3. byte student = 499001; 10. boolean enterData = 81;
4. system.out.println("Hello"); 11. *\ sample comment *\
5. Public Void myMethodName() 12. system.out.println(abc);
6. class myFirstJavaClass{ 13. int income;
} 14. double grade = true;
7. \\This is a comment 15. int $gross00 = -300.33;
Operators
- There are arithmetic operators, relational
operators, logical operators and conditional
operators.
The Arithmetic Operators:
Arithmetic operators are used in mathematical expressions in the same way
that they are used in algebra. The following table lists the arithmetic operators:
Assume integer variable A holds 10 and variable B holds 20, then:
The Relational Operators:
There are following relational operators supported by Java language
Assume variable A holds 10 and variable B holds 20, then:
The Logical Operators:
The following table lists the logical operators:
Assume Boolean variables A holds true and variable B holds false, then:
The Assignment Operators:
There are following assignment operators supported by Java language:
Operator precedence defines the compiler’s order of evaluation of operators
so as to come up with an unambiguous result.

Given a complicated expression,


6%2*5+4/2+88-10
we can re-write the expression and place some parenthesis base on operator
precedence,
((6%2)*5)+(4/2)+88-10;
Coding Guidelines
To avoid confusion in evaluating mathematical operations, keep your expressions simple and use
parenthesis.
Find out the value of the variable / expression:
Given variables:
int student = 30;
int teacher = 4;
Boolean
Example Program

class Example1 {
public static void main(String args[]) {
int var1; // this declares a variable
int var2; // this declares another variable
var1 = 1024; // this assigns 1024 to var1
System.out.println("var1 contains " + var1);
var2 = var1 / 2;
System.out.print("var2 contains var1 / 2: ");
System.out.println(var2);
}
}
Example Program

class Example2 {
public static void main(String args[]) {
int iresult, irem;
double dresult, drem;
iresult = 10 / 3;
irem = 10 % 3;
dresult = 10.0 / 3.0;
drem = 10.0 % 3.0;
System.out.println("Result and remainder of 10 / 3: " + iresult + " " + irem);
System.out.println("Result and remainder of 10.0 / 3.0: " + dresult + " " +
drem); }
}
Example Program
class Example3{
public static void main(String args[]) {
int var; // this declares an int variable
double x; // this declares a floating-point variable
var = 10; // assign var the value 10
x = 10.0; // assign x the value 10.0
System.out.println("Original value of var: " + var);
System.out.println("Original value of x: " + x);
System.out.println(); // print a blank line
// now, divide both by 4
var = var / 4;
x = x / 4;
System.out.println("var after division: " + var);
System.out.println("x after division: " + x);
}
}
Example Program
public class Example4{
public static void main(String args[]) {
int age = 0;
age = age + 7;
System.out.println("Puppy age is : " + age);
}
}
Group Activity: SOLVE – GROUP –SHARE
Direction:
1. The class will be divided into groups
2. Each group shall choose a leader, a writer, a reporter
3. Answer the following exercises individually and answer the following
question as a group.
- How did you solve this exercises?
- What are the error occurred during solving this exercises?
4. You will be given ___ to do this exercises and five minutes will be given to
each group to report.
Exercise
1. 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.

The following should be the expected screen output,


Number = 10
letter = a
result = true
str = hello
Exercise
2. 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
Exercise
3. Product of four integers
Write a program that calculates and prints the product of three
integers.

Vous aimerez peut-être aussi