7/30/2019 2.3 Fundamental Programming Structure in Java
1/14
2. Introduction to Java Programming Language 1
2.3 Fundamental programming Structures in Java
A Simple Java Program
In Java, all program codes must be written inside a class. Classes in Java aredeclared using the keyword class followed by class name.
Comments
Java permits both the single-line and multi-line comments.// for single line/* for multiple line comment used this */
Java Program Structure
A Java program may contain many classes of which only one class defines amain method. Classes contain data members and methods that operate on the
data members of the class. Methods may contain data type declarations and
executable statements. To write a Java program, we first define classes and thenput them together. A Java program may contain one or more sections as shownin fig 2.2.
Fig 2.2 General Structure of Java Program
Java Tokens
Java token is the smallest element of a program that is meaning to the computer.When we submit a Java Program to Java compiler, the compiler goes through
the text and extracts individual tokens.Java language includes five types of tokens. They are:
Documentation
Package Statements
Import Statements
Interface Statements
Class Definition
Main Method Class
{
Main Method Definition
}
Suggested
Optional
Optional
Optional
Optional
Essential
//Simple Java Program
Class FirstProgram//declares a class, which is an object-oriented construct.
{
public static void main(String args[])//defines a method named main
{
System.out.println(My first program in Java);/*similar to printf or cout in c&
c++ */
}
}
7/30/2019 2.3 Fundamental Programming Structure in Java
2/14
2. Introduction to Java Programming Language 2
Reserved Keywords Identifiers Literals Operators Separators
Keywords
At the time of designing a programming language, some words are reserved todo specific tasks. Such words are known as keywords or reserved words.Java language has reserved 50 words as keywords.
abstract Switch Native Finally Default
byte Throws Protected If Enum
class Volatile Static Int Float
do Assert Synchronized New Implement
extends Case Transient Public Interfacefor Const While Strictfp Package
import Double Boolean This Return
long Final Catch Try Super
Private Goto Continue Break Throw
short Instanceof Else char void
Identifiers
Identifiers are programmer-designed tokens. They are used for naming classes,methods, variables, objects, labels, packages and interfaces in a program.
Literals
Literal is a constant value written into a program instruction. A literal does notchange its value during the execution of a program.There are four types of literals. These are:
Numeric literals Character literals String literals Boolean literals
OperatorsIt is symbol that takes one or more arguments and operates on them to producea result.
Separators
Separators are symbols used to indicate where groups of code are divided andarranged. They basically divide the shape and function of our code.
Name What it is used
Parentheses() Used to enclose parameters in method definition and invocation, also used
for defining precedence in expressions, containing expressions for flowcontrol and surrounding cast types.
7/30/2019 2.3 Fundamental Programming Structure in Java
3/14
2. Introduction to Java Programming Language 3
Braces{} Used to contain the values of automatically initialized arrays and to define a
block of code for classes, methods and local scopes.
Brackets[] Used to declare array types and for dereferencing array values.
Semicolon ; Used to separate statements
Comma , Used to separate consecutive identifiers in a variable declaration, also used
to chain statements together inside a for statement
Period . Used to separate package names from sub-packages and classes; also used
to separate a variable or method from a reference variable.
Constant
Constants in Java refer to the fixed values that do not change during theexecution of a program.
Numeric Constant Integer Constant Real Constant
Character Constant Character Constant String Constant
Variables
It is an identifier that denotes storage location used to store a data value. A
variable may take different values at different times during the execution of theprogram.
Data Types
Data Types specify the size and the type of values that can be stored.
Fig 2.4 Data types in Java
Numeric
Data Types in Java
Primitive (Intrinsic) Non-Primitive (Derived)
Non-Numeric Classes ArrayInterfac
Integer Floating-Point Character Boolean
byte (1 byte)
short (2 bytes)
int (4 bytes)
long (8 bytes)
float (4 byte)
double (8 bytes)
char (2 byte) boolean (1 byte)
7/30/2019 2.3 Fundamental Programming Structure in Java
4/14
2. Introduction to Java Programming Language 4
Variables Declaration
Declaration does three things:
It tells the compiler what the variable name is. It specifies what type of data the variable will hold. The place of declaration (in the program) decides the scope of the
variable.The general form of declaration of a variable is
Variables are separated by commas. A decimal statement must end with a
semicolon. Some valid declarations are:int count;
float x,y;double pi;
OperatorsOperators are used in program to manipulate data and variables. They usually
form a part of mathematical or logical expressions.Java operators can be classified into a number of related categories as below:
1. Arithmetic Operators2. Relational Operators3. Logical Operators4. Assignment Operators5. Increment and Decrement Operators6. Conditional Operators7. Bitwise Operators8. Special Operators
Arithmetic Operators
Arithmetic Operators are used to construct mathematical expressions as in
algebra.Operator Meaning
+ Addition and unary plus
- Subtraction or unary minus
* Multiplication
/ Division% Modulo division (Remainder)
Output:
a=45b=20
a+b=65a-b=25a*b=900
a/b=2
a%b=5
Type variable1, variable2 variableN;
//Arithmetic Operator Example
class ArithmeticOperator
{
Public static void main(String args[])
{
Int a=20, b=45;
System.out.println(a=+a);
System.out.println(b=+b);
System.out.println(a+b=+(a+b));
System.out.println(a-b=+(a-b));
System.out.println(a*b=+(a*b));
System.out.println(a/b=+(a/b));
System.out.println(a%b=+(a%b));
}
7/30/2019 2.3 Fundamental Programming Structure in Java
5/14
2. Introduction to Java Programming Language 5
Relational Operators
Some examples of the usage of logical expressions are
if(age>55 && salaryy) : x ? y ; // Here lar = 45
Operator Meaning
< Is less than
Is greater than
>= Is greater than or equal to
!= Is not equal to
Operator Meaning&& Logical AND
|| Logical OR
! Logical NOT
v op= exp;
exp1? exp2: exp3;
//Relational Operators Example
class RelationalOperators
{Public static void main(String args[])
{
float a=15.0F, b=20.0F, c=15.0F;
System.out.println(a=+a);
System.out.println(b=+b);
System.out.println(b=+b);
System.out.println(ab));
System.out.println(a==c is +(a==b));
System.out.println(a
7/30/2019 2.3 Fundamental Programming Structure in Java
6/14
2. Introduction to Java Programming Language 6
Big Numbers
For handing the long number, there are couple of handy classes in the java.mathpackage, called BigInteger and BigDecimal.
BigInteger class implement arbitrary precision integer arithmetic BigDecimal does the same for floating point numbers.
The java.math.BigInteger has got the following methods:
BigInteger add(BigInteger other): return the sum of this big integer objectand other.
BigInteger subtract(BigInteger other): return the difference of this biginterger object and other.
BigInteger multiply(BigInteger other): return the product of this big integerobject and other.
BigInteger divide(BigInteger other): return the quotient of this big integerobject and other.
BigInteger mod(BigInteger other): return the remainder of this big integerobject and other.
Int compareTo(BigInterger other): Returns 0 if this big integer equals other, anegative result if this big integer is less than other, and positive resultsotherwise.
Operator Meaning
& bitwise AND
| bitwise OR
^ Bitwise exclusive
~ Ones complement
> Shift right
>>> Shift right with zero fill
Bitwise Operators
Bitwise Operators are used to
manipulate the individual bits within
an operand.
Special Operator
Java support some special operators of
interest such as instanceof operator andmember selection operator (.).
instanceof: It is an objectreference operator and returns
true if the object on the left handside is an instance of the classgiven on the right-hand side.
Dot Operator (.): It is used toaccess the instance variables
and methods of class objects.
//BigInteger Exampleimportjava.math.BigInteger;
publicclass bigint
{
publicstaticvoidmain(String[] args)
{
BigInteger x = newBigInteger ("123456789");
BigInteger y = newBigInteger ("112334");
BigInteger bigIntResult =x.multiply(y);
System.out.println("Result is ==> " + bigIntResult);
}}
7/30/2019 2.3 Fundamental Programming Structure in Java
7/14
2. Introduction to Java Programming Language 7
Java Statement
A statement is an executable combination of tokens ending with semicolon (;)
mark. Statements are usually executed in sequence in the order in which theyappear. However, it is possible to control the flow of execution, if necessary, using
special statements. Java implements several types of statements as shown in fig2.3
Fig 2.3 Classification of Java Statement
Control
Statement
Selection
Statements
Iteration
Statements
Jump
Statements
if-else
if
switch
do
while
for
continue
break
return
if (test expression)
{
statementblock;}statement-x;
if (test expression)
{
true- block statement(s);}
else
{false- block statement(s);}
statement-x;
ifelse Statement
The ifelse statement is the extension
of the simple if statement. The
general form is
Simple if Statement
The general form of simple ifstatement is
e.gif(age>=18)
System.out.println(You can cast a
vote);
7/30/2019 2.3 Fundamental Programming Structure in Java
8/14
2. Introduction to Java Programming Language 8
switch statement
The switch statement tests the value of a given variable (or expression) against alist of case values and when a match is found, a block of statement associated
with that case is executed. The general form of switch statement is as shownbelow:
//Program to test the given number is even or notimport java.util.Scanner;class oddtest{
Public static void main(String args[]){Scanner input=new Scanner(System.in);int num;System.out.println(Enter your number: );num=input.nextInt;
if(num%2==0) System.out.println(num+ is even);elseSystem.out.println(num+ is not even);
}}
switch (test expression){
case value-1:Block-1break;
case value-2:Block-1break;
..default:
default-blockbreak;
}Statement-x;
//Program simple Calculatorimport java.util.Scanner;class oddtest{
public static void main(String args[]){Scanner input=new Scanner(System.in);int x,y,option;System.out.println(Enter the first value: );
x=input.nextInt;
System.out.println(Enter the second value: );y=input.nextInt;System.out.println(1.Addition\n2. Difference\n3. Multiplication\n4. Division\n);System.out.println(Choose your option: );option=input.nextInt;switch(option){
case1: document.out.println(The sum is +(x+y)); break;case2: document.out.println(The difference is +(x-y)); break;case3: document.out.println(The Product is +(x*y)); break;case4: document.out.println(The division is +(x/y)); break;default: document.out.println(Invalid option);
}
}
7/30/2019 2.3 Fundamental Programming Structure in Java
9/14
2. Introduction to Java Programming Language 9
The for Statement
The for loop is entry controlled loop that provides a more concise loop controlstructure. The general form of the for loop is
Example:
sum = 0;
for(n=1; n
7/30/2019 2.3 Fundamental Programming Structure in Java
10/14
2. Introduction to Java Programming Language 10
Array
An array is a group of contiguous or related data items that share a common
name.
Creating an Array
Creation of an array involves three steps:1. Declaring the array2. Creating memory locations3. Putting values into the memory locations.
Declaration of Arrays
Arrays in Java may be declared in two forms:
Creating of Arrays
After declaring an array, we need to create it in the memory. Java allows us tocreate arrays using new operator only, as shown below:
Initialization of ArraysThe final step is to put values into the array created. This process is known as
initialization. This is done using the array subscripts as shown below.
Example
number [0] = 35;
number [1] = 40;..
number [4] = 60;
Example
int number[ ]={36,78,23,67,89};
Array Length
In Java, all arrays store the allocated size in a variable named length.
type arrayname[ ];
type [ ] arrayname;
Form 1
Form 2
Example:
int number[ ];
float average[ ];int [ ]counter;
float[ ] marks;
arrayname = new type[size]; Example:
number = new int[5];average = new float[10];
Arrayname[subscript] = value;
type arrayname[ ] ={list of values};
7/30/2019 2.3 Fundamental Programming Structure in Java
11/14
2. Introduction to Java Programming Language 11
StringsString represents a sequence of characters. In Java, strings are class objects andimplemented using two classes, namely, String and StringBuffer.Strings may be declared and created as follows:
Example:
String firstname;
firstname = new String(Danny); OrString firstname= new String(Danny);
String Arrays
We can create and use arrays that contain strings. The Statement
String itemArray[ ]= new String[3];
//Sorting a list of numbersimport java.util.Scanner;class NumberSorting{
public static void main(String args[]){int number[]={55,45,67,78,79};
int n=number.length;system.out.print(given list: );//sorting beginsfor(int i=0;i
7/30/2019 2.3 Fundamental Programming Structure in Java
12/14
2. Introduction to Java Programming Language 12
String Methods
The String class defines a number of methods that allow us to accomplished a
variety of string manipulation tasks.
Method call Tasks performed
s2=s1.toLowercase(); Converts the string s1 to all lowercase
s2=s1.toUppercase(); Convert the string s1 to all Uppercase
s2=s1.replace(x,y); Replace all appearances of x with y
s2=s1.trim(); Remove white spaces at the beginning and end of the strings s1
s1.equals(s2) Returns true if s1 is equal to s2
s1.equalsIgnorecase(s2) Returns true if s1=s2, ignoring the case of characters
s1.length(s2) Gives the length of s1
s1.Chartat(n) Gives nth character of s1
s1.compareTo(s2) Returns negative if s1s2, and zero if s1 is equal s2
s1.concat(s2) Concatenates s1 and s2
s1.substring(n) Gives substring starting from nth character
s1.substring(n,m) Gives substring starting from nth character up to mth
String.Valueof(p) Creates a string object of the parameter p
p.toString() Creates a string representation of object p
s1.indexof(x) Gives the position of the first occurrence of x in the string s1
s1.indexof(x,n) Gives the position of x that occurs after nth position in the string s1
String.Valuesof(Variable) Converts the parameter value to string representation
//Special String Operations
class strConcat{Public static void main(String args[]){String name=Sunita;String str =Her +name +is +name;System.out.println(str);
}}
7/30/2019 2.3 Fundamental Programming Structure in Java
13/14
2. Introduction to Java Programming Language 13
StringBuffer Class
StringBuffer is a peer class of String. While String creates strings of fixed_length,
StringBuffer creates strings of flexible length that can be modified in terms of bothlength and content.
Method call Tasks performed
s1.setCharAt(n,x) Modifies the nth character to x
s1.append Appends the string s2 to s1 at the end
s1.insert(n,s2) Replace all appearances of x with y
s1.setLength(n) Sets the length of the string s1 ton. If n< s1.length () s1 is truncated.
If n>s1.length() zeros are added to s1
//Distinction between equals() method and == operatorclass Eq{
public static void main(String args[]){String str1 = Hello!;String str2 = Hell;
String str3 = str1;String str4 = new String(str1);//condition 1if(str1.equals(str2))
System.out.println(1 is true);//condition 2if(str1.equals(str3))
System.out.println(2 is true);//condition 3if(str1.equals(str4))
System.out.println(3 is true);//condition 4if(str1==str2)
System.out.println(4 is true);//condition 5if(str1==str3)
System.out.println(5 is true);//condition 6if(str1==str4)
System.out.println(6 is true);}
//Manipulation of Stringspublicclass StringMani {
publicstaticvoid main(String args[]){StringBuffer str = new StringBuffer("Object Language");System.out.println("Original String: "+str);System.out.println("Length of String: "+str.length());//Modifying Characterstr.setCharAt(6, '-');System.out.println("Modified String: "+str);//Appending String at endstr.append(" improves security.");System.out.println("Appended String: "+str);
}}
7/30/2019 2.3 Fundamental Programming Structure in Java
14/14
2. Introduction to Java Programming Language 14
Input/Output (I/O) Operations
In Java, data can be read from or written to files or standard Input/Output
devices like keyboard and VDU. However, I/O operations in Java are very
complicated and awkward to use. This is so because, Java performs most of theinput-output operations through the GUI (supported by java.awt package) and
depends very rarely on text-based programming.
Stream
A stream is a file or a physical device, such as printer, disk, monitor etc.
Pre-defined Streams
Java defines the following three predefined stream objects:
System.in (Standard input stream object) System.out (Standard output stream object) System.err (Standard error stream object)
Using Scanner for Input from Console
The Scanner splits input into substrings, or tokens, separated by delimiters, whichby default consist of any white space. The tokens can then be obtained as strings
or as primitive types if that is what they represent.For example, the following code snippet shows how to read an integer from the
keyboardScanner scanner = new Scanner (System.in);
int i = scanner.nextInt ();
/** Demonstrate the Scanner class for input of numbers.**/import java.io.*;import java.util.*;
publicclass ScanConsoleApp{publicstaticvoid main (String arg[]) {
// Create a scanner to read from keyboardScanner scanner = new Scanner (System.in);
System.out.printf ("Input int (e.g. %4d): ",3501);int int_val = scanner.nextInt ();System.out.println (" You entered " + int_val +"\n");
System.out.printf ("Input float (e.g. %5.2f): ", 2.43);float float_val = scanner.nextFloat ();System.out.println (" You entered " + float_val +"\n");
System.out.printf ("Input double (e.g. %6.3e): ",4.943e15);double double_val = scanner.nextDouble ();System.out.println (" You entered " + double_val +"\n");
} // main} // class ScanConsoleApp
Top Related