0% found this document useful (0 votes)
0 views

Java Notes - Unit 1 Chapter 2

The document outlines the syllabus and course outcomes for the B.Tech course in Object-Oriented Programming (OOP) with Java. It covers key concepts such as object-oriented programming principles, exception handling, and Java features, along with prerequisites and lecture objectives. Additionally, it details various programming constructs in Java, including classes, constructors, methods, and their functionalities.

Uploaded by

Vaibhav Pal
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Java Notes - Unit 1 Chapter 2

The document outlines the syllabus and course outcomes for the B.Tech course in Object-Oriented Programming (OOP) with Java. It covers key concepts such as object-oriented programming principles, exception handling, and Java features, along with prerequisites and lecture objectives. Additionally, it details various programming constructs in Java, including classes, constructors, methods, and their functionalities.

Uploaded by

Vaibhav Pal
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 68

Department of Applied Computational Science & Engg.

Program: B.Tech. (AIML/AI/DS)


Course Code: BCS403
Course Name: OOP with Java
Lecture No: 02
Department of Applied Computational Science & Engg.
Course Code : BCS403 Course Name: OPP with Java

Course Outcomes :

CO1 Develop the object-oriented programming concept using Java


Implement exception handling, file handling and multi-threading in
CO2 Java

CO3 Apply new Java features to build java programs

CO4 Analyse Java programs with collection Framework


Test web and RESTful web services with spring boot using Spring
CO5 Framework concepts

Program Name: B. Tech (AIML/AI/DS) Program Code:


Department of Applied Computational Science & Engg.
Course Code : BCS403 Course Name: OOP with Java

Course Prerequisites
Basic Programming Concepts
Procedural Programming
Understanding Algorithms and Problem Solving
Memory Management
Data Structures
Basic Command-Line Usage
Understanding of Databases

Program Name: B. Tech (AIML/AI/DS) Program Code:


Department of Applied Computational Science & Engg.
Course Code : BCS403 Course Name: OOP with Java

Syllabus
Unit - 1
• Introduction: Why Java, History of Java, JVM, JRE, Java Environment, Java
Source File Structure, and Compilation. Fundamental,
• Programming Structures in Java: Defining Classes in Java, Constructors, Methods,
Access Specifies, Static Members, Final Members, Comments, Data types,
Variables, Operators, Control Flow, Arrays & String.
• Object Oriented Programming: Class, Object, Inheritance Super Class, Sub Class,
Overriding, Overloading, Encapsulation, Polymorphism, Abstraction, Interfaces,
and Abstract Class.
• Packages: Defining Package, CLASSPATH Setting for Packages, Making JAR
Files for Library Packages, Import and Static Import Naming Convention For
Packages

Program Name: Program Code:


Department of Applied Computational Science & Engg.
Course Code : Course Name:

• Lecture Objectives
To understand Java definition, Java environment, Java program
structure and compilation of java program
Department of Applied Computational Science & Engg.
Course Code : Course Name:

• Lecture Outcomes
Develop the object-oriented programming concept using Java
Department of Applied Computational Science & Engg.
Course Code : Course Name:

Object in JAVA
• An entity that has state and behavior is
known as an object e.g., chair, bike,
marker, pen, table, car, etc. It can be
physical or logical (tangible and
intangible). The example of an
intangible object is the banking system.
• An object has three characteristics:
• State: represents the data (value) of an
object.
• Behavior: represents the behavior
(functionality) of an object such as
deposit, withdraw, etc.
• Identity: An object identity is typically
implemented via a unique ID. The value
of the ID is not visible to the external
user. However, it is used internally by
the JVM to identify each object
uniquely.
Department of Applied Computational Science & Engg.
Course Code : Course Name:

