Revising Basic Java Concepts
Chapters Covered-
1. Introduction to Object Oriented Programming Concepts
2. Elementary Concept of Objects and Classes
3. Values and Data Types
4. Operators in Java
5. Input in Java
6. Mathematical Library Methods
7. Conditional Constructs in Java
Java is a portable, machine-independent, object-oriented, multithreaded and high level programming
language. It was developed by James Gosling, Patrick Naughton, Chris Worth, Ed Frank, Mike Sheridan at Sun
Microsystems in year 1991. Java was initially called “Oak”. But in 1996, it was renamed as “Java”, which is now
a part of Oracle corporation.
Flow of Java Programming Java programs are firstly compiled and then interpreted.
Java Source Code: It is a collection of computer instructions built by the programmer using Java.
Java Compiler: A Java compiler is a set of programs that transforms source code into bytecode.
Bytecode: Java source code is compiled into bytecode by Java compiler. This bytecode is independent
of the machine on which the program is to run. This makes a Java compiler highly portable.
Java Interpreter: The Java interpreter decodes and executes bytecode for the Java Virtual Machine
(JVM). The Java interpreter is actually a part of JVM. JVM is a platform-independent execution
environment.
Different Types of Java Programming A Java program can be written in the following ways:
Stand-alone Applications (Java Application): It is also known as desktop application or window
based application. It is developed by the user and if we needed to run on any machine, we will have to
install it on that machine.
Java Applet: A Java applet is a special kind of Java program that a browser enabled with Java
technology can be downloaded from the Internet and run.
Package (Java Package): Java packages can be stored in compressed files called JAR (Java Archive)
files.
Object Oriented Programming (OOP) Object oriented programming is a programming paradigm that
represents concepts as objects that have data fields and associated procedures known as methods.
Elementary Concept of Objects and Classes In object oriented programming technique, we design a
program using objects and classes, which are as follows:
Object: An object is a real world entity. It could be a person, place, table, chair or vehicle. It can be a
program map, handle etc. Each object holds data and code to operate on the data.
Class: Class is a collection of objects of similar type. Each object of a class possesses same attributes
and common behaviour defined within the same class.
Principles of Object Oriented Programming OOP works on the principles of encapsulation, abstraction,
inheritance and polymorphism, which are as follows:
Encapsulation: Process of wrapping up the data and methods into a single unit is called
encapsulation. In object oriented programming, it is done by making data and associated methods
within the class to operate on data and to manage it, i.e. class.
Data Hiding: Data is not accessible to outside the world and only class methods can operate on this
data. This isolation of data from direct access is the essential concept of OOP. It is also referred to as
data hiding.
Data Abstraction: Abstraction is a concept, which is used to represent essential features without
including the background details or explanations. It is an essential concept of OOP.
Inheritance: The capability of one class to inherit (derive) the properties of any other class
completely or partially, is known as inheritance. The class, from which properties are inherited, is
Page 1 of 7
known as super class (or base class or parent class) and the class, which inherits the properties from
superclass is known as sub class (or derived class or child class).
Polymorphism: The term polymorphism literally means the capacity to take “different forms from
one”. Polymorphism is broadly used in implementing inheritance. It means that the same operations
may behave differently in different classes. It allows us to write generic, reusable code more easily.
Tokens Tokens are the smallest unit or single element of a Java program, which are identified by the
compiler.
There are five types of tokens, i.e., literals, keywords, identifiers, operators and separators.
Literals These are the constants in a Java program. It can be any number, text or other information that
represents a value. We can specify any value as a literal such as:
(i) Integer Literals (iv) String Literals
(ii) Floating Literals (v) Boolean Literals
(iii) Character Literals (vi) Null Literals
Keywords These are reserved words used within the program to specify a particular task.
Identifiers This is a name given to a package, class, interface, method or variable. It allows a programmer to
refer to them from other places in the program. e.g., $salary, _value, 1_value
Operators These are basically the symbols or tokens, which perform mathematical or logical operations to
yield results. They are used to manipulate primitive data types.
Conditional Operator (?:) This operator is used to find the condition result, which could be either true or
false. The goal of this operator is to decide which value should be assigned to the variable.
Syntax: variable x = (expression) ? value1 (if true) : value2 (if false);
Separators It helps to define the structure of a program. Some separators are as follows:
Parenthesis ( ) Braces { } Brackets [ ] Period . Comma , Semicolon ;
Data Types It refers to the type of data that can be stored in a variable. Sometimes, Java is called a strongly
typed language because when you declare a variable, you must specify the variable type. Data types in Java
are classified into two types:
Primitive data types
These are the data types defined by the language itself. A primitive data type can hold only one value at a time
and is the simplest built-in form of data within Java.
byte, short, int, long, float, double, boolean, char are the examples of primitive data types.
Non-primitive data types (Composite data types)
These are referenced data types, which are based on primitive data types. Non-primitive data types store the
memory address of an object. Class, Interface, Array are the examples of reference data types.
Expression
It is a construct made of variables, operators and method invocations, which are raised according to the
syntax of the language, that evaluates to a single value.
Block
It is a group of zero or more statements between balanced braces and can be used anywhere. It is also known
as a compound statement.
Type Casting
It is a term of converting one data type into another. It is necessary because, sometimes data is in a form that
is unrecognisable to the program. In Java, there are two ways of type casting:
Implicit Type Casting
When the type conversion is performed automatically by the compiler without programmer's intervention,
such type of conversion is known as implicit type conversion.
Explicit Type Casting
Page 2 of 7
A data type of higher size cannot be assigned to a data type of lower size. This is not done implicitly by the
compiler and requires explicit conversion; a casting operation to be performed by the programmer.
Statements A statement in Java forms a complete command to be executed and can include one or more
expressions. There are three kinds of statements in Java:
Declaration Statements – These statements declare variables.
Expression Statements – These statements change the value of variables, call methods and create
objects.
Control Flow Statements – These statements determine the order in which the given statements are
executed.
Comments
Comments are an integral part of any program for the purpose of documentation or explanation. Comments
are non-executable statements that are ignored by the compiler or interpreter. Java has three types of
comments as follows:
Single Line Comment is used for a single line of comment.
A line comment starts with two forward slashes (//).
Multi-Line or Block Comment is used for multiple lines comment.
A block comment starts with a forward slash and asterisk (/*) and ends with asterisk and forward
slash (*/).
Documentation or JavaDoc Comment is used specially to document non-private classes, attributes
and methods. It starts with one forward slash and two asterisks (/**) and ends with one asterisk and
one forward slash (*/).
Input/Output in Java
Input is any information that is needed by a program to complete its execution.
Output is any information that the program must convey to the user.
Using Scanner Class
The Scanner class is a class, which allows the user to read values of various types.
Scanner class is available in java.util system package.
You must import java.util package to avail the facilities contained in Scanner class. The statement to
import java.util package is shown below:
import java.util.Scanner;
After importing java.util package, create object which can hold a set of values of different types.
The syntax to create a Scanner object is shown below:
Scanner input = new Scanner(System.in);
It is an advanced version of BufferedReader which was added in later versions of Java.
The Scanner looks for tokens in the input. A token is a series of characters that ends with what Java
calls whitespace.
Control Structure
It determines an order in which the statements used in a program are executed.
There are three types of control structure:
Selection: These statements are used in a program to choose different paths of execution based upon
the outcome of an expression or the state of a variable.
Some selection statements are as follows:
(i) if Statement
It is the most basic form of selection statement, which executes a single block of statements, if the specified
condition evaluates to true, otherwise the given set of statements are ignored.
Syntax:
if (Condition) {
Page 3 of 7
Statements;}
(ii) if-else Statement It is a type of selection statement in which a single statement or a group of statements
enclosed within braces. The if block is executed only when, if condition is true. Otherwise, the else block is
executed.
Syntax:
if (Condition) else
{ {
Statement 1; Statement 2;
Statement 2; ...
... }
}
(iii) Nested if Statement It is always legal to nest if-else statements, which means you can use if or if-else
statements inside another if or if-else statements.
Syntax:
if (Condition 1){ }
if (Condition 2){ }
Statement 1; else
...} {
else{ Statement 3;
Statement 2; ...
... }
(iv) if-else-if Statement It is a kind of statement, in which a number of logical conditions are checked for
executing various statements. It is based upon nested if and is often called the if-else-if ladder.
Syntax:
if (Condition 1) else if (Condition 3)
{ {
Statement 1; Statement 3;
... ...
} }
else if (Condition 2) else
{ {
Statement 2; Statement;
... ...
} }
(v) switch Statement It works as a multi-way branch statement. It provides an easy way to execute different
blocks of a program according to the value of an expression. Instead of using the if-else-if series of statements,
using switch statement is a better option.
Syntax:
switch(expression) case value 2:
{ Statements;
case value 1: break;
Statements; ...
break; default:
Statements;}
Iteration: It means repetition of a set of statements, depending upon a condition test. Till the time a condition
is true, a set of statements are repeated again and again. Iteration is also known as looping or repetition.
Some iteration statements are as follows:
(i) while Loop This loop is also known as 'entry controlled loop'. while loop checks the condition first before
entering in a loop. If the condition evaluates to true, the statements given inside the while loop get executed.
Syntax:
Page 4 of 7
while(Condition)
{
Statement 1;
Statement 2;
...
Statement N;
}
(ii) do-while Loop It is also known as 'exit controlled loop'. This loop ensures that the complete loop is
executed at least once, then it checks whether the while condition is true or false. If the condition is true then
the loop will continue but if the condition is false, the loop will be terminated.
Syntax
do
{
Statement 1;
Statement 2;
...
} while (Condition);
(iii) for Loop It is also an 'entry controlled loop'. It is a short method of looping, which is commonly preferred
by programmers. It tests the condition before entering in the loop body. If the condition evaluates to true, the
given statements are executed else the loop will not execute.
Syntax
for(initialization; condition; increment/decrement)
{
Statement 1;
Statement 2;
...
Statement N;
}
Jump Statements These statements are used to transfer control to other parts of the program. These
statements can be used to modify the behaviour of conditional and iterative statements. Jump statements
allow you to exit a loop, start the next iteration of a loop or explicitly transfer program control to a specified
location in your program. Some jump statements are as follows:
(i) break Statement It is used to jump out of a loop. On encountering a break statement within a loop, the
execution continues with the next statement outside the loop.
Syntax - break;
(ii) continue Statement It is used only within looping statements. When the continue statement is
encountered, the next iteration starts and the remaining statements in the present iteration are skipped.
Syntax : continue;
(iii) return Statement It is used to explicitly return from a method. It causes program control to transfer
back to the caller of the method. The return statement immediately terminates the method in which it is
executed.
Syntax : return(Expression);
Errors Errors are those statements or instructions that may be caused to stop the program execution or to
stop the compilation process. There are three kinds of errors: syntax errors, runtime errors and logic errors.
Syntax Errors These are errors where the compiler finds something wrong with your program and
you cannot even try to execute it, e.g., you may have incorrect punctuation or may be trying to use a
variable that has not been declared. Syntax errors are the easiest to find and correct. The compiler will
tell you where it got into trouble and its best guess as to what you did wrong.
Page 5 of 7
Runtime Errors If there are no syntax errors, Java may detect an error while your program is running.
You will get an error message telling you the kind of error and a stack trace that tells you where the
error occurred, but also what other method or methods you were in.
Logic Errors A logic error or bug is when your program compiles and runs, but does the wrong thing.
The Java system, of course, has no idea what your program is supposed to do, so it provides no
additional information to help you find the error.
Class A class can be defined as a template/blue print that describes the state and behaviour of its object. A
class can contain fields and methods to describe the state and behaviour of an object.
Class as Composite Type Composite types are reference type, which holds the reference id of a
memory location.
A class is a composite data type because it requires a reference to use its attributes.
Declaration of Class In general, class declarations can include these components in order:
o (i) Modifiers such as public, private and a number of others that you will encounter later.
o (ii) The class name with the initial letter capitalized by convention.
o (iii) The name of the class's parent (superclass), if any preceded by the keyword extends.
o (iv) The class body, surrounded by braces {}.
Object as Instance of a Class An object is an instance of class or a class type variable that holds individual
copy of data.
Creating Objects As a Class is created from a class in Java, the 'new' keyword is used to create a new
object. There are three steps to create an object of a class:
(i) Declaration An object is declared with an object name as class type.
(ii) Instantiation The 'new' keyword is used to create the object.
(iii) Initialization The 'new' keyword is followed by a call to a constructor. This call initializes
the new object (i.e. to set the initial value of instance variable).
Variable It is a container that holds values that are used in a Java programming language. It can possess any
combination of letter without space. Each variable in Java has a specific type, which determines the size and
layout of the variable's memory.
Declaration of Variable A declaration of a variable refers to the following:
o (i) Specify the name of the variable.
o (ii) Specify the data type of the variable.
o (iii) Specify the scope of usage of the variable.
Syntax
Datatype variableName;
e.g., int age;
Types of Variable The Java programming language defines the following kinds of variables:
o (i) Instance Variable Non-static variables are called instance variables. Instance variables are
used to store the state of an object. Every object created from a class definition would have its own
copy of variable.
Syntax : Object .variableName;
o (ii) Class Variable It is a static field declared with the static modifier. It is a special type of class
attribute (or class property, field or data member). Class variable is created when the program
starts and destroyed when the program stops. It can be accessed by calling with the class name.
Syntax : ClassName.variableName;
o (iii) Local Variable These variables are declared in method, constructors or blocks. These are
implemented at stack level internally. There is no default value for local variable, so when local
variable is declared, an initial value should be assigned to it before the first use.
Syntax : variableName;
main() Function The main function is so special because it is implicitly invoked to execute a program.
Page 6 of 7
Before a Java application runs, Java's class loader loads its starting main class (the class with main method)
and Java's byte code verifier verify that class. Then, the class initializes.
public static void main(String args[]) throws IOException
{
// ...
}
Math Functions
Sno Function Description Return Data Type Syntax
Returns the smaller number
1 min(a,b) int/long/float/double Math.min(a,b)
between a and b
Returns the greater number
2 max(a,b) int/long/float/double Math.max(a,b)
between a and b
3 cbrt(a) Returns the cube root of a number double Math.cbrt(a)
Returns the square root of a positive
4 sqrt(a) double Math.sqrt(a)
number
Returns the absolute value of a
5 abs(a) int/long/float/double Math.abs(a)
number
Returns the value of a raised to the
6 pow(a,b) double Math.pow(a,b)
power of b
Returns the rounded value up to the
7 ceil(a) double Math.ceil(a)
nearest integer.
Returns the rounded value down to
8 floor(a) double Math.floor(a)
the nearest integer.
Returns the whole number greater
9 round(a) int/long Math.round(a)
than or equal to the number.
Returns the truncated value
10 rint(a) double Math.rint(a)
number.
Returns a random number between
11 random() double Math.random()
0 and 1.
Returns the natural logarithm of a
12 log(a) double Math.log(a)
number.
13 exp(a) Returns an exponent value, i.e., eadouble Math.exp(a)
14 sin(a) double Math.sin(a)
Returns the Sine/Cosine/Tangent of
15 cos(a) double Math.cos(a)
an angle a (expressed in radian).
16 tan(a) double Math.tan(a)
Page 7 of 7