You are on page 1of 16

LESSON 2

Introduction to Java Programming

Objectives:
 Understand Java programming language
 Discuss history of Java and Java Development
 Understand Variables and Data types

Introduction
Java is a programming language. It is used to develop web
application, desktop application, mobile application and more. This lesson
will discuss how Java develop to use in technology trends.

Activity
1. What application is the most trend in this generation?
2. Any Idea about computer programming?
3. Were you able to create a program?

Analysis
1. Why do you think java is the most programming language now a
days?
2. What process can you create in programming?

Abstraction
a. The Basic Java Application
Java Applications with the Java class and method syntax in hand, we
can design a Java program. Java applications consist of one or more
classes that define data and behavior. Java applications are translated
into a distilled format by a Java compiler. This distilled format is nothing
more than a linear sequence of operation-operand(s) tuples:

What is Java?
Java is a popular programming language, created in 1995, owned
by Oracle, and Java can run 3 billion Devices and more

Java is used for:

 Web servers and application servers


 Games
 Database connection
 Mobile applications (especially Android apps)
 Desktop applications
 Web applications
 And much, much more

Why we use Java?

 Java can works on different platforms (Windows, Mac, Linux,


Raspberry Pi, etc.)
 Java is one of the most popular programming language in the world
 Java is easy to learn and simple to use
 Java is an open-source and free
 Java can secure, fast and powerful
 Java has a huge community support (tens of millions of developers)
 Java is an object oriented language which gives a clear structure to
programs and allows code to be reused, lowering development costs
 As Java is close to C++ and C#, it makes it easy for programmers
to switch to Java or vice versa

Sample Code of Java

In Java, every application begins with a class name, and that class
name must have the same filename.

For example, we create our first java program, called


MyFirstProgram.java. The output of your program should contain a
“HELLO WORLD” message.

MyFirstProgram.java

public class MyFirstProgram {


public static void main(String[] args) {
System.out.println(“Hello World”);
}
}

Output: Hello World


Java Syntax
Every code line that runs in Java must be inside a class. In our
example, we named the class “MyFirstProgram”. Always remember that a
class should always start with an uppercase first letter.
Note: Java is case-sensitive: " MyFirstProgram” and "myfirstprogram" has
different meaning.
The name of the java file must match the class name. When saving
the file, save it using the class name and add ".java" to the end of the
filename or if you use any software application like eclipse and netbeans no
need to put .java as your extension. To run your program make sure that
your Java is properly installed.

b. Variables & Data Types


A Java variable can contain a data value in a memory allocation.
While your java Program is executed a variable can holds the value.
A variables is assign together with your data types. There are three
types of variables in java: LOCAL, INSTANCE and STATIC.
Variable is a reserved name where area allocated in memory. In
other words, it is name of memory location. Variable term it is a
combination of “vary + able” that means its value can be changed.
For example: int a=20;
In this example, our variable is letter a.
Reminder: You can use any variable if you want.

Three Types of Variables


1. Local Variable- A variable declared inside the body of the method
is called local variable. You can use this variable only within that
method and the other methods in the class aren’t even aware that
the variable exists.
A local variable cannot be defined with “static” keyword.
2. Instance Variable- A variable declared inside the class but outside
the body of the method, it is called instance variable. It is not
declared as static.
It is called instance variable because its value is instance
specific and it is not shared among instance.
3. Static Variables- A variable which is declared as a static is called
static variable. It cannot be local. You can create a single copy of
static variable and share among all the instances of the class.
Memory allocation for static variable happened only once when the
class is loaded in the memory.

Here is the example to understand the three types of Variable in


Java.

class A (
int x= 20; // instance variable
static int y=10; // static variable
void method(){
int z=5; // local variable
}
}

Data Types
A data type can specify the different values and sizes that can be
assigned in the variable. There are two type of data types first is the
primitive and second is the non- primitive data types in java.

So what is primitive and non- primitive data types?


Primitive data types – the primitive data types includes the following

Data Definition Default Default


type value size
It is used to store only two false 1 bit
boolean possible values the true and
false. This data type is simple to
use it used answerable True or
False.
char This char data types is used to \’u0000’ 2 byte
store characters.
Char use this
because java
uses Unicode
not ASCII
code system.
byte byte data type is used to save 0 1 byte
large memory in large arrays.

byte data types is 4 times


smaller than an integer .You can
use byte data types place of
“int” data types.
short short data types is a 16 bit 0 2 byte
signed two’s compliment
integer.

You can also use short data type


to save your memory because
short data type is 2 times
smaller than an integer.
int int data types is a 16 bit signed 0 4 byte
two’s compliment integer.

This data type is use as a default


value for integral values.

long The use of long data types is 0L 8 byte


