Java Notes - Unit 1 Chapter 2
Java Notes - Unit 1 Chapter 2
Course Outcomes :
Course Prerequisites
Basic Programming Concepts
Procedural Programming
Understanding Algorithms and Problem Solving
Memory Management
Data Structures
Basic Command-Line Usage
Understanding of Databases
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
• 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:
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:
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 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:
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:
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:
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
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
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:
14. }
15. }
16. }
• Output:
• Delhi
Department of Applied Computational Science & Engg.
Course Code : Course Name:
• Output:
• 2
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
• Output:
• 10
• 20
• 70
• 40
• 50
Department of Applied Computational Science & Engg.
Course Code : Course Name:
• Output:
• 3
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.
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