You are on page 1of 52

PROGRAMMING

LANGUAGES
FUNDAMENTALS
REPORTERS:

Jeezreel Mabolis
John Salre N. Largo
Cristian Jay Bueno
Marcelino Baldapan Jr.
Dave Aberte
3.1 Data Types and Naming Conventions in Java
Data Types in Java
* Used to represent the type of memory allocation.
* Used with variables and methods.
* These are fixed.
As the name suggests, data types specify the type of data that can be
stored inside variables in Java .
Primitive Data Types
Primitive data types are defined already by the programming
language. In Java there are 8 primitive data types.
Size Default Value Type of Value Stored

byte 1 byte 0 Integral

short 2 byte 0 Integral

int 4 byte 0 Integral

long 8 byte 0L Integral

char 2 byte '\u0000' Character

float 4 byte 0.0f Decimal

Double 8 byte 0.0d Decimal

boolean 1bit (till JDK 1.3 it uses 1 false True or False


byte)
Java is a statically-typed language. This means that all variables must be
declared before they can be used.
int speed;

Here, speed is a variable, and the data type of the variable is int.

The int data type determines that the speed variable can only contain
Integers.

There are 8 data types predefined in Java programming language, known


as primitive data types.

Note: In addition to primitive data types, there are also referenced types
(object type).
8 Primitive Data Types
1. boolean type

The boolean data type has two possible values, either true or false.
Default value: false.
They are usually used for true/false conditions.
Example 1: Java boolean data type