Class in JAVA
• A class is a group of objects which have 1. class <class_name>{
common properties. It is a template or 2. field;
blueprint from which objects are 3. method;
created. It is a logical entity. It can't be 4. }
Class and Field in Java Program:
physical.
5. class Student{
• A class in Java can contain: 6. //defining fields
• Fields 7. int id;//
• Methods field or data member or instance variable
8. String name;
• Constructors
9. //creating main method inside the Student class
• Blocks 10. public static void main(String args[]){
• Nested class and interface 11. //Creating an object or instance
12. Student s1=new Student();//
creating an object of Student
* An object is an instance of a class. A
13. //Printing values of the object
class is a template or blueprint from
14. System.out.println(s1.id);//
which objects are created. So, an object is accessing member through reference variable
the instance(result) of a class. 15. System.out.println(s1.name);
16. }
17. }
Department of Applied Computational Science & Engg.
Course Code : Course Name:

Constructor in Java
• In Java, a constructor is a block of codes Rules for creating Java constructor
similar to the method. It is called when an 1. Constructor name must be the same as its
instance of the class is created. At the time of class name
calling constructor, memory for the object is 2. A Constructor must have no explicit return
allocated in the memory. type
• Every time an object is created using the 3. A Java constructor cannot be abstract, static,
new() keyword, at least one constructor is final, and synchronized
called.
• It calls a default constructor if there is no
• Types of Java constructors
constructor available in the class. In such
case, Java compiler provides a default • There are two types of constructors in Java:
constructor by default. 1. Default constructor (no-arg constructor)
• There are two types of constructors in Java: 2. Parameterized constructor
no-arg constructor, and parameterized
constructor. Note: We can use access modifiers while declaring
a constructor. It controls the object creation. In
other words, we can have private, protected, public
or default constructor in Java.
Department of Applied Computational Science & Engg.
Course Code : Course Name:

Default Constructor in Java


• A constructor is called "Default Constructor" Example of default constructor
when it doesn't have any parameter.
• Syntax of default constructor: 1. //
1. <class_name>(){} Java Program to create and call a default cons
tructor
2. class Bike1{
3. //creating a default constructor
4. Bike1()
{System.out.println("Bike is created");}
5. //main method
6. public static void main(String args[]){
7. //calling a default constructor
8. Bike1 b=new Bike1();
9. }
10. }
Department of Applied Computational Science & Engg.
Course Code : Course Name:

Parameterized Constructor in Java


• A constructor which has a specific number of 1. class Student4{
parameters is called a parameterized 2. int id;
constructor. 3. String name;
• Why use the parameterized constructor? 4. //creating a parameterized constructor
• The parameterized constructor is used to 5. Student4(int i,String n){
provide different values to distinct objects. 6. id = i;
However, you can provide the same values 7. name = n;
also. 8. }
• Example of parameterized constructor 9. //method to display the values
• In this example, we have created the 10. void display()
constructor of Student class that have two {System.out.println(id+" "+name);}
parameters. We can have any number of 11.
parameters in the constructor. 12. public static void main(String args[]){
13. //creating objects and passing values
14. Student4 s1 = new Student4(111,"Karan");
15. Student4 s2 = new Student4(222,"Aryan");
16. //
calling method to display the values of object
17. s1.display();
18. s2.display();
19. }
20. }
Department of Applied Computational Science & Engg.
Course Code : Course Name:

Constructor Overloading in Java


• In Java, a constructor is just like a method but 1. //Java program to overload constructors
without return type. It can also be overloaded 2. class Student5{
3. int id;
like Java methods.
4. String name;
• Constructor overloading in Java is a 5. int age;
technique of having more than one 6. //creating two arg constructor
constructor with different parameter lists. 7. Student5(int i,String n){
They are arranged in a way that each 8. id = i;
constructor performs a different task. They 9. name = n;
are differentiated by the compiler by the 10. }
number of parameters in the list and their 11. //creating three arg constructor
types. 12. Student5(int i,String n,int a){
13. id = i;
14. name = n;
15. age=a;
16. }
17. void display()
{System.out.println(id+" "+name+" "+age);}
18.
19. public static void main(String args[]){
20. Student5 s1 = new Student5(111,"Karan");
21. Student5 s2 = new Student5(222,"Aryan",25);
22. s1.display();
23. s2.display();
24. }
25. }
Department of Applied Computational Science & Engg.
Course Code : Course Name:

Method in Java
• A method is a block of code or collection of statements or a set of code grouped together to perform a
certain task or operation. It is used to achieve the reusability of code. We write a method once and use it
many times. We do not require to write code again and again. It also provides the easy
modification and readability of code, just by adding or removing a chunk of code. The method is
executed only when we call or invoke it.
• Method Signature: Every method has a method signature. It is a part of the method declaration. It
includes the method name and parameter list.
• Access Specifier: Access specifier or modifier is the access type of the method. It specifies the visibility of
the method. Java provides four types of access specifier:
• Public: The method is accessible by all classes when we use public specifier in our application.
• Private: When we use a private access specifier, the method is accessible only in the classes in which it is
defined.
• Protected: When we use protected access specifier, the method is accessible within the same package or
subclasses in a different package.
• Default: When we do not use any access specifier in the method declaration, Java uses default access
specifier by default. It is visible only from the same package only.
Department of Applied Computational Science & Engg.
Course Code : Course Name:

Method in Java
• Return Type: Return type is a data type that the method returns. It may have a primitive data type, object,
collection, void, etc. If the method does not return anything, we use void keyword.
• Method Name: It is a unique name that is used to define the name of a method. It must be corresponding
to the functionality of the method. Suppose, if we are creating a method for subtraction of two numbers, the
method name must be subtraction(). A method is invoked by its name.
• Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of parentheses.
It contains the data type and variable name. If the method has no parameter, left the parentheses blank.
• Method Body: It is a part of the method declaration. It contains all the actions to be performed. It is
enclosed within the pair of curly braces.
Department of Applied Computational Science & Engg.
Course Code : Course Name:

Method in Java
• Naming a Method
• While defining a method, remember that the method name must be a verb and start with a lowercase letter.
If the method name has more than two words, the first name must be a verb followed by adjective or noun.
In the multi-word method name, the first letter of each word must be in uppercase except the first word.
For example:
• Single-word method name: sum(), area()
• Multi-word method name: areaOfCircle(), stringComparision()
• It is also possible that a method has the same name as another method name in the same class, it is known
as method overloading.
• Types of Method
• There are two types of methods in Java:
• Predefined Method
• User-defined Method
Department of Applied Computational Science & Engg.
Course Code : Course Name:

Predefined Method in Java


• Predefined Method 1. public class Demo
• In Java, predefined methods are the method 2. {
that is already defined in the Java class 3. public static void main(String[] args)
libraries is known as predefined methods. It is 4. {
also known as the standard library
5. // using the max() method of Math class
method or built-in method. We can directly
use these methods just by calling them in the 6. System.out.print("The maximum number is: "
program at any point. Some pre-defined + Math.max(9,7));
methods are length(), equals(), compareTo(), 7. }
sqrt(), etc. When we call any of the 8. }
predefined methods in our program, a series
of codes related to the corresponding method
runs in the background that is already stored
in the library.
• Each and every predefined method is defined
inside a class. Such as print() method is
defined in the java.io.PrintStream class. It
prints the statement that we write inside the
method. For example, print("Java"), it prints
Java on the console.
Department of Applied Computational Science & Engg.
Course Code : Course Name:

User - Defined Method in Java


• The method written by the user or 1. import java.util.Scanner;
programmer is known as a user- 2. public class EvenOdd
defined method. These methods are modified 3. {
according to the requirement. 4. public static void main (String args[])
• How to Create a User-defined Method 5. {
6. //creating Scanner class object
• Let's create a user defined method that checks
7. Scanner scan=new Scanner(System.in);
the number is even or odd. First, we will
8. System.out.print("Enter the number: ");
define the method.
9. //reading value from user
10. int num=scan.nextInt();
• How to Call or Invoke a User-defined Method 11. //method calling
• Once we have defined a method, it should be 12. findEvenOdd(num);
called. The calling of a method in a program 13. }
is simple. When we call or invoke a user- 14. //user defined method
defined method, the program control transfer 15. public static void findEvenOdd(int num)
to the called method. 16. {
17. //method body
18. if(num%2==0)
19. System.out.println(num+" is even");
20. else
21. System.out.println(num+" is odd");
22. }
23. }
Department of Applied Computational Science & Engg.
Course Code : Course Name:

Static Method in Java


• A method that has static keyword is known as 1. public class Display
static method. In other words, a method that 2. {
belongs to a class rather than an instance of a 3. public static void main(String[] args)
class is known as a static method. We can also
4. {
create a static method by using the
keyword static before the method name. 5. show();
• The main advantage of a static method is that 6. }
we can call it without creating an object. It 7. static void show()
can access static data members and also 8. {
change the value of it. It is used to create an 9. System.out.println("It is an example of static
instance method. It is invoked by using the method.");
class name. The best example of a static 10. }
method is the main() method.
11. }
Department of Applied Computational Science & Engg.
Course Code : Course Name:

Instance Method in Java


• The method of the class is known as 1. public class InstanceMethodExample
an instance method. It is a non- 2. {
static method defined in the class. Before 3. public static void main(String [] args)
calling or invoking the instance method, it is 4. {
necessary to create an object of its class. Let's 5. //Creating an object of the class
see an example of an instance method. 6. InstanceMethodExample obj = new InstanceMeth
odExample();
7. //invoking instance method
8. System.out.println("The sum is: "+obj.add(12, 13)
);
9. }
10. int s;
11. //user-
defined method because we have not used static k
eyword
12. public int add(int a, int b)
13. {
14. s = a+b;
15. //returning the sum
16. return s;
17. }
18. }
Department of Applied Computational Science & Engg.
Course Code : Course Name:

Abstract Method in Java


• The method that does not has method body is 1. abstract class Demo //
known as abstract method. In other words, abstract class
without an implementation is known as 2. {
abstract method. It always declares in 3. //abstract method declaration
the abstract class. It means the class itself
4. abstract void display();
must be abstract if it has abstract method. To
create an abstract method, we use the 5. }
keyword abstract. 6. public class MyClass extends Dem
o
• Syntax 7. {
1. abstract void method_name(); 8. //method impelmentation
9. void display()
10. {
11. System.out.println("Abstract method
?");
12. }
13. public static void main(String args
[])
14. {
15. //creating object of abstract class
16. Demo obj = new MyClass();
17. //invoking abstract method
Department of Applied Computational Science & Engg.
Course Code : Course Name:

Abstract Method in Java


Java Constructor Java Method

A constructor is used to initialize the state of an A method is used to expose the behavior of an
object. object.

A constructor must not have a return type. A method must have a return type.

The constructor is invoked implicitly. The method is invoked explicitly.

The Java compiler provides a default constructor The method is not provided by the compiler in any
if you don't have any constructor in a class. case.

The constructor name must be same as the class The method name may or may not be same as the
name. class name.
Department of Applied Computational Science & Engg.
Course Code : Course Name:

Access Specifies/Modifier in Java


• A method is a block of code or collection of statements or a set of code grouped together to perform a
certain task or operation. It is used to achieve the reusability of code. We write a method once and use it
many times. We do not require to write code again and again. It also provides the easy
modification and readability of code, just by adding or removing a chunk of code. The method is
executed only when we call or invoke it.
• Method Signature: Every method has a method signature. It is a part of the method declaration. It
includes the method name and parameter list.
• Access Specifier: Access specifier or modifier is the access type of the method. It specifies the visibility of
the method. Java provides four types of access specifier:
• Public: The method is accessible by all classes when we use public specifier in our application.
• Private: When we use a private access specifier, the method is accessible only in the classes in which it is
defined.
• Protected: When we use protected access specifier, the method is accessible within the same package or
subclasses in a different package.
• Default: When we do not use any access specifier in the method declaration, Java uses default access
specifier by default. It is visible only from the same package only.
Department of Applied Computational Science & Engg.
Course Code : Course Name:

Access Specifies/Modifier in Java

Access within class within outside outside


Modifier package package by package
subclass only

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y
Department of Applied Computational Science & Engg.
Course Code : Course Name:

Access Specifies/Modifier in Java


1) Private 1. class A{
2. private int data=40;
• The private access modifier is accessible 3. private void msg()
only within the class. {System.out.println("Hello java");}
• Simple example of private access 4. }
modifier 5.
• In this example, we have created two 6. public class Simple{
classes A and Simple. A class contains 7. public static void main(String args[])
private data member and private {
method. We are accessing these private
8. A obj=new A();
members from outside the class, so there
is a compile-time error. 9. System.out.println(obj.data);//
Compile Time Error
• Role of Private Constructor
10. obj.msg();//Compile Time Error
• If you make any class constructor
private, you cannot create the instance 11. }
of that class from outside the class. 12. }
Department of Applied Computational Science & Engg.
Course Code : Course Name:

Access Specifies/Modifier in Java


2) Default 1. //save by A.java
2. package pack;
• If you don't use any modifier, it is treated 3. class A{
as default by default. The default modifier is 4. void msg(){System.out.println("Hello");}
accessible only within package. It cannot be 5. }
accessed from outside the package. It
provides more accessibility than private. But, 6. //save by B.java
it is more restrictive than protected, and
7. package mypack;
public.
8. import pack.*;
• Example of default access modifier
9. class B{
• In this example, we have created two
packages pack and mypack. We are accessing 10. public static void main(String args[]){
the A class from outside its package, since A 11. A obj = new A();//Compile Time Error
class is not public, so it cannot be accessed 12. obj.msg();//Compile Time Error
from outside the package. 13. }
14. }

In the above example, the scope of class A and its


method msg() is default so it cannot be accessed
from outside the package.
Department of Applied Computational Science & Engg.
Course Code : Course Name:

Access Specifies/Modifier in Java


3) Protected 1. //save by A.java
2. package pack;
• The protected access modifier is accessible 3. public class A{
within package and outside the package but 4. protected void msg()
through inheritance only. {System.out.println("Hello");}
• The protected access modifier can be applied 5. }
on the data member, method and constructor. 6. //save by B.java
It can't be applied on the class. 7. package mypack;
• It provides more accessibility than the default 8. import pack.*;
modifer. 9.
• Example of protected access modifier 10. class B extends A{
• In this example, we have created the two 11. public static void main(String args[]){
packages pack and mypack. The A class of
12. B obj = new B();
pack package is public, so can be accessed
from outside the package. But msg method of 13. obj.msg();
this package is declared as protected, so it can 14. }
be accessed from outside the class only 15. }
through inheritance.
Department of Applied Computational Science & Engg.
Course Code : Course Name:

Access Specifies/Modifier in Java


4) Public 1. //save by A.java
2.
• 3. package pack;
The public access modifier is
4. public class A{
accessible everywhere. It has the widest
scope among all other modifiers. 5. public void msg()
{System.out.println("Hello");}
• Example of public access modifier 6. }
7. //save by B.java
8.
9. package mypack;
10. import pack.*;
11.
12. class B{
13. public static void main(String args[]){
14. A obj = new A();
15. obj.msg();
16. }
17. }
Department of Applied Computational Science & Engg.
Course Code : Course Name:

Static Keyword/Member in Java


• The static keyword in Java is used for memory management mainly. We can apply static
keyword with variables, methods, blocks and nested class. The static keyword belongs to the
class than an instance of the class.
• The static can be:
1. Variable (also known as a class variable)
2. Method (also known as a class method)
3. Block
4. Nested class
Department of Applied Computational Science & Engg.
Course Code : Course Name:

Static Keyword/Member in Java


• 1) Java static variable 1. //
Java Program to demonstrate the use of static varia
• If you declare any variable as static, it is ble
known as a static variable. 2. class Student{
3. int rollno;//instance variable
• The static variable can be used to refer to the 4. String name;
common property of all objects (which is not 5. static String college = ”GLB
unique for each object), for example, the ITM";//static variable
company name of employees, college name 6. //constructor
7. Student(int r, String n){
of students, etc. 8. rollno = r;
• The static variable gets memory only once in 9. name = n;
the class area at the time of class loading. 10. }
11. //method to display the values
• Advantages of static variable 12. void display ()
• It makes your program memory {System.out.println(rollno+" "+name+" "+college);
}
efficient (i.e., it saves memory).
13. }
14. //Test class to show the values of objects
15. public class TestStaticVariable1{
16. public static void main(String args[]){
17. Student s1 = new Student(111,"Karan");
18. Student s2 = new Student(222,"Aryan");
19. //
we can change the college of all objects by the sing
le line of code
20. //Student.college="BBDIT";
21. s1.display();
22. s2.display();
23. }
Department of Applied Computational Science & Engg.
Course Code : Course Name:

Static Keyword/Member
1.
in Java
//Java Program to demonstrate the use of a static method.
2. class Student{
• 2) Java static method 3. int rollno;
4. String name;
• If you apply static keyword with any 5. static String college = "ITS";
6. //static method to change the value of static variable
method, it is known as static method.
7. static void change(){
• A static method belongs to the class 8. college = "BBDIT";
rather than the object of a class. 9. }
10. //constructor to initialize the variable
• A static method can be invoked without 11. Student(int r, String n){
the need for creating an instance of a 12. rollno = r;
13. name = n;
class. 14. }
• A static method can access static data 15. void display(){System.out.println(rollno+" "+name+" "+college);}
16. }
member and can change the value of it. 17. //Test class to create and display the values of object
18. public class TestStaticMethod{
19. public static void main(String args[]){
20. Student.change();//calling change method
21. //creating objects
22. Student s1 = new Student(111,"Karan");
23. Student s2 = new Student(222,"Aryan");
24. Student s3 = new Student(333,"Sonoo");
25. //calling display method
26. s1.display();
27. s2.display();
28. s3.display();
29. }
30. }
Department of Applied Computational Science & Engg.
Course Code : Course Name:

Static Keyword/Member in Java


• 3) Java static block • Example of static block
• Is used to initialize the static data 1. class A2{
member. 2. static{System.out.println("static block is invoked");}
• 3. public static void main(String args[]){
It is executed before the main method at
the time of classloading. 4. System.out.println("Hello main");
5. }
6. }
Department of Applied Computational Science & Engg.
Course Code : Course Name:

Final Keyword in Java


• The final keyword in java is used to restrict the user. The java final keyword can be used in many context.
Final can be:
1. variable
2. method
3. class
• The final keyword can be applied with the variables, a final variable that have no value it is called blank
final variable or uninitialized final variable. It can be initialized in the constructor only. The blank final
variable can be static also which will be initialized in the static block only. We will have detailed learning
of these. Let's first learn the basics of final keyword.
Department of Applied Computational Science & Engg.
Course Code : Course Name:

Final Keyword in Java


1) Java final variable 1. class Bike9{
• If you make any variable as final, you cannot 2. final int speedlimit=90;//final variable
change the value of final variable(It will be 3. void run(){
constant). 4. speedlimit=400;
• Example of final variable 5. }
• There is a final variable speedlimit, we are 6. public static void main(String args[]){
going to change the value of this variable, but
7. Bike9 obj=new Bike9();
It can't be changed because final variable
once assigned a value can never be changed. 8. obj.run();
9. }
10. }//end of class
Department of Applied Computational Science & Engg.
Course Code : Course Name:

Final Keyword in Java


2) Java final method 1. class Bike{
• If you make any method as final, you cannot 2. final void run(){System.out.println("running");}
override it. 3. }
4.
5. class Honda extends Bike{
6. void run()
{System.out.println("running safely with 100kmph");}
7.
8. public static void main(String args[]){
9. Honda honda= new Honda();
10. honda.run();
11. }
12. }
Department of Applied Computational Science & Engg.
Course Code : Course Name:

Final Keyword in Java


3) Java final class 1. final class Bike{}
• If you make any class as final, you cannot 2.
extend it. 3. class Honda1 extends Bike{
4. void run()
{System.out.println("running safely with 100kmph");}
5.
6. public static void main(String args[]){
7. Honda1 honda= new Honda1();
8. honda.run();
9. }
10. }
Department of Applied Computational Science & Engg.
Course Code : Course Name:

Comments in Java
• The Java comments are the statements in a 1. Single Line Comment
program that are not executed by the compiler • Syntax:
and interpreter. //This is single line comment
• Why do we use comments in a code? 2. Multi Line Comment
• Comments are used to make the program more • Syntax:
readable by adding the details of the code. 1. /*
• It makes easy to maintain the code and to find the 2. This
errors easily. 3. is
• The comments can be used to provide information 4. multi line
or explanation about the variable, method, class, 5. comment
or any statement. 6. */
• It can also be used to prevent the execution of 3. Documentation Comment
program code while testing the alternative code. • Syntax:
• Types of Java Comments 1. /**
• There are three types of comments in Java. 2. *
3. *We can use various tags to depict the paramete
r
4. *or heading or author name
5. *We can also use HTML tags
6. *
7. */
Department of Applied Computational Science & Engg.
Course Code : Course Name:

Datatypes in Java
• Data Types in Java
• Data types specify the different sizes and
values that can be stored in the variable.
There are two types of data types in Java:
1. Primitive data types: The primitive data
types include boolean, char, byte, short, int,
long, float and double.
2. Non-primitive data types: The non-primitive
data types include Classes, Interfaces,
and Arrays.
Department of Applied Computational Science & Engg.
Course Code : Course Name:

Datatypes in Java

Data Type Default Value Default size

boolean false 1 bit

char '\u0000' 2 byte

byte 0 1 byte

short 0 2 byte

int 0 4 byte

long 0L 8 byte

float 0.0f 4 byte

double 0.0d 8 byte


Department of Applied Computational Science & Engg.
Course Code : Course Name:

Variables in Java
• A variable is a container which holds the value while the Java program is executed. A variable is assigned with a
data type.
• Variable is a name of memory location. There are three types of variables in java: local, instance and static.
• There are two types of data types in Java: primitive and non-primitive.
• Variable
• A variable is the name of a reserved area allocated in memory. In other words, it is a name of the memory location. It
is a combination of "vary + able" which means its value can be changed.
• Types of Variables
• There are three types of variables in Java:
• 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, is called an instance variable. It is not
declared as static.
• It is called an instance variable because its value is instance-specific and is not shared among instances.
• 3) Static variable
• A variable that is declared as static is called a static variable. It cannot be local. You can create a single copy of the
static variable and share it among all the instances of the class. Memory allocation for static variables happens only
once when the class is loaded in the memory.
Department of Applied Computational Science & Engg.
Course Code : Course Name:

Variables in Java
1. public class A
2. {
3. static int m=100;//static variable
4. void method()
5. {
6. int n=90;//local variable
7. }
8. public static void main(String args[])
9. {
10. int data=50;//instance variable
11. }
12. }//end of class
Department of Applied Computational Science & Engg.
Course Code : Course Name:

Operators in Java
Operator Type Category Precedence
Unary postfix expr++ expr--
prefix ++expr --expr +expr -
expr ~ !
Arithmetic multiplicative */%
additive +-
Shift shift << >> >>>
Relational comparison < > <= >= instanceof
equality == !=
Bitwise bitwise AND &
bitwise exclusive OR ^

bitwise inclusive OR |
Logical logical AND &&
logical OR ||
Ternary ternary ?:
Assignment assignment = += -= *= /= %= &= ^= |
= <<= >>= >>>=
Department of Applied Computational Science & Engg.
Course Code : Course Name:

Control Flow in Java