when you need a range values
more than those provided by int.
float float is recommended to use 0.0f 4 byte
than double data types. float
data types in decimal point
numbers.
double The double data types used for 0.0d 8 byte
decimal values same with float
data types
This is a boolean sample
public class MyFirstProgram { Output:
public static void main(String[] args) {
boolean a=true; the value is: true
boolean b=false;
System.out.println(“the value is:”+ a);
the value is: false
System.out.println(“the value is:”+ b); when you want to add statement
}
before the value just use the + signed
}
to add your statement and the value.
This is the example using char
data types.
public class MyFirstProgram { Output:
public static void main(String[] args) {
The letter is: J
char letter=’J’;
System.out.println(“the letter is:” Always remember when you use a
+letter); char data types use only a single
} quote
}

public class MyFirstProgram { The example of a byte data types


public static void Output: 24
main(String[] args) { The example of a short data types
byte a=24; Output: 240
short Num=240; The example of a int data types
int x=1222; Output: 1222
long z= 10000000L; The example of a long data types
float b=2.50f; Output: 10000000
double c=3.50d; The example of a float data types

Output: 2.50
System.out.println(a); The example of a double data
System.out.println(Num); types

System.out.println(x); Output: 3.50

System.out.println(z);
System.out.println(b);
System.out.println(c);

}
Non–Primitive Data Types
Non-primitive Data types are not actually defined by the
programming language but these data types are created by the
programmer.
Non-Primitive Data types it refers to the objects and hence they called
it reference types.
Here are the Example of Non- primitive Data Types

Strings
It refers to an object. String object has methods that are used to
perform certain operations on strings.
These java.lang.String class it is used for creating a String object.
Array
Java in Array are the homogeneous data Structures implemented in
Java as Objects. An array can store one or more values of a specific data
types and provide indexed access store the same. Where a specific element
in an array is accessed by its index.
Classes
These is a blueprint in Java. A blueprint which includes all your data.
A Class contains fields(variables) and methods to describe the behavior of
an object.
Interfaces
Interface is like a class, where an interface can have method and
variables, but the methods declared in interface are by default abstract
(inly method signature, no body).
C. Java Operators

Java Operators
It is used to perform operations on variables and values.
Java divides the operators into the following groups:
 Arithmetic Operators
 Assignment Operators
 Comparison Operators
 Logical Operators
 Bitwise Operators
Arithmetic Operators
These operators are used to perform the common mathematical
operations.
Assume that we have a two variable x & y which x =4, y= 2;

Operator Description Example


+ Adds together two values x+y
(Addition) 4+2 = 6
- Subtract one value from x-y
(Subtraction) another 4-2= 2
* Multiplies two values x*y
(Multiplication) 4*2= 8
/ Divides one value by x/y
(Division) another 4/2 = 2
% Returns the division Let x=5, y=2
(Modulus) remainder x%y
5%2 = 1
Answer is 1. Why?
Since the remainder
of 5%2 is 1.
++ Increases the value of a ++x or x++
(Increment) variable by 1 1+x or x+1
-- Decrease the value of --x or x—
(Decrement) variable by 1 1-x or x-1
Assignment Operators
Assignment Operators are used to assign values to variable.
int x =2;
x + = 4; answer is: 6.
This is an example of additional assignment operator (=+) adds a value
to a variable.

Operator Description Example

Simple assignment operator. Assigns C=A+B


values from right side operands to left side will assign
=
operand. value of A
+ B into C

Add AND assignment operator. It adds C += A is


right operand to the left operand and equivalent
+=
assign the result to left operand. to C = C +
A

Subtract AND assignment operator. It C -= A is


subtracts right operand from the left equivalent
-=
operand and assign the result to left to C = C –
operand. A

Multiply AND assignment operator. It C *= A is


multiplies right operand with the left equivalent
*=
operand and assign the result to left to C = C *
operand. A

/= Divide AND assignment operator. It C /= A is


divides left operand with the right operand equivalent
and assign the result to left operand. to C = C /
A
Modulus AND assignment operator. It C %= A is
takes modulus using two operands and equivalent
%=
assign the result to left operand. to C = C
%A

C <<= 2
is same as
<<= Left shift AND assignment operator.
C = C <<
2

C >>= 2
is same as
>>= Right shift AND assignment operator.
C = C >>
2

C &= 2 is
&= Bitwise AND assignment operator. same as C
=C&2

bitwise exclusive OR and assignment C ^= 2 is


^= operator. same as C
=C^2

bitwise inclusive OR and assignment C |= 2 is


|= operator. same as C
=C|2

Comparison Operators
Comparison operators are used to compare two values.
Let x= 4, y =1;

Operator Example
== x==y
(Equal to) 4==1? The answer is false why?
It returns false because 4 is not equal to 3
!= x!=y
(Not Equal) 4! =1? Answer is true why? It returns true
because 4 in not equal to 1
> x>y
(Greater than) 4>1= True.
True because 4 is greater than 1
< x<y
(Less than) 4<1= False
Because 4 is not less than to 1
>= x>=y
(Greater than or equal x>y
to) 4>1= True.
True because 4 is greater than or equal to
1
<= x<=y
(Less than or equal to) 4<1= False
Because 4 is not less than or equal to 1

Logical Operators
Logical operators are used to determine the logic between variables
or values.

Operator Description Example


&& Returns true if both Let x=3;
(Logical and) statements are true x > 2 && x <5
Answer is true. Why?
Because 3 is greater
than to 2 and 3 is less
than to 5.
|| Returns true if one of x> 4 || x <5
(Logical or) the statements is true Answer is True. Why?
Because one of the
statement is true.
where 3 is not greater
than to 4 is not true
but 3 less than to 5 is
a true statement.
! Reverse the result, Let x=3;
(Logical not) returns false if the (!(x > 2 && x <5))
result is true Answer is false. Why?
Because! (not) is
used to reverse the
result.
Bitwise Operators
Java defines several bitwise operators, which can be applied to the
integer types, long, int, short, char, and byte.
Bitwise operator works on bits and performs bit-by-bit operation. Assume
if a = 60 and b = 13; now in binary format they will be as follows −
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
The following table lists the bitwise operators −
Assume integer variable A holds 60 and variable B holds 13 then

Operator Description Example

Binary AND Operator copies a bit (A & B) will give


& (bitwise
to the result if it exists in both 12 which is
and)
operands. 0000 1100

(A | B) will give
Binary OR Operator copies a bit if
| (bitwise or) 61 which is
it exists in either operand.
0011 1101

Binary XOR Operator copies the (A ^ B) will give


^ (bitwise
bit if it is set in one operand but 49 which is
XOR)
not both. 0011 0001

(~A ) will give -


Binary Ones Complement
~ (bitwise 61 which is
Operator is unary and has the
compliment) 1100 0011 in 2's
effect of 'flipping' bits.
complement
form due to a
signed binary
number.

Binary Left Shift Operator. The left


A << 2 will give
operands value is moved left by
<< (left shift) 240 which is
the number of bits specified by
1111 0000
the right operand.

Binary Right Shift Operator. The


A >> 2 will give
>> (right left operands value is moved right
15 which is
shift) by the number of bits specified by
1111
the right operand.

Shift right zero fill operator. The


left operands value is moved right A >>>2 will
>>> (zero fill
by the number of bits specified by give 15 which is
right shift)
the right operand and shifted 0000 1111
values are filled up with zeros.

Java User Input (Scanner)


Scanner is a class is used to get user input, and it is found in the
java.util package.
How to use this Scanner?
To use these Scanner class, create an object of the class and use
any of the variable methods found in the Scanner class documentation.
Types of Input types

Methods Description
nextBoolean() Reads a boolean value from the user
nextByte() Reads a byte value from the user
nextDouble() Reads a double value from the user
nextFloat() Reads a float value from the user
nextInt() Reads a int value from the user
nextLine() Reads a String value from the user
nextLong() Reads a long value from the user
nextShort() Reads a short value from the user

Output /Display
Difference between println(), print() and printf()
 print() - It prints string inside the quotes.
 println() - It prints string inside the quotes similar like print()
method. Then the cursor moves to the beginning of the next line.
 printf() - Tt provides string formatting (similar to printf in C/C++
programming).
Example: Display “Hello World” program.

public class MyFirstJavaProgram {

/* This is my first java program.

* This will print 'Hello World' as the output

*/

public static void main(String []args) {

System.out.println("Hello World"); // prints Hello World

public − scope of the class. Public means visible to all.


class − declares the class in java.
/* */ − Comments section.
static − marks element as static so that it can be accessed without
creating the object.
void − return type of the function. void refers to nothing.
String[] args − command line arguments.
System.out.println() − print the statement on the console.
public static void main() − the main method is startup method of java
program. It is visible to all, it is static, so no object is required, and it is
not returning any value.
Example Program Input and Output

import java.util.Scanner;

class MySecondJavaProgram {

public static void main(String[] args) {

Scanner myObj = new Scanner(System.in);

System.out.println("Enter name, age and salary:");

// String input

String name = myObj.nextLine();

// Numerical input

int age = myObj.nextInt();

double salary = myObj.nextDouble();

// Output input by user

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

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

System.out.println("Salary: " + salary);

}
Application: Analyze the problem below.
Encoding:
1. Create a program that will accept and display your name, age,
address and Contact number.

2. Create a program that will compute the sum, product and


difference of three number.

3. Convert Fahrenheit to Celsius


Debugging:
 Sava your file as JavaQuiz.java
 Display HELLO Love Goodbye!

public class MyFirstJavaProgram {

public static void main(String []args) {

System.out.println("Hello Love");

You might also like