Chapter Two
Chapter Two
Chapter Two
WOLKITE UNIVERSITY
CHAPTER
TWO
Basics in Java Programming
YEAR: 2016
2
Structure of Java Program
General Syntax
class Classname
{
Data;
Methods()
{
Statements;
}
}
3
Simple Java Program
Example 1.
}
4
Cont..
Class File
Method 1
Put a class in a source fi le. statement
Put methods in a class. Method 2
statement
Put statements in a method statement
Source File
5
Class
6
Cont..
Method
7
Cont..
Statements
Cont.… 8
Example 2
class FirstProgram
{
public static void main(String[] args)
{
System.out.println("This is my first program");
}
}
Cont.… 9
The name of the class is made of alphabetical characters and digits without spaces, the
first character must be alphabetical.
The line “public static void main (String[] args )”‖ shows where the program will start
running.
Java system handling begins from the main() function, which is a required piece of each
Java program.
The JVM starts running any program by executing this method first.
The main method in “FirstProgram.java”‖ consists of a single statement
It deals with editing or writing a java source code program using different
editor platforms.
Examples of IDEs: Apache NetBeans, Eclipse, Notepad++, JCreator etc.
Java source code files are given a name ending with.java extension to indicate
that the file contains a java source code.
Cont.… 15
A java compiler is a program that takes the source code file and compiles it into a platform-
independent java file.
The java compiler translates Java source code into bytecodes that represent the tasks to
execute in the execution phase.
In this phase you use the command javac( the Java compiler) to compile a program.
For example to compile the previous java program in example 2: FirstProgram.java
You would type javac FirstProgram.java
If the program is compiled, the compiler produces a .class file called FirstProgram.class
Cont.… 17
In this phase the JVM places the program in memory to execute it, this is known as
loading
The JVM class loader takes the .class files containing the program’s bytecodes and
transfers them to primary memory.
The class loader also loads any of the .class files provided by Java that your program
uses
The .class files can be loaded from a disk on your system or over a network
Cont.… 19
In Phase 4, as the classes are loaded, the bytecode verifier examines their
bytecodes to ensure that they’re valid and do not violate Java’s security
restrictions.
Java enforces strong security to make sure that Java programs arriving over the
network do not damage your files or your system (as computer viruses and
worms might)
Cont.… 20
Phase 5: Execution
In phase 5, the JVM executes the program’s bytecodes, thus performing the
actions specified by the program.
Today’s JVMs typically execute bytecodes using a combination of
interpretation and so-called just-in-time(JIT) compilation.
In this process, the JVM analyzes the bytecodes as they’re interpreted,
searching for hotspot parts of the bytecode.
Cont.… 21
Java Variables
A variable is a container that holds the value while the java program is executed.
A variable is assigned with a data type
A variable is the name of the reserved area allocated in memory.
Reserved Area
50
Cont.… 23
Types of variables
Several types of variables are supported by Java. These types of variables include:
2 Local variables
1
Instance variable (Non-static variables)
A variable that is declared inside a class but outside the method is called instance
variable
Can be accessed directly by calling the variable name inside the class
Instance variables are created when an object is created with the use of the keyword
‘new’ and destroyed when the object is destroyed.
Holds 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.
Example 1: 25
2 Local variable
A variable that is declared inside the body of a method is called local variable
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 exists the method, constructor or block
Access modifiers can be used in local variables
Can be visible only within the declared method, constructor or block.
There is no default value for local variables so local variables should be declared and
an initial value should be assigned before the first use
Example 2: 27
2
Static variable (class variable)
Static variables are also known as class variable because they are associated with the class
and common for all the instances of class.
Static variables are declared with the static keyword in a class.
You can create a single copy of the static variable and share it among all the instances of the
class.
Static variables are rarely used other than being declared as constants.
Constants are variables that are declared as public or private, final and static.
Cont.… 29
There would only be one copy of each class variable per class, regardless of how many
objects are created from it.
Static variables are created when the program stars 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 the users of the class
Default values are the same as instance variables.
Static variables can be accessed by calling the class name. ClassName.VariableName
Example 3: 30
Identifiers in java
Identifiers are used to name things, such as classes, variables, and methods.
Identifiers must respect a few rules to allow the code to compile and also common-sense
programming rules, called Java coding conventions.
In Java, there are a few focuses to recall about identifiers. They are as per the following
standard
Literals in java
A constant value in Java is created by using a literal representation
It can be digits, letters, or others that represent constant value to be stored in variables.
Literals are used to create values that are assigned to variables, used in expressions, and
passed to methods
A literal can be used anywhere a value of its type is allowed
For example, here are some literals:
Left to right, the first literal specifies an integer, the next is a floating-point value, the third is
a character constant, and the last is a string.
Cont.… 33
2 Non-Primitive-Data Types
There are eight primitive information types, which are supported by Java.
Primitive data types are predefined by the dialect and named by a catchphrase
Data types in java 34
Primitive Non-Primitive
Boolean Arrays
boolean
Character Strings
char
Integers This group includes byte, short, int, and long, which are for whole-valued signed
numbers.
Floating-point numbers This group includes float and double, which represent numbers
with fractional precision.
Characters This group includes char, which represents symbols in a character set, like
letters and numbers.
Boolean This group includes boolean, which is a special type for representing true/false
values.
Cont.… 36
Comments in java
Java comments refer to pieces of explanatory text that are not part of the code executed and
are ignored by the compiler.
There are three types of comments defined by Java
Reserved words for data types: (8) Reserved words for flow control:(11)
1) byte 1) if
2) else
2) short
3) switch
3) int
4) case
4) long 5) default
5) float 6) for
6) double 7) do
8) while
7) char
9) break
8) boolean
10) continue
11) return
Java Reserved Words 39
Escape Sequences
Java support some special character constant which are given in following table.
2 Relational Operators
5
Assignment Operators
6 Conditional operators
Arithmetic Operators
Operations in Java are used in essentially the same manner as in algebra.
They are used with variables for performing arithmetic operations
Here is a list of arithmetic operators available in Java.
Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
Cont.. 44
Examples
Addition Subtraction
class AdditionInt { class SubtractionInt {
public static void main(String args[]) public static void main(String args[])
{ {
int num1 = 10; int a = 20;
int num2 =20; int b =10;
int sum; int sub;
sum = num1+num2; sub = a-b;
System.out.println("Addition =:"+sum); System.out.println("Subtraction =:"+sub);
} }
} }
Output: Addition=:30 Output: Subtraction=:10
Cont.. 45
Examples
Multiplication Division
class MultiplicationInt { class DivisionInt {
public static void main(String args[]) public static void main(String args[])
{ {
int a = 6; int a = 10;
int b =2; int b =2;
int mult; int div;
sum = a*b; div = a/b;
System.out.println(“Multiplication =:"+mult); System.out.println(“Division =:"+div);
} }
} }
Output: Multiplication=:12 Output: Division=:5
Cont.… 46
Relational Operators
Java also supports several relational operators.
The list of relational operators that are supported by Java are given below
Operator Operation
== Equal To
=! Not Equal To
Now, following examples show the actual public static void main(String[] args) {
int a = 10;
use of operators. int b = 30;
System.out.println("a>b = " +(a>b));
1) If 10 > 30 then result is false System.out.println("a<b = "+(a<b));
System.out.println("a<=b = "+(a<=b));
2) If 40 > 17 then result is true }
3) If 10 >= 300 then result is false }
. Output:
4) If 10 <= 10 then result is true a>b = false
a<b = true
a<=b = true
Cont.… 48
Logical Operators
Logical operators are an integral part of any operator set.
The logical operators supported by Java are listed in the table below
public class BooleanLogic{
Operator Operation public static void main(String[] args) {
boolean a = true;
&& Logical AND boolean b = false;
System.out.println("a||b = " +(a||b));
System.out.println("a&&b = "+(a&&b));
|| Logical OR System.out.println("a! = "+(!a));
}
} Output:
! Logical NOT
. a||b = true
a&&b = false
a! = false
49
Syntax
Scanner Object_name = new Scanner(System.in);
Variable_name = object_name.nextDatatype();
Example:
Scanner input = new Scanner(System.in);//an object used to access the methods of
input
int int_number=input.nextInt();//to read integer number from keyboard
byte byte_number=input.nextByte();//to read integer number from keyboard
char c =input.next().charAt(0); //to read a single character
Cont.… 50
Example
Write a java program that displays the sum of two numbers?
Write a java program that calculates the square of any number?
Cont.… 51
import java.util.Scanner;
When one type of data is assigned to another type of variable, an automatic type conversion
will take place if the following two conditions are met:
1 The two types are compatible.
When these two conditions are met, a widening conversion takes place
For example, the int type is always large enough to hold all valid byte values
For widening conversions, integer and floating-point types, are compatible with each other.
However, there are no automatic conversions from the numeric types to char or boolean.
Also, char and boolean are not compatible with each other.
Examples 54
Casting Incompatible Types 55
Although the automatic type conversions are helpful, they will not fulfill all needs
This kind of conversion is sometimes called a narrowing conversion, since you are explicitly
making the value narrower so that it will fit into the target type
To create a conversion between two incompatible types, you must use a cast
A cast is simply an explicit type conversion.
It has a general form: (target-type) value
Here, target-type specifies the desired type to convert the specified value to
For example int a;
byte b;
b = (byte) a;
Example 56
class ConversionDemo
{
public static void main(String args[])
{
byte b;
int i = 257;
double d = 323.142; Output
System.out.println("\nConversion of int to byte.");
b = (byte) i; Conversion of int to byte.
System.out.println("i and b " + i + " " + b); i and b 257 1
System.out.println("\nConversion of double to int.");
i = (int) d;
System.out.println("d and i " + d + " " + i); Conversion of double to int.
System.out.println("\nConversion of double to byte."); d and i 323.142 323
b = (byte) d;
System.out.println("d and b " + d + " " + b); Conversion of double to byte.
}
}
d and b 323.142 67
Control Statements 57
In Java, program is a set of statements and which are executed sequentially in order in which
they appear
A programming language uses control statements to cause the flow of execution to advance
and branch based on changes to the state of a program.
Java’s program control statements can be put into the following categories :
1 Selection Statement
2 Iteration Statement
3 Jump Statement
Selection Statements 58
Syntax:
If (condition)
{
Statement block;
}
Selection Statements 59
5 Switch Statement
In Java, switch statement check the value of given variable or statement against a list of case
values and when the match is found a statement-block of that case is executed .
switch(expression)
{
case constant1:
Statement sequence
break;
case constant2:
statement sequence
break;
case constant3:
statement sequence
break;
……….
default:
statement sequence
}
Selection Statements 61
Example:
public class Switch_Example1 {
public static void main(String[] args) {
for (int i = 0; i<6; i++){
switch (i) {
case 0:
System.out.println("Value is:"+i);
break; Output
case 1:
System.out.println("Value is:"+i);
break;
case 2:
Value is:0
System.out.println("Value is:"+i); Value is:1
break;
case 3: Value is:2
System.out.println("Value is:"+i); Value is:3
break;
default: Here is default value
System.out.println("Here is default value");
}
Here is default value
}
}
}
Iteration Statement 62
Java’s iteration statements are for, while, and do-while. These statements create what we
commonly call loops
02 03
1 For loop 2 while loop Do-while loop
3
Iteration Examples 63
class Number
{
public static void main(String args[])
{
int i;
System.out.println("list of 1 to 10 numbers:");
for(i=1;i<=10;i++)
{
System.out.print(" "+i);
}
} list of 1 to 10 numbers:
} 1 2 3 4 5 6 7 8 9 10
Iteration Examples 64
class Number
{
public static void main(String args[])
{
int i=1;
System.out.println("list of 1 to 10 numbers");
while(i<=10)
{
System.out.print(""+i);
i++;
list of 1 to 10 numbers:
}
1 2 3 4 5 6 7 8 9 10
}
}
Iteration Examples 65
2 Using continue
It is possible to force an early iteration of a loop, bypassing the loop’s normal control structure
The continue statement forces the next iteration of the loop to take place, skipping any code between itself and
the conditional expression that controls the loop
2 Multidimensional Arrays
// printing 2D array
for (int i=0; i< 3 ; i++)
{
for (int j=0; j < 3 ; j++) 279
System.out.print(arr[i][j] + " "); 361
System.out.println(); 742
}
}
}
Strings 75
Generally, a String is a sequence of characters. But in Java, a string is an object that represents a sequence of
characters.
Syntax : String variabl_name; Or String variable_name= new String(“statement ”);
class MainString {
public static void main(String[] args) {
// create strings
String first = "Java";
String second = "Python";
String third = "JavaScript";
// print strings
System.out.println(first); // print Java
System.out.println(second); // print Python
System.out.println(third); // print JavaScript
}
}
Strings 76