• Java compiler executes the code from top to bottom. The statements in the code are
executed according to the order in which they appear. However, Java provides
statements that can be used to control the flow of Java code. Such statements are
called control flow statements. It is one of the fundamental features of Java, which
provides a smooth flow of program.
• Java provides three types of control flow statements.
1. Decision Making statements
1. if statements
2. switch statement
2. Loop statements
1. do while loop
2. while loop
3. for loop
4. for-each loop
3. Jump statements
1. break statement
2. continue statement
Department of Applied Computational Science & Engg.
Course Code : Course Name:

Control Flow in Java


• 1) If Statement: • Student.java
• In Java, the "if" statement is used to evaluate a 1. public class Student {
condition. The control of the program is diverted 2. public static void main(String[] args) {
depending upon the specific condition. The 3. int x = 10;
condition of the If statement gives a Boolean
4. int y = 12;
value, either true or false. In Java, there are four
types of if-statements given below. 5. if(x+y > 20) {
1. Simple if statement 6. System.out.println("x + y is greater than 20");
2. if-else statement 7. }
3. if-else-if ladder 8. }
4. Nested if-statement 9. }
• 1) Simple if statement: • Output:
• It is the most basic statement among all control • x + y is greater than 20
flow statements in Java. It evaluates a Boolean
expression and enables the program to enter a
block of code if the expression evaluates to true.
• Syntax of if statement is given below.
1. if(condition) {
2. statement 1; //executes when condition is true
3. }
Department of Applied Computational Science & Engg.
Course Code : Course Name:

Control Flow in Java


• 2) if-else statement • Student.java
• The if-else statement is an extension to the if- 1. public class Student {
statement, which uses another block of code, i.e., 2. public static void main(String[] args) {
else block. The else block is executed if the 3. int x = 10;
condition of the if-block is evaluated as false.
4. int y = 12;
• Syntax:
5. if(x+y < 10) {
1. if(condition) {
6. System.out.println("x + y is less than 10");
2. statement 1; //executes when condition is true
7. } else {
3. }
8. System.out.println("x + y is greater than 20");
4. else{
9. }
5. statement 2; //executes when condition is false
10. }
6. }
11. }
• Output:
• x + y is greater than 20
Department of Applied Computational Science & Engg.
Course Code : Course Name:

Control Flow in Java


• 3) if-else-if ladder: • Student.java
• The if-else-if statement contains the if-statement 1. public class Student {
followed by multiple else-if statements. In other 2. public static void main(String[] args) {
words, we can say that it is the chain of if-else 3. String city = "Delhi";
statements that create a decision tree where the
4. if(city == "Meerut") {
program may enter in the block of code where the
condition is true. We can also define an else 5. System.out.println("city is meerut");
statement at the end of the chain. 6. }else if (city == "Noida") {
• Syntax of if-else-if statement is given below. 7. System.out.println("city is noida");
1. if(condition 1) { 8. }else if(city == "Agra") {
2. statement 1; //executes when condition 1 is true 9. System.out.println("city is agra");
3. } 10. }else {
4. else if(condition 2) { 11. System.out.println(city);
5. statement 2; //executes when condition 2 is true 12. }
6. } 13. }
7. else { 14. }
8. statement 2; // • Output:
executes when all the conditions are false • Delhi
9. }
Department of Applied Computational Science & Engg.
Course Code : Course Name:

Control Flow in Java


• 4. Nested if-statement • Student.java
• In nested if-statements, the if statement can 1. public class Student {
contain a if or if-else statement inside another if 2. public static void main(String[] args) {
or else-if statement. 3. String address = "Delhi, India";
• Syntax of Nested if-statement is given below. 4. if(address.endsWith("India")) {
1. if(condition 1) { 5. if(address.contains("Meerut")) {
2. statement 1; //executes when condition 1 is true 6. System.out.println("Your city is Meerut");
3. if(condition 2) { 7. }else if(address.contains("Noida")) {
4. statement 2; //executes when condition 2 is true 8. System.out.println("Your city is Noida");
5. } 9. }else {
6. else{ 10. System.out.println(address.split(",")[0]);
7. statement 2; //executes when condition 2 is false 11. }
8. } 12. }else {
9. } 13. System.out.println("You are not living in India");

14. }
15. }
16. }
• Output:
• Delhi
Department of Applied Computational Science & Engg.
Course Code : Course Name:

Control Flow in Java


• Switch Statement:
• In Java, Switch statements are similar to if-else-if statements. The switch statement contains multiple
blocks of code called cases and a single case is executed based on the variable which is being switched.
The switch statement is easier to use instead of if-else-if statements. It also enhances the readability of the
program.
• Points to be noted about switch statement:
• The case variables can be int, short, byte, char, or enumeration. String type is also supported since version
7 of Java
• Cases cannot be duplicate
• Default statement is executed when any of the case doesn't match the value of expression. It is optional.
• Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
• While using switch statements, we must notice that the case expression will be of the same type as the
variable. However, it will also be a constant value.
Department of Applied Computational Science & Engg.
Course Code : Course Name:

Control Flow in Java


1. switch (expression){ 1. public class Student implements Cloneable {
2. case value1: 2. public static void main(String[] args) {
3. statement1; 3. int num = 2;
4. break; 4. switch (num){
5. . 5. case 0:
6. . 6. System.out.println("number is 0");
7. . 7. break;
8. case valueN: 8. case 1:
9. statementN; 9. System.out.println("number is 1");
10. break; 10. break;
11. default: 11. default:
12. default statement; 12. System.out.println(num);
13. } 13. }
14. }
15. }

• Output:
• 2
Department of Applied Computational Science & Engg.
Course Code : Course Name:

Control Flow in Java


• Loop Statements
• In programming, sometimes we need to execute the block of code repeatedly while some
condition evaluates to true. However, loop statements are used to execute the set of
instructions in a repeated order. The execution of the set of instructions depends upon a
particular condition.
• In Java, we have three types of loops that execute similarly. However, there are differences in
their syntax and condition checking time.
1. for loop
2. while loop
3. do-while loop
Department of Applied Computational Science & Engg.
Course Code : Course Name:

Control Flow in Java


• Java for loop
• In Java, for loop is similar
to C and C++. It enables us to
initialize the loop variable,
check the condition, and
increment/decrement in a single
line of code. We use the for
loop only when we exactly
know the number of times, we
want to execute the block of
code.
1. for(initialization, condition, inc
rement/decrement) {
2. //block of statements
3. }
Department of Applied Computational Science & Engg.
Course Code : Course Name:

Control Flow in Java


• Calculation.java
1. public class Calculattion {
2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. int sum = 0;
5. for(int j = 1; j<=10; j++) {
6. sum = sum + j;
7. }
8. System.out.println("The sum of first 10 natural numbers is " + sum);
9. }
10. }
• Output:
• The sum of first 10 natural numbers is 55
Department of Applied Computational Science & Engg.
Course Code : Course Name:

Control Flow in Java


Calculation.java
• Java for-each loop 1. public class Calculation {
• Java provides an enhanced for loop to traverse the 2. public static void main(String[] args) {
data structures like array or collection. In the for- 3. // TODO Auto-generated method stub
each loop, we don't need to update the loop
4. String[] names = {"Java","C","C+
variable. The syntax to use the for-each loop in
+","Python","JavaScript"};
java is given below.
5. System.out.println("Printing the content of the arr
ay names:\n");
6. for(String name:names) {
1. for(data_type var : array_name/collection_name)
7. System.out.println(name);
{
8. }
2. //statements
9. }
3. }
10. }
Output:
• Printing the content of the array names: Java C
C++ Python JavaScript
1. Java
2. C
3. C++
4. Python
5. JavaScript
Department of Applied Computational Science & Engg.
Course Code : Course Name:

Control Flow in Java


• Java while loop
• The while loop is also used to iterate over the
number of statements multiple times. However, if
we don't know the number of iterations in
advance, it is recommended to use a while loop.
Unlike for loop, the initialization and
increment/decrement doesn't take place inside the
loop statement in while loop.
• It is also known as the entry-controlled loop since
the condition is checked at the start of the loop. If
the condition is true, then the loop body will be
executed; otherwise, the statements after the loop
will be executed.
• The syntax of the while loop is given below.
1. while(condition){
2. //looping statements
3. }
Department of Applied Computational Science & Engg.
Course Code : Course Name:

Control Flow in Java


• Calculation .java
1. public class Calculation {
2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. int i = 0;
5. System.out.println("Printing the list of first 10 even numbers \n");
6. while(i<=10) {
7. System.out.println(i);
8. i = i + 2;
9. }
10. }
11. }
• Output:
• Printing the list of first 10 even numbers
• 0
• 2
• 4
• 6
• 8
• 10
Department of Applied Computational Science & Engg.
Course Code : Course Name:

Control Flow in Java


• Java do-while loop
• The do-while loop checks the condition at the end
of the loop after executing the loop statements.
When the number of iteration is not known and
we have to execute the loop at least once, we can
use do-while loop.
• It is also known as the exit-controlled loop since
the condition is not checked in advance. The
syntax of the do-while loop is given below.
1. do
2. {
3. //statements
4. } while (condition);
5.
Department of Applied Computational Science & Engg.
Course Code : Course Name:

Control Flow in Java


• Calculation.java
1. public class Calculation {
2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. int i = 0;
5. System.out.println("Printing the list of first 10 even numbers \n");
6. do {
7. System.out.println(i);
8. i = i + 2;
9. }while(i<=10);
10. }
11. }
• Output:
• Printing the list of first 10 even numbers
• 0
• 2
• 4
• 6
• 8
• 10
Department of Applied Computational Science & Engg.
Course Code : Course Name:

Control Flow in Java


• Java break statement • BreakExample.java
• As the name suggests, the break statement is used 1. public class BreakExample {
to break the current flow of the program and 2. public static void main(String[] args) {
transfer the control to the next statement outside a 3. // TODO Auto-generated method stub
loop or switch statement. However, it breaks only
4. for(int i = 0; i<= 10; i++) {
the inner loop in the case of the nested loop.
5. System.out.println(i);
• The break statement cannot be used
independently in the Java program, i.e., it can 6. if(i==6) {
only be written inside the loop or switch 7. break;
statement. 8. }
• The break statement example with for loop 9. }
• Consider the following example in which we have 10. }
used the break statement with the for loop. 11. }
• Output:
• 0
• 1
• 2
• 3
• 4
• 5
• 6
Department of Applied Computational Science & Engg.
Course Code : Course Name:

Control Flow in Java


• Java continue statement 1. public class ContinueExample {
• Unlike break statement, the continue 2. public static void main(String[] args) {
statement doesn't break the loop, whereas, it skips 3. // TODO Auto-generated method stub
the specific part of the loop and jumps to the next 4. for(int i = 0; i<= 2; i++) {
iteration of the loop immediately.
5. for (int j = i; j<=5; j++) {
• Consider the following example to understand the
6. if(j == 4) {
functioning of the continue statement in Java.
7. continue;
8. }
9. System.out.println(j);
10. }
11. }
12. }
13. }
• Output:
• 01235
• 1235
• 235
Department of Applied Computational Science & Engg.
Course Code : Course Name:

Array in Java
• Java array is an object which contains elements
of a similar data type. Additionally, The elements
of an array are stored in a contiguous memory
location. It is a data structure where we store
similar elements. We can store only a fixed set of
elements in a Java array.
• Array in Java is index-based, the first element of
the array is stored at the 0th index, 2nd element is
stored on 1st index and so on.
• Advantages
• Code Optimization: It makes the code
optimized, we can retrieve or sort the data
efficiently.
• Random access: We can get any data located at
an index position.
• Disadvantages
• Size Limit: We can store only the fixed size of
elements in the array. It doesn't grow its size at
runtime. To solve this problem, collection
framework is used in Java which grows
automatically.
Department of Applied Computational Science & Engg.
Course Code : Course Name:

Array in Java

• Types of Array in java 1. class Testarray{


• There are two types of array. 2. public static void main(String args[]){
• Single Dimensional Array 3. int a[]=new int[5];//declaration and instantiation
• Multidimensional Array 4. a[0]=10;//initialization
• Single Dimensional Array in Java 5. a[1]=20;
• Syntax to Declare an Array in Java 6. a[2]=70;
1. dataType[] arr; (or) 7. a[3]=40;
2. dataType []arr; (or) 8. a[4]=50;
3. dataType arr[]; 9. //traversing array
• Instantiation of an Array in Java 10. for(int i=0;i<a.length;i++)//
length is the property of array
1. arrayRefVar=new datatype[size];
11. System.out.println(a[i]);
12. }}

• Output:
• 10
• 20
• 70
• 40
• 50
Department of Applied Computational Science & Engg.
Course Code : Course Name:

Control Flow in Java


1. //Java Program to demonstrate the way of passing an array
2. //to method.
3. class Testarray2{
4. //creating a method which receives an array as a parameter
5. static void min(int arr[]){
6. int min=arr[0];
7. for(int i=1;i<arr.length;i++)
8. if(min>arr[i])
9. min=arr[i];
10.
11. System.out.println(min);
12. }
13.
14. public static void main(String args[]){
15. int a[]={33,3,4,5};//declaring and initializing an array
16. min(a);//passing array to method
17. }}

• Output:
• 3
Department of Applied Computational Science & Engg.
Course Code : Course Name:

Control Flow in Java


• ArrayIndexOutOfBoundsException
• The Java Virtual Machine (JVM) throws an ArrayIndexOutOfBoundsException if length of the array in
negative, equal to the array size or greater than the array size while traversing the array.
1. //Java Program to demonstrate the case of
2. //ArrayIndexOutOfBoundsException in a Java Array.
3. public class TestArrayException{
4. public static void main(String args[]){
5. int arr[]={50,60,70,80};
6. for(int i=0;i<=arr.length;i++){
7. System.out.println(arr[i]);
8. }
9. }}
• Output:
• Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4 at
TestArrayException.main(TestArrayException.java:5)
• 50
• 60
• 70
• 80
Department of Applied Computational Science & Engg.
Course Code : Course Name:

Control Flow in Java


• Example of Multidimensional Java Array
• Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.
1. //Java Program to illustrate the use of multidimensional array
2. class Testarray3{
3. public static void main(String args[]){
4. //declaring and initializing 2D array
5. int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
6. //printing 2D array
7. for(int i=0;i<3;i++){
8. for(int j=0;j<3;j++){
9. System.out.print(arr[i][j]+" ");
10. }
11. System.out.println();
12. }
13. }}
• Output:
• 123
• 245
• 445
Department of Applied Computational Science & Engg.
Course Code : Course Name:

String in Java
• String is a sequence of characters. But in Java, string is an object that represents a sequence of characters.
The java.lang.String class is used to create a string object.
• In Java, string is basically an object that represents sequence of char values. An array of characters works
same as Java string. For example:
1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);
• is same as:
1. String s="javatpoint";
• Java String class provides a lot of methods to perform operations on strings such as compare(), concat(),
equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.

• How to create a string object?


• There are two ways to create String object:
1. By string literal
2. By new keyword
Department of Applied Computational Science & Engg.
Course Code : Course Name:

String in Java
• 1) String Literal
• Java String literal is created by using double quotes.
For Example:
1. String s="welcome";
• Each time you create a string literal, the JVM checks
the "string constant pool" first. If the string already
exists in the pool, a reference to the pooled instance is
returned. If the string doesn't exist in the pool, a new
string instance is created and placed in the pool. For
example:
1. String s1="Welcome";
2. String s2="Welcome";//
It doesn't create a new instance
Department of Applied Computational Science & Engg.
Course Code : Course Name:

String in Java
• 2) By new keyword • StringExample.java
1. String s=new String("Welcome");// 1. public class StringExample{
creates two objects and one reference variable 2. public static void main(String args[]
• In such case, JVM will create a new string ){
object in normal (non-pool) heap memory, and 3. String s1="java";//
the literal "Welcome" will be placed in the creating string by Java string literal
string constant pool. The variable s will refer to 4. char ch[]={'s','t','r','i','n','g','s'};
the object in a heap (non-pool).
5. String s2=new String(ch);//
converting char array to string
6. String s3=new String("example");//
creating Java string by new keyword

7. System.out.println(s1);
8. System.out.println(s2);
9. System.out.println(s3);
10. }}

• Output:
• java
• strings
• example
Department of Applied Computational Science & Engg.
Course Code : Course Name:

Recommended Books
Text books

Reference Book

Additional online materials

Program Name: Program Code:


THANK YOU

You might also like