2. SYLLABUS
Introduction to Java: Importance and features of Java
Keywords
Constants
Variable
Datatypes
Operators and Expressions
Decision Making
Branching and Looping
Introducing classes, objects and methods
3. Cont….
Defining a class
Adding variables and methods
Creating objects
Constructors
Class inheritance
Arrays and String.
4. Introduction to Java: Importance and
features of Java
Java programming language was originally developed by Sun Microsystems
which was initiated by James Gosling and released in 1995.
The latest release of the Java Standard Edition is Java SE 8.
Java is guaranteed to be Write Once, Run Anywhere .
Java is:
Object Oriented: In Java, everything is an Object. Java can be easily
extended since it is based on the Object model.
Platform Independent: Unlike many other programming languages including C
and C++, when Java is compiled, it is not compiled into platform specific
machine, rather into platform independent byte code. This byte code is
distributed over the web and interpreted by the Virtual Machine (JVM) on
whichever platform it is being run on.
5. Cont…..
Simple: Java is designed to be easy to learn. If you understand the basic
concept of OOP Java, it would be easy to master.
Secure: With Java's secure feature it enables to develop virus-free, tamper-
free systems. Authentication techniques are based on public-key encryption.
Architecture-neutral: Java compiler generates an architecture-neutral object
file format, which makes the compiled code executable on many processors,
with the presence of Java runtime system.
Portable: Being architecture-neutral and having no implementation dependent
aspects of the specification makes Java portable.
Robust: Java makes an effort to eliminate error prone situations by
emphasizing mainly on compile time error checking and runtime checking.
Multithreaded: With Java's multithreaded feature it is possible to write
programs that can perform many tasks simultaneously. This design feature
allows the developers to construct interactive applications that can run
smoothly.
6. Cont….
Interpreted: Java byte code is translated on the fly to native machine
instructions and is not stored anywhere. The development process is more
rapid and analytical since the linking is an incremental and light-weight
process.
High Performance: With the use of Just-In-Time compilers, Java enables
high performance.
Distributed: Java is designed for the distributed environment of the
internet.
Dynamic: Java is considered to be more dynamic than C or C++ since it is
designed to adapt to an evolving environment. Java programs can carry
extensive amount of run-time information that can be used to verify and
resolve accesses to objects on run-time.
7. First Java 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
}
}
9. Keywords
Java has a total of 51 keywords.
Java keywords are also known as reserved words.
Keywords are particular words that act as a key to a code. These are predefined
words by Java so they cannot be used as a variable or object name or class name.
A list of Java keywords or reserved words are given below:
abstract: Java abstract keyword is used to declare an abstract class. An abstract
class can provide the implementation of the interface. It can have abstract and
non-abstract methods.
boolean: Java boolean keyword is used to declare a variable as a boolean type. It
can hold True and False values only.
break: Java break keyword is used to break the loop or switch statement. It
breaks the current flow of the program at specified conditions.
10. Cont….
byte: Java byte keyword is used to declare a variable that can hold 8-bit data
values.
case: Java case keyword is used with the switch statements to mark blocks of
text.
catch: Java catch keyword is used to catch the exceptions generated by try
statements. It must be used after the try block only.
char: Java char keyword is used to declare a variable that can hold unsigned
16-bit Unicode characters
class: Java class keyword is used to declare a class.
continue: Java continue keyword is used to continue the loop. It continues
the current flow of the program and skips the remaining code at the specified
condition.
11. Cont….
default: Java default keyword is used to specify the default block of code in a
switch statement.
do: Java do keyword is used in the control statement to declare a loop. It can
iterate a part of the program several times.
double: Java double keyword is used to declare a variable that can hold 64-
bit floating-point number.
else: Java else keyword is used to indicate the alternative branches in an if
statement.
enum: Java enum keyword is used to define a fixed set of constants. Enum
constructors are always private or default.
extends: Java extends keyword is used to indicate that a class is derived from
another class or interface.
12. Cont….
final: Java final keyword is used to indicate that a variable holds a constant value.
It is used with a variable. It is used to restrict the user from updating the value of
the variable.
finally: Java finally keyword indicates a block of code in a try-catch structure.
This block is always executed whether an exception is handled or not.
float: Java float keyword is used to declare a variable that can hold a 32-bit
floating-point number.
for: Java for keyword is used to start a for loop. It is used to execute a set of
instructions/functions repeatedly when some condition becomes true. If the
number of iteration is fixed, it is recommended to use for loop.
if: Java if keyword tests the condition. It executes the if block if the condition is
true.
implements: Java implements keyword is used to implement an interface.
13. Constants
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.
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.
Static and Final Modifiers
The purpose to use the static modifier is to manage the memory.
It also allows the variable to be available without loading any instance of the class
in which it is defined.
The final modifier represents that the value of the variable cannot be changed. It
also makes the primitive data type immutable or unchangeable.
14. Static and Final Modifiers
The purpose to use the static modifier is to manage the memory.
It also allows the variable to be available without loading any instance of the
class in which it is defined.
The final modifier represents that the value of the variable cannot be
changed.
It also makes the primitive data type immutable or unchangeable.
The syntax to declare a constant is as follows:
static final datatype identifier_name=value;
15. Cont….
Where static and final are the non-access modifiers.
The double is the data type and PRICE is the identifier name in which the
value 432.78 is assigned.
In the above statement, the static modifier causes the variable to be
available without an instance of its defining class being loaded and
the final modifier makes the variable fixed.
16. Variable
Java variable is a name given to a memory location.
It is the basic unit of storage in a program.
The value stored in a variable can be changed during program execution.
Variables in Java are only a name given to a memory location.
All the operations done on the variable affect that memory location.
In Java, all variables must be declared before use.
17. Example
// Declaring float variable
float simpleInterest;
// Declaring and initializing integer variable
int time = 10, speed = 20;
// Declaring and initializing character variable
char var = 'h';
18. Datatypes
Data types specify the different sizes and values that can be stored in the
variable. There are two types of data types in Java:
Primitive data types: The primitive data types include boolean, char, byte,
short, int, long, float and double.
Non-primitive data types: The non-primitive data types
include Classes, Interfaces, and Arrays.
19.
20. Operators and Expressions
Operators in Java are the symbols used for performing specific operations in
Java.
Operators make tasks like addition, multiplication, etc which look easy
although the implementation of these tasks is quite complex.
Types of Operators in Java
There are multiple types of operators in Java all are mentioned below:
Arithmetic Operators
Unary Operators
Assignment Operator
Relational Operators
Logical Operators
22. 1. Arithmetic Operators
They are used to perform simple arithmetic operations on primitive data
types.
* : Multiplication
/ : Division
% : Modulo
+ : Addition
– : Subtraction
23. Java Program to implement
Arithmetic Operators
import java.io.*;
// Drive Class
class GFG {
// Main Function
public static void main (String[] args) {
// Arithmetic operators
int a = 10;
int b = 3;
24. Cont….
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));
}
}
25. 2. Unary Operators
Unary operators need only one operand. They are used to increment,
decrement, or negate a value.
– : Unary minus, used for negating the values.
+ : Unary plus indicates the positive value (numbers are positive without this,
however). It performs an automatic conversion to int when the type of its
operand is the byte, char, or short. This is called unary numeric promotion.
++ : Increment operator, used for incrementing the value by 1. There are
two varieties of increment operators.
Post-Increment: Value is first used for computing the result and then incremented.
Pre-Increment: Value is incremented first, and then the result is computed.
– – : Decrement operator, used for decrementing the value by 1. There are
two varieties of decrement operators.
26. Cont….
Post-decrement: Value is first used for computing the result and then
decremented.
Pre-Decrement: The value is decremented first, and then the result is
computed.
! : Logical not operator, used for inverting a boolean value.
27. Java Program to implement
Unary Operators
import java.io.*;
// Driver Class
class GFG {
// main function
public static void main(String[] args)
{
// Interger declared
int a = 10;
int b = 10;
29. Assignment operator
‘=’ Assignment operator is used to assign a value to any variable.
It has right-to-left associativity, i.e. value given on the right-hand side of the
operator is assigned to the variable on the left, and therefore right-hand side
value must be declared before using it or should be a constant.
The general format of the assignment operator is:
variable = value;
30. Java Program to implement
Assignment Operators
import java.io.*;
// Driver Class
class GFG {
// Main Function
public static void main(String[] args)
{
// Assignment operators
int f = 7;
32. 4. Relational Operators
These operators are used to check for relations like equality, greater than,
and less than.
They return boolean results after the comparison and are extensively used in
looping statements as well as conditional if-else statements.
The general format is,
variable relation_operator value
33. Some of the relational operators are-
==, Equal to returns true if the left-hand side is equal to the right-hand side.
!=, Not Equal to returns true if the left-hand side is not equal to the right-
hand side.
<, less than: returns true if the left-hand side is less than the right-hand side.
<=, less than or equal to returns true if the left-hand side is less than or
equal to the right-hand side.
>, Greater than: returns true if the left-hand side is greater than the right-
hand side.
>=, Greater than or equal to returns true if the left-hand side is greater than
or equal to the right-hand side.
34. Java Program to implement
Relational Operators
import java.io.*;
// Driver Class
class GFG {
// main function
public static void main(String[] args)
{
// Comparison operators
int a = 10;
int b = 3;
int c = 5;
35. Cont….
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 == c: " + (a == c));
System.out.println("a != c: " + (a != c));
}
}
36. 5. Logical Operators
These operators are used to perform “logical AND” and “logical OR”
operations, i.e., a function similar to AND gate and OR gate in digital
electronics. One thing to keep in mind is the second condition is not
evaluated if the first one is false, i.e., it has a short-circuiting effect. Used
extensively to test for several conditions for making a decision. Java also has
“Logical NOT”, which returns true when the condition is false and vice-versa
Conditional operators are:
&&, Logical AND: returns true when both conditions are true.
||, Logical OR: returns true if at least one condition is true.
!, Logical NOT: returns true when a condition is false and vice-versa
37. Java Program to implemenet
Logical operators
import java.io.*;
// Driver Class
class GFG {
// Main Function
public static void main (String[] args) {
// Logical operators
boolean x = true;
boolean y = false;
39. 6. Ternary operator
The ternary operator is a shorthand version of the if-else statement. It has
three operands and hence the name Ternary.
The general format is:
condition ? if true : if false
The above statement means that if the condition evaluates to true, then
execute the statements after the ‘?’ else execute the statements after the
‘:’.
40. Java program to illustrate
max of three numbers using
ternary operator
public class operators {
public static void main(String[] args)
{
int a = 20, b = 10, c = 30, result;
// result holds max of three
// numbers
result
= ((a > b) ? (a > c) ? a : c : (b > c) ? b : c);
System.out.println("Max of three numbers = "
+ result);
}
}
41. Bitwise Operators
These operators are used to perform the manipulation of individual bits of a
number. They can be used with any of the integer types.
They are used when performing update and query operations of the Binary
indexed trees.
&, Bitwise AND operator: returns bit by bit AND of input values.
|, Bitwise OR operator: returns bit by bit OR of input values.
^, Bitwise XOR operator: returns bit-by-bit XOR of input values.
~, Bitwise Complement Operator: This is a unary operator which returns the
one’s complement representation of the input value, i.e., with all bits
inverted.
42. Java Program to implement
bitwise operators
import java.io.*;
// Driver class
class GFG {
// main function
public static void main(String[] args)
{
// Bitwise operators
int d = 0b1010;
int e = 0b1100;
44. 8. Shift Operators
These operators are used to shift the bits of a number left or right, thereby
multiplying or dividing the number by two, respectively.
They can be used when we have to multiply or divide a number by two.
General format-
number shift_op number_of_places_to_shift;
45. Cont…
<<, Left shift operator: shifts the bits of the number to the left and fills 0 on
voids left as a result. Similar effect as multiplying the number with some
power of two.
>>, Signed Right shift operator: shifts the bits of the number to the right and
fills 0 on voids left as a result. The leftmost bit depends on the sign of the
initial number. Similar effect to dividing the number with some power of two.
>>>, Unsigned Right shift operator: shifts the bits of the number to the right
and fills 0 on voids left as a result. The leftmost bit is set to 0.
46. Java Program to implement
shift operators
import java.io.*;
// Driver Class
class GFG {
// main function
public static void main(String[] args)
{
int a = 10;
47. Cont..
// using left shift
System.out.println("a<<1 : " + (a << 1));
// using right shift
System.out.println("a>>1 : " + (a >> 1));
}
}
48. Expression
Expression is an essential building block of any Java program.
Generally, it is used to generate a new value.
Sometimes, we can also assign a value to a variable.
In Java, expression is the combination of values, variables, operators,
and method calls.
49. There are three types of expressions in
Java:
Expressions that produce a value. For example, (6+9), (9%2), (pi*radius) + 2.
Note that the expression enclosed in the parentheses will be evaluate first,
after that rest of the expression.
Expressions that assign a value. For example, number = 90, pi = 3.14.
Expression that neither produces any result nor assigns a value. For
example, increment or decrement a value by using increment or decrement
operator respectively, method invocation, etc. These expressions modify the
value of a variable or state (memory) of a program. For example, count++,
int sum = a + b; The expression changes only the value of the variable sum.
The value of variables a and b do not change, so it is also a side effect.
50. Decision Making
Decision Making in programming is similar to decision-making in real life. In
programming also face some situations where we want a certain block of code to
be executed when some condition is fulfilled.
A programming language uses control statements to control the flow of execution
of a program based on certain conditions. These are used to cause the flow of
execution to advance and branch based on changes to the state of a program.
Java’s Selection statements:
if
if-else
nested-if
if-else-if
switch-case
jump – break, continue, return
51. 1. if:
if statement is the most simple decision-making statement.
It is used to decide whether a certain statement or block of statements will
be executed or not i.e if a certain condition is true then a block of statements
is executed otherwise not.
Syntax:
if(condition)
{
// Statements to execute if
// condition is true
}
52. // Java program to illustrate If
statement without curly block
import java.util.*;
class IfDemo {
public static void main(String args[])
{
int i = 10;
if (i < 15)
53. Cont….
System.out.println("Inside If block"); // part of if block(immediate one
statement after if condition)
System.out.println("10 is less than 15"); //always executes as it is
outside of if block
// This statement will be executed
// as if considers one statement by default again below statement is
outside of if block
System.out.println("I am Not in if");
}
}
55. 2. if-else:
The if statement alone tells us that if a condition is true it will execute a block of statements and if the
condition is false it won’t. But what if we want to do something else if the condition is false? Here comes
the else statement. We can use the else statement with the if statement to execute a block of code when
the condition is false.
Syntax:
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
57. // Java program to illustrate if-else
statement
import java.util.*;
class IfElseDemo {
public static void main(String args[])
{
int i = 10;
if (i < 15)
System.out.println("i is smaller than 15");
else
System.out.println("i is greater than 15");
}
}
58. 4. if-else-if ladder:
Here, a user can decide among multiple options.
The if statements are executed from the top down.
As soon as one of the conditions controlling the if is true, the statement
associated with that ‘if’ is executed, and the rest of the ladder is bypassed.
If none of the conditions is true, then the final else statement will be
executed.
There can be as many as ‘else if’ blocks associated with one ‘if’ block but only
one ‘else’ block is allowed with one ‘if’ block.
59. Java program to illustrate if-else-if
ladder
import java.util.*;
class ifelseifDemo {
public static void main(String args[])
{
int i = 20;
if (i == 10)
60. Cont….
System.out.println("i is 10");
else if (i == 15)
System.out.println("i is 15");
else if (i == 20)
System.out.println("i is 20");
else
System.out.println("i is not present");
}
}
61. 5. switch-case:
The switch statement is a multiway branch statement.
It provides an easy way to dispatch execution to different parts of code based on
the value of the expression.
Syntax:
switch (expression)
{
case value1:
statement1;
break;
case value2:
63. Example
import java.io.*;
class GFG {
public static void main (String[] args) {
int num=20;
switch(num){
case 5 : System.out.println("It is 5");
break;
case 10 : System.out.println("It is 10");
break;
64. Cont….
case 15 : System.out.println("It is 15");
break;
case 20 : System.out.println("It is 20");
break;
default: System.out.println("Not present");
}
}
}
65. 6. jump:
Java supports three jump statements: break, continue and return. These
three statements transfer control to another part of the program.
Break: In Java, a break is majorly used for:
Terminate a sequence in a switch statement (discussed above).
To exit a loop.
Used as a “civilized” form of goto.
Continue: Sometimes it is useful to force an early iteration of a loop. That is,
you might want to continue running the loop but stop processing the
remainder of the code in its body for this particular iteration. This is, in
effect, a goto just past the body of the loop, to the loop’s end. The continue
statement performs such an action.
66. Java program to illustrate using
continue in an if statement
import java.util.*;
class ContinueDemo {
public static void main(String args[])
{
for (int i = 0; i < 10; i++) {
// If the number is even
// skip and continue
67. Cont….
if (i % 2 == 0)
continue;
// If number is odd, print it
System.out.print(i + " ");
}
}
}
Return: The return statement is used to explicitly return from a method.
That is, it causes program control to transfer back to the caller of the
method.
68. Branching and Looping
Branching statements are the statements used to jump the flow of execution
from one part of a program to another.
The branching statements are mostly used inside the control statements.
Java has mainly three branching statements, i.e., continue, break,
and return.
The branching statements allow us to exit from a control statement when a
certain condition meet.
69. while loop:
A while loop is a control flow statement that allows code to be executed repeatedly based on
a given Boolean condition. The while loop can be thought of as a repeating if statement.
import java.io.*;
class GFG {
public static void main (String[] args) {
int i=0;
while (i<=10)
{
System.out.println(i);
i++;
}
}
}
70. for loop:
for loop provides a concise way of writing the loop structure.
Unlike a while loop, a for statement consumes the initialization, condition and
increment/decrement in one line thereby providing a shorter, easy to debug structure of
looping.
import java.io.*;
class GFG {
public static void main (String[] args) {
for (int i=0;i<=10;i++)
{
System.out.println(i);
}
}
}
71. do while:
do while loop is similar to while loop with only difference that it checks for condition after
executing the statements, and therefore is an example of Exit Control Loop.
import java.io.*;
class GFG {
public static void main (String[] args) {
int i=0;
do
{
System.out.println(i);
i++;
}while(i<=10);
}
}
72. Introducing classes, objects and methods
Java is an object-oriented programming language.
Everything in Java is associated with classes and objects, along with its attributes
and methods. For example: in real life, a car is an object. The car has attributes,
such as weight and color, and methods, such as drive and brake.
A Class is like an object constructor, or a "blueprint" for creating objects.
Create a Class
To create a class, use the keyword class:
public class Main {
int x = 5;
}
73. Create an Object
In Java, an object is created from a class.
public class Main {
int x = 5;
public static void main(String[] args) {
Main myObj = new Main();
System.out.println(myObj.x);
}
}
74. method in Java
The method in Java or Methods of Java is a collection of statements that
perform some specific task and return the result to the caller.
A Java method can perform some specific task without returning anything.
Java Methods allow us to reuse the code without retyping the code.
In Java, every method must be part of some class that is different from
languages like C, C++, and Python.
1. A method is like a function i.e. used to expose the behavior of an object.
2. It is a set of codes that perform a particular task.
75.
76. Constructors
In Java, a constructor is a block of codes similar to the method.
It is called when an instance of the class is created.
At the time of calling constructor, memory for the object is allocated in the
memory.
Constructor name must be the same as its class name
A Constructor must have no explicit return type
A Java constructor cannot be abstract, static, final, and synchronized
There are two types of constructors in Java:
Default constructor (no-arg constructor)
Parameterized constructor
77. Java Program to create and call default
constructor
class Bike1{
//creating a default constructor
Bike1(){System.out.println("Bike is created");}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}
78. Java Program to demonstrate the use of
the parameterized constructor.
class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){System.out.println(id+" "+name);}
79. Cont….
public static void main(String args[]){
//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
s1.display();
s2.display();
}
}
80. Class inheritance
class Vehicle {
protected String brand = "Ford"; // Vehicle attribute
public void honk() { // Vehicle method
System.out.println("Tuut, tuut!");
}
}
class Car extends Vehicle {
private String modelName = "Mustang"; // Car attribute
public static void main(String[] args) {
81. Cont….
// Create a myCar object
Car myCar = new Car();
// Call the honk() method (from the Vehicle class) on the myCar object
myCar.honk();
// Display the value of the brand attribute (from the Vehicle class) and the
value of the modelName from the Car class
System.out.println(myCar.brand + " " + myCar.modelName);
}
}
82. Arrays and String
public class Main {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars[0]);
}
}
83. String
public class Main {
public static void main(String[] args) {
String greeting = "Hello";
System.out.println(greeting);
}
}