class Main {
public static void main(String[] args) {

boolean flag = true;


System.out.println(flag); // prints true
2. byte type

The byte data type can have values from -128 to 127 (8-bit signed
Two's complement integer).
If it's certain that the value of a variable will be within -128 to 127,
then it is used instead of int to save memory.
Default value: 0
Example 2: Java byte data type

class Main {
public static void main(String[] args) {

byte range;
range = 124;
System.out.println(range); // prints 124
3. short type
* The short data type in Java can have values from -32768 to 32767
(16-bit signed two's complement integer).
* If it's certain that the value of a variable will be within -32768 and
32767, then it is used instead of other integer data types (int, long).

Default value: 0
Example 3: Java short data type

class Main {
public static void main(String[] args) {

short temperature;
temperature = -200;
System.out.println(temperature); // prints -200
4. int type

* The int data type can have values from -2 31 to 2 31 -1 (32-bit signed
Two's complement integer).
* If you are using Java 8 or later, you can use an unsigned 32-bit
integer. This will have a minimum value of 0 and a maximum value
of 2 32 -1. To learn more, visit How to use the unsigned integer in java
8?

* Default value: 0
5. long type
* The long data type can have values from -2 63 to 2 63 -1 (64-bit signed
Two's complement integer).
* If you are using Java 8 or later, you can use an unsigned 64-bit
integer with a minimum value of 0 and a maximum value of 2 64 -1.
* Default value: 0
Example 5: Java long data type

class LongExample {
public static void main(String[] args) {

long range = -42332200000L;


System.out.println(range); // prints -42332200000
}
}

Notice, the use of L at the end of -42332200000. This represents that it's
an integral literal of the long type. You will learn about integral literals
later in this article.
6. double type
* The double data type is a double-precision 64-bit floating-point.
* It should never be used for precise values such as currency.
* Default value: 0.0 (0.0d)
Example 6: Java double data type

class Main {
public static void main(String[] args) {

double number = -42.3;


System.out.println(number); // prints -42.3
7. float type
* The float data type is a single-precision 32-bit floating-point.Learn
more about single-precision and double-precision floating-point if
you are interested.
* It should never be used for precise values such as currency.
* Default value: 0.0 (0.0f)

Example 7: Java float data type3

class Main {
public static void main(String[] args) {

float number = -42.3f;


System.out.println(number); // prints -42.3

Notice that, we have used -42.3f instead of -42.3in the above program.
It's because -42.3 is a double literal.
To tell the compiler to treat -42.3 as float rather than double, you need to
use f or F.
8. char type
* It's a 16-bit Unicode character.
* The minimum value of the char data type is '\u0000' (0) and the
maximum value of the is '\uffff.
* Default value: '\u0000'

Example 8: Java char data type

class Main {

public static void main(String[] args) {

char letter = '\u0051;

System.out.println(letter); // prints Q
String type
Java also provides support for character strings via java.lang.String
class.
Strings in Java are not primitive types. Instead, they are objects. For
example,

String myString = "Java Programming"


Here, myString is an object of the String class. To learn more, visit Java

Non-Primitive Data Types


Non-Primitive data types are defined by the user. They are
Class, Array, Interface and String.
Naming Conventions in Java
There are few naming conventions defined by the Java language that
should be kept in mind while giving name of a class, interface,
function, etc.

*Class and Interface: First letter of each word should be


uppercase. Ex: MyClassName.
* Method: First letter of first word is lowercase while
first letter of other words is uppercase. Ex: myMethodName().
* Package and Keyword: In lowercase. Ex: int, float, static,
etc.
3.2 Java Variable Types and Rules for Declaring Variables
Variable is nothing it is just the name of memory location.
While declaring variables we must follow rules given below.
Rules for Declaring Variables in Java
1. Variable name must bound with data type . It means while
declaring a variable we must specify its data type.
Ex: int x=10;
2. Reserve word or keywords cannot be taken as a variable
name.
3. C
supports 32 character long variable names while in Java the length of
variable
name can be infinite.
4. Nothing except 0-9, A-Z, a-z, _, $ can be used in variable
name.
5. Variable name must not start with numeric and special
characters are also not allowed.
Example:
intabc=7; (valid)
int _abc=8; (valid)
int abc8=9; (valid)
int 8abc=10 (invalid)
int $_abc=12; (valid)
int $_abc*=15; (invalid)
6. Variable name should be meaningful.
Example:
string i=”Raj”;
//valid but not meaningful
string name=”Raj”; //valid and meaningful
Note: Local variables must be initialized before first use.
class demo
{
public
static void main(String…s)
{
int
x; //must be initialized
System.out.println(x);
}
}
Java Variable Types
There are three types of variables in Java that are
instance, local and static.
1. Instance Variables
Instance variables are declared in a class, but outside any
method, constructor or block.

2. Local Variables
Local variables are declared in methods, constructors or
blocks. It must be initialized before first use.

3. Static Variables
Static variables are declared with the static keyword in a class, but
outside any method, constructor or block.
class A
3.3 Java Constant
As the name suggests, a constant is an entity in programming that is
immutable. In other words, the value that cannot be changed. In this
section, we will learn about Java constant and how to declare a
constant in Java.

What is constant?
Constant is a value that cannot be changed after assigning it. Java does
not directly support the constants. There is an alternative way to define
the constants in Java by using the non-access modifiers static and final.

How to declare constant in Java?


In Java , to declare any variable as constant, we
use static and final modifiers. It is also known as non-access modifiers.
According to the Java naming convention the identifier name must be in capital letters.
Why we use constants?
The use of constants in programming makes the program easy and
understandable which can be easily understood by others. It also affects
the performance because a constant variable is cached by both JVM and
the application.
Example 1: Declaring Constant as Private
Constant Example1.java
1. import java.util.Scanner;
2. public class ConstantExample1
3. {
4. //declaring constant
5. private static final double PRICE=2349.0
6. public static void main(String[] args)
7. {
8. int unit;
9. double total_bill;
10. System.out.print(Enter the number of units you have used:");
11. Scanner sc=new Scanner(System.in);
12. unit=sc.nextInt();
13. total_bill=PRICE*unit;
14. System.out.println(The total amount you have to deposit is; +total_bill);
15. }
16. }
Output:
Enter the amount of units you have used: 10
The total amount you have to deposit is: 2349.0
Example 2:
ConstantExample2.java
1. public class ConstantExample2
2. {
3. private static final double PRICE=2999;
4. public static void main(String[] args)
5. {
6. System.out.println("Old Price of Iron: "+PRICE);
7. ConstantExample obj = new ConstantExample();
8. obj.showPrice();
9. }
10. }
11. class ConstantExample
12. {
13. private static final double PRICE=3599;
14. void showPrice()
15. {
16. System.out.print("New Price of Iron: "+PRICE);
17. }
18. }
Output:
Old Price of Iron: 2999.0
New Price of Iron: 3599.0
Example 3: Declaring Constant as Public
In the following example, we have declared constant PI as public. Inside
the main() method, we have assigned 3.15 in the constant PI. Afterthat,
we have invoked the printValue() method. When we execute the
program, it shows an error cannot assign a value to the final variable PI.
ConstantExample3.java
1. public class ConstantExample3
2. {
3. //declaring PI as constant
4. public static final double PI= 3.14;
5. public static void main(String[] args)
6. {
7. printValue();
8. //trying to assign 3.15 in the constant PI
9. PI = 3.15;
10. printValue();
11. }
12. void printValue()
13. {
14. System.out.print("The value of PI cannot be changed to " + PI);
15. }
16. }
Output:
/ConstantExample3.java:9: error: cannot assign a value to final variable PI
PI = 3.15;
Using Enumeration (Enum) as Constant
* It is the same as the final variables.
* It is a list of constants.
* Java provides the enum keyword to define the enumeration.
* It defines a class type by making enumeration in the class that
may contain instance variables, methods, and constructors.

Example of Enumeration
1. public class EnumExample
2. {
3. //defining the enum
4. public enum Color {Red, Green, Blue, Purple, Black, White, Pink, Gray
}
5. public static void main(String[] args)
6. {
7. //traversing the enum
8. for (Color c : Color.values())
9. System.out.println(c);
10. }
11. }
Output:
RED BLACK
GREEN WHITE
BLUE PINK
PURPLE GRAY
3.4 Java Class Attributes and Methods
Java Class Attributes
In the previous chapter, we used the term "variable" for x in the example
(as shown below). It is actually an attribute of the class. Or you could
say that class attributes are variables within a class:
Example
Create a class called "Main" with two attributes: x and y:
public class Main {
int x = 5;
int y = 3;
Another term for class attributes is fields.
Accessing Attributes
You can access attributes by creating an object of the class, and by using
the dot syntax (.):

The following example will create an object of the Main class, with the
name myObj. We use the x attribute on the object to print its value:

Example
Create an object called "myObj" and print the value of x:
public class Main {
int x = 5;

public static void main(String[] args) {


Main myObj = new Main();
System.out.println(myObj.x);
Java Methods
A method is a block of code which only runs when it is called.
You can pass data, known as parameters, into a method.
Methods are used to perform certain actions, and they are also known as
functions.
Why use methods? To reuse code: define the code once, and use it many
times.

Create a Method
A method must be declared within a class. It is defined with the name of
the method, followed by parentheses (). Java provides some pre-defined
methods, such as System.out.println(), but you can also create your own
methods to perform certain actions:
A method must be declared within a class. It is defined with the name of
the method, followed by parentheses (). Java provides some pre-defined
methods, such as System.out.println(), but you can also create your own
methods to perform certain actions:

Example
Create a method inside Main:
public class Main {
static void myMethod() {
// code to be executed

Example Explained
* myMethod() is the name of the method
* means that the method belongs to the Main class and not an
object of the Main class. You will learn more about objects and
how to access methods through objects later in this tutorial.
* void means that this method does not have a return value. You
will learn more about return values later in this chapter
Call a Method
To call a method in Java, write the method's name followed by two
parentheses () and a semicolon;
In the following example, myMethod() is used to print a text (the action),
when it is called:

Example
Inside main, call the myMethod() method:
public class Main {
static void myMethod() {
System.out.println("I just got executed!");
public static void main(String[] args) {
myMethod();

// Outputs "I just got executed!"


I just got executed!
Java Method Parameters

Parameters and Arguments


Information can be passed to methods as parameter. Parameters act as
variables inside the method.
Parameters are specified after the method name, inside the parentheses.
You can add as many parameters as you want, just separate them with a
comma.
The following example has a method that takes a String called fname as
parameter. When the method is called, we pass along a first name, which
is used inside the method to print the full name:
Example
public class Main {
static void myMethod(String fname) {
System.out.println(fname + " Refsnes");
}

public static void main(String[] args) {


myMethod("Liam");
myMethod(";Jenny");
myMethod(";Anja");
}
}
// Liam Refsnes
// Jenny Refsnes
// Anja Refsnes
Liam Refsnes
Jenny Refsnes
Anja Refsnes
3.5 Java Constructors
A constructor in Java is a special method that is used to initialize
objects. The constructor is called when an object of a class is created. It
can be used to set initial values for object attributes:
Example
Create a constructor:
// Create a Main class
public class Main {
int x; // Create a class attribute
// Create a class constructor for the Main class
public Main() {
x = 5; // Set the initial value for the class attribute x
}
public static void main(String[] args) {
Main myObj = new Main(); // Create an object of class Main (This
will call the constructor)
System.out.println(myObj.x); // Print the value of x
}
}
// Outputs 5
3.6 Java Control and Iterative Statements

There are 2 types of control statements in Java. One category is of


conditional statements that are used for checking condition. The
second category belongs to Iterative statements (loops).
1. Conditional Statements
As for as conditional statements are concerned, there are two such
statements in Java i.e. if statement, and switch statement.
If Statement
This statement consists of 3 things: if keyword, a condition, and a block
of statements.
if (condition)
{
… (if block)
}
When control comes to if statement then first of all condition is
evaluated. Now if its output comes out true then the if-block (set of
statements) would be executed. Otherwise, the control would be
transferred to the immediate next statement to if-statement.
For example,
int x =7;
if(x>5)
{
System.out.println(X is greater than 5);
}
As 7 is greater than 5 so the if-block statement System.out.println(X is
greater than 5); would be executed.
If- Else Statement
There is also if-else statement (variation of if statement). In this case if if-
statement’s condition becomes true then if-block would be executed.
Otherwise else-block would be executed.
if (condition)
{
…(if block)
}
else
{
…(else block)
}
Nested If

You can put If with-in an If. This is called Nested If.


For example,
int a = 10;
int b = 8;
int c = 9;
if(a>b)
{
if(a>c)
{
System.out.println(a is greater than b & c);
}
}
else
{
System.out.println(a is lesser than b );
}
2. Iterative Statements

There are 3 such statements in Java i.e. while statement, Do statement,


for statement.
While Statement
It is used to execute a set of statements for more than one time till the
condition remains true.
while (condition)
{
… (while block)
}
First of all condition is being checked and if comes out true then while-
block would be executed. Now after the execution of while block
statements, the while-condition is again checked and if is true then while
block will be executed and so on. Now when while-condition becomes
false then control is transferred to the immediate statement after while
statement.
For example,
int k = 36;
while(k>30)
{
System.out.println("k>30");
k = k-1;
}
Do Statement
The Do statement (also called Do-While statement) works very similar to
While statement except that termination condition is at end.
do
{
… (do block)
} while (condition);
For Statement
The for statement is used to iterate a set of statements certain number of
times.
for (initialization; condition; update)
{
… (for block)
}
for statement has three parts: initialization is used to initialize a variable,
3.7 Characters and String in Java
We interact with each other through words and sentences. So, there must be some way by which Java should also
play with these words or sentences. And that is exactly what we are going to do in this chapter.
Characters
You all must be knowing about characters. In Java, the data type to store
characters is char.
In Java, characters are represented using Unicode. Unicode is an
international character set representing all the characters.
In Java, char ranges from 0 to 65,535.
Characters are always written within ' '
Let's see an example.
class C1{
public static void main(String[] args){
char c1, c2;
c1 = 'd'
c2 = 88;
System.out.println("c1 ="+ c1 + ",c2 ="
Strings
We can think of a string as a collection of characters. In other words, it is an array of characters,
like Robin is a string. In Java programming, strings are objects. Before understanding it, let's
first see how to declare a string.
String s = "Hello";
We can also declare it as
String s = {'h','e','I','l','o'}
Here, s is a string having the value Hello. s is an object of the
class String.
Thus 's' is an String object having its value "Hello".
As stated that string is an array of characters, in the second example we
are declaring string as an array of characters.
We can also create String objects using the new keyword. Here, the new
keyword is used to create an object 's' of the class String. The following
codes are used to create a String object 's' having its value "Hello".
Difference between equals() method and ==
Whenever we create a new object, it is allocated some location in the memory.For example, if we write
String s1 = new String("Welcome");
Here, object s1 is created and given some location in the memory. Its
value is assigned as "Welcome".
When we create another object s2, it is also given some location in the
memory( since it is also a new object). Its value is also assigned as
"Welcome".
String s2 = new String("Welcome");
Thus, we have two objects with different memory locations and the same
value "Welcome".
== operator compares two objects

Though both the objects are different, but since their values are same, so
the condition (s1.equals(s2)) is true.
3.8 Java Arrays

An array is a collection of similar types of data.


For example, if we want to store the names of 100 people then we can
create an array of the string type that can store 100 names.

String[] array = new String[100];

Here, the above array cannot store more than 100 names.
The number of values in a Java array is always fixed.
How to declare an array in Java?
In Java, here is how we can declare an array.

dataType[] arrayName;

* dataType - it can be primitive data types like int, char, double, byte,
etc. or Java objects
* arrayName - it is an identifier
For example,

double[] data;

Here, data is an array that can hold values of type double.


But, how many elements can array this hold?
Good question! To define the number of elements that an array can hold,
we have to allocate memory for the array in Java. For example,
// declare an array
double[] data;

// allocate memory
data = new double[10];

Here, the array can store 10 elements. We can also say that the size or
length of the array is 10.
In Java, we can declare and allocate memory of an array in one single
statement. For example,

double[] data = new double[10];


How to Initialize Arrays in Java?
In Java, we can initialize arrays during declaration. For example,

//declare and initialize and array


int[] age = {12, 4, 5, 2, 5};

Here, we have created an array named age and initialized it with the
values inside the curly brackets.
Note that we have not provided the size of the array. In this case,
the Java compiler automatically specifies the size by counting the
number of elements in the array (i.e. 5).
In the Java array, each memory location is associated with a number.
The number is known as an array index. We can also initialize arrays
in Java, using the index number. For example,

// declare an array
int[] age = new int[5];

// initialize array
age[0] = 12;
age[1] = 4;
age[2] = 5;
Java Arrays initialization
Note:
* Array indices always start from 0. That is, the first element of an
array is at index 0.
* If the size of an array is n, then the last element of the array will be at
index n-1.
How to Access Elements of an Array in Java?
We can access the element of an array using the index number. Here is
the syntax for accessing elements of an array,

// access array elements


array[index]

Let's see an example of accessing array elements using index numbers.


Example: Access Array Elements

class Main {
public static void main(String[] args) {

// create an array
int[] age = {12, 4, 5, 2, 5};

// access each array elements


System.out.println(Accessing Elements of Array);
System.out.println(First Element: " + age[0]);
System.out.println(Second Element: " + age[1]);
System.out.println(Third Element: " + age[2]);
System.out.println(Fourth Element: " + age[3]);
System.out.println(Fifth Element: " + age[4]);
}

You might also like