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

java unit 1 NOTES

The document provides an introduction to Java programming, covering key concepts such as Object-Oriented Programming (OOP) principles, Java features, and the Java environment. It explains the syntax and functionality of classes and objects, inheritance, encapsulation, polymorphism, and data types, including primitive and non-primitive types. Additionally, it discusses variables, command line arguments, and the scope of variables in Java.

Uploaded by

khanumjameela379
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

java unit 1 NOTES

The document provides an introduction to Java programming, covering key concepts such as Object-Oriented Programming (OOP) principles, Java features, and the Java environment. It explains the syntax and functionality of classes and objects, inheritance, encapsulation, polymorphism, and data types, including primitive and non-primitive types. Additionally, it discusses variables, command line arguments, and the scope of variables in Java.

Uploaded by

khanumjameela379
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 132

❑Introduction and basics of java programming

• What is oops?
• Difference between c and java?
• Oops concepts-
class,object,Encapsulation,Inheritance,Polymorphism,Dynamic
Binding
• History of java
• Java features
• Java Environment-JDK,JRE,JVM,API
• Tokens,Identifiers,Constants,keywords
Basic concepts of OOPS programming

Class is a template or blueprint used to create objects and to
define object data types and methods.
A class is a group of objects which have common properties.
A class — in the context of Java — is a
template used to create objects and to
define object data types and methods.
Classes are categories, and objects are items
within each category. All class objects should
have the basic class properties.

Syntax of Class in Java


class <class_name>

fields or data members or attributes;


method;

}
Object
An object is a real world entity.
An object is an instance of a class.

Objects have states and behaviors. Example: A dog has


states - color, name, breed as well as behaviors –
wagging the tail, barking, eating.

•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.
Object Syntax in Java
ClassName ReferenceVariable = new ClassName();

Dog tuffy = new Dog("tuffy","papillon",5, "white");


Inheritance
• Inheritance in Java is a mechanism in which one
object acquires all the properties and behaviors of a
parent object. It is an important part of OOPs (Object
Oriented programming system).
• The idea behind inheritance in Java is that you can
create new classes that are built upon existing classes.
• When you inherit from an existing class, you can
reuse methods and fields of the parent class.

• java Inheritance provides a reusability mechanism in


object-oriented programming for the users to reuse the
existing code within the new applications.
• It does this by allowing the programmer to build a
relationship between a new class and an existing class
and define a new code in terms of existing code. This
relationship is known as parent-child relationship in
java.
A car is a type of Vehicle, so inheritance hierarchy might begin from the Vehicle class as follows:
The syntax of Java Inheritance
1.class Subclass-name extends Superclass-name
2.{
3. //methods and fields
4.}
Encapsulation
Encapsulation is one of the four fundamental OOP concepts.
Polymorphism
• Polymorphism is the ability of an object or a
function to take on many forms.
• There are 2 types of polymorphism
• Compile time polymorphism
• Runtime polymorphism
Dynamic Binding

• “Dynamic” means “run time”, and “binding”


means “association”. So the term dynamic
binding indicates run time association
of objects by java virtual machine.
• Connecting a method call to the method
body is known as binding.
• In dynamic binding, the method call is
resolved at runtime, which means the
method to be executed is determined at the
time of execution.
Data Abstraction
• Data abstraction is the process of
hiding certain details and showing
only essential information to the
user. Abstraction can be achieved
with either abstract classes or
interfaces.
❑ Features of java
Platform Independent

Multithreading
Simple
Distributed

The Just-In-Time (JIT) compiler is a component of the Java™ Runtime Environment


that improves the performance of Java applications at run time.

The JIT compiler helps improve the performance of Java programs by compiling
bytecodes into native machine code at run time.
Machine code ,compiling it just in time to run.
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 an extensive amount of run-
time information that can be used to verify and resolve accesses to objects at run-
time.
❑ Java Environment
• JDK –Java Development Kit- collection
of tools for developing and running the
java programs.
• JSL-Java Standard Library Contains
classes and methods also called API
(Application programming Interface)
• JVM-Java virtual Machine provides a
runtime environment in which we can
execute bytecode.
• JRE-java runtime environmemt-
collection of tools (developmemt of
applications and runtime
environment).JVM is a part of JRE.
• JIT –just in time complier is a code
generator that converts java bytecode 1.JDK is for development purposes whereas JRE is for running
into machine language instructions. the java programs.
2.JDK and JRE both contain JVM so that we can run our java
JVM is called virtual because it program.
provides an interface that does not 3.JVM is the heart of Java programming language and provides
depend on the underlying operating platform independence.
system and machine hardware.
What are the Java tokens?
Java tokens are the basic building
blocks of a Java program. They are
the smallest units of a program,
and they include keywords,
identifiers, operators, literals,
separators, and comments.
Separators are symbols that
separate different parts of a program.

Variables Sum,age ,rollno


DATA TYPES
•Data type is used for declaring variable.
•Data type tells about the size and value type which is
stored in the variable.
•Datatype specifies what type of value a variable can
store.
•Data types hold different kind of information.
Primitive datatypes are predefined by the language and
named by a keyword.(Built-in datatypes)

Primitive data types in Java are those data types whose variables
can store only one value at a time. We cannot store multiple
values of the same type. These data types are pre-defined in Java.
They are named by a Keyword.
Non-primitive data types are created by programmer. It
is also called as ‘Reference data types’ because it refers a
memory location where data is stored. It is also called as
user defined datatypes or derived datatypes.
Primitive datatypes declaration in java
char Data Type in Java
In Java, the data type used to store characters
is char. A character data type represents a single
character.
A character is an identifier which is enclosed
within single quotes. In java to represent character
data, we use a data type called char.
This data type takes two byte (16-bit) since it
follows Unicode character set.
char letter = 'A’;
Example:

char numChar = '5';


Boolean

The boolean data type in Java is used for representing


conditional/logical values true and false.
• public class B
• { public static void main(String[] args)
• { boolean bol1 = true;
• if(bol1==true)
• System.out.println("It is True");
• else
• System.out.println("It is False");
• }
•}
Non –primitive data types
• Non-primitive data types are created by programmers. They are not
predefined in java like primitive data types. These data types are used
to store a group of values or several values.
• They are also called Reference data types because they
cannot store the value of a variable directly in memory. Non-
primitive data types do not store the value itself but they store a
reference or address (memory location) of that value.
• long modelNumber = 62548723468;
• Strings: String is a sequence of characters. But in Java,
a string is an object that represents a sequence of
characters. The java.lang.String class is used to create a string
object.
• Ways to create a string object:
• There are 2 ways of creating a String object:
• By using a string literal: Java String literal can be created just by
using double-quotes.

• String myLine = “Welcome to Java class”;


• By using a “new” keyword: Java String can also be created by
using a new keyword. For example:
• String myLine = new String(“Welcome to Java class”);
• public class Stringtest
• {
• public static void main(String args[])
• {
• String string1 = "Hello World"; // declaring string using string literals

• String string2 = new String("This is a Java class "); //declaring string using new
operator

• System.out.println(string1);
• System.out.println(string2);
• }
• }
• Output:
• Hello World
This is a Java Tutorial
• Arrays: Java array is an object which contains elements of a similar
data type. Arrays store one or more values of a specific data type and
provide indexed access to store the same.

The valid syntax for array The valid syntax for array initialization can be:
declaration can be: array_name = new data-type [size of array];
data-type array_name [ ]; array_name = new data-type {elements of array using
data-type [ ] array_name; using commas};
• public class Arraydemo
•{
• public static void main(String args[])
•{
• int [ ] marksOfStudents = new int[ ] {65, 90, 78, 60, 84 };
• System.out.println("Marks of first student: " +marksOfStudents[0]);
• System.out.println("Marks of second student: "
+marksOfStudents[1]);
• System.out.println("Marks of third student: " +marksOfStudents[2]);
• System.out.println("Marks of fourth student: " +marksOfStudents[3]);
• System.out.println("Marks of fifth student: " +marksOfStudents[4]);
•}
•}
• Marks of first student: 65
Marks of second student: 90
Marks of third student: 78
Marks of fourth student: 60
Marks of fifth student: 84
• Classes: A class is a collection of objects of the same type. It is a
user-defined blueprint or prototype which defines the behavior or
state of objects. A class contains fields(variables) and methods to
describe the behavior of an object.
• We create a class using a class keyword.
• A class can be declared using the following components in the order-
• 1. Access modifiers: Access modifiers define the access privileges of a
class. A class can be public or it has default access.
• 2. Class name: The name of a class should represent a noun and must
start with a capital letter. These are the best practices to be kept in
mind while declaring any class.
• 3. Body: The class body contains properties and methods. The body is
always enclosed by curly braces { }.
• Syntax of writing a class:
• AccessModifier class class_name
• {
• Class body - variables and methods();
• }

• public class MyClass


• {
• int x = 5;
• void display()
• {
• // methodBody;
• }
• }
• Java Objects
• It is a basic unit of Object-Oriented
Programming which represents the real-
world entities. An object is an instance of a
class. It defines the state and behavior of
real-life entities.
• State: It represents the attributes and
properties of an object.
• Behavior: Methods define the behavior of an
object. It also reflects the communication of
one object with the other objects.
• Identity: It gives a unique name to an object
which allows one object to interact with
other objects.
• Syntax of creating an object of a class:
• To create an object of a class, specify the class name, followed by the object name, by using the new keyword-
• Class name object_Name = new Class name();
• Example:
• MyClass object1 = new MyClass();
• public class Student
• {
• int marks = 76;
• public static void main(String[] args)
• {
• Student student1 = new Student(); // creating object of the class by using new operator

• System.out.println("Marks of student: " +student1.marks); //Accessing the property “marks” of the class with the help of an object.

• }

• }
• Output:
• Marks of student: 76
• An interface behaves like a blueprint of a class,
which specifies “what a class has to do and not how
it will do”.
• Interface: Like a class, an interface can have
methods and variables, but the methods
declared in interface are by default abstract (only
method signature, no body).

• In the real-world, one user defines an interface, but


different user provides its implementation.
Moreover, it is finally used by some other user.
• Syntax of writing interfaces:
• To declare an interface, we just write the keyword
“interface” followed by the interface name:
• interface interface_name
• To use an interface in a class, we have to append the
keyword “implements” after the class name followed
by the interface name.
• class class_name implements interface_name
• //creating an interface
• interface Runnable
• {
• public void run(); //an abstract method
• }
• // implementing the interface
• public class Person implements Runnable
• {
• public void run()
• {
• System.out.println("This person can run");
• }
• public static void main(String args[])
• {
• Person person1 = new Person();
• person1.run();
• }
• }
Variables in java
• A Variable is an identifier
that denotes a storage
location used to store a data
value .
• 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.

Note: An Identifier is simply a sequence of characters. In other words, we can say, an Identifier is just a word or a
single character that is used in our program. If the identifier is named according to the rules then only it is considered
to be valid otherwise the compiler will generate an error.
➢Unlike constants that remain unchanged during the execution of a
program, a variable may take different values at different times during
the execution of the program.
➢Variable name should be meaningful as to
reflect what it represents in the program.
EXAMPLES:
Average
Height
Total_height
Class strength
• Variable names may consist of alphabets,digits, the underscore(_)
and dollar characters, subject to the following conditions:
Declaration of a Variable:
• In java, variables are the names of storage locations.
• Declaration of variables does 3 things:
• 1. It tells the complier what the variable name is.
• 2.It specifies what type the variable will hold
• 3.The place of declaration decides the scope of the variable.
• Declaration:
• Type variable 1, variable 2…..
• int count;
• float x,y;
• double pi;
• Command Line Arguments
1.Command Line Argument
2.Simple example of command-line
argument
3.Example of command-line argument
that prints all the values
• The java command-line argument is
an argument i.e. passed at the time
of running the java program.
• The arguments passed from the
console can be received in the java
program and it can be used as an
input.
• So, it provides a convenient way to
check the behavior of the program
for the different values. You can
pass N (1,2,3 and so on) numbers of
arguments from the command
prompt.
Types of Variables/Scope of the variables

A Java variable is a piece of memory that can contain a data


value

In programming, a variable can be declared and defined inside a


class, method, or block. It defines the scope of the variable i.e.
the visibility or accessibility of a variable. Variable declared
inside a block or method are not visible to outside.
• 1) Local Variable
• A variable declared inside the body of the methods, constructors or any block is called local variable.
• A local variable cannot be defined with "static" keyword.
• There is no default value for local variables so local variables should be declared and an initial value
should be assigned before the first use.
• Eg: int assignment=0;
• 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.
• Instance variables have default values. For numbers the default value is 0, for Boolean it is false and
for object references it is null.
• 3) Static variable/class Variable
• Class variables also known as static variables are declared with the static keyword in a class, but
outside a method, constructor or a block.
• Class variables have default values. For numbers the default value is 0, for Boolean it is false and for
object references it is null.
• The class variables are visible for all methods, constructors and block in the class.
• static variables can be accessed by calling with the class name ClassName. VariableName.
• Different Types of Variables in Java
• 1) Local Variable :
• A variable that is declared and used inside the body of methods, constructors, or blocks is
called local variable in java. It is called so because local variables are not available for use
from outside.
• We must assign a local variable with a value at the time of creating. If you use a local variable
without initializing a value, you will get a compile-time error like “variable x not have been
initialized”.
• public void mySchool()
• {
• // Declaration of local variables.
• String schoolName; // Compilation error due to not initializing of value.
• System.out.println("Name of School: " +schoolName);
• }
We cannot use access modifiers with local variables.
The local variables are visible only within the declared constructors, methods, or blocks.
A local variable is not equivalent to an instance variable.
A local variable cannot be static.
Sample program to demonstrate Scope of
Variables.
2. Instance Variables:
Overloading
Overloading allows different methods to have the
same name, but different signatures where the
signature can differ by the number of input
parameters or type of input parameters or both.
Overloading is related to compile-time (or static)
polymorphism.

Method overloading is a concept that allows to


declare multiple methods with same name but
different parameters in the same class.

Method overloading is one of the ways through which


java supports polymorphism. Polymorphism is a concept
of object oriented programming that deal with multiple
forms.
Note:Polymorphism is the ability of an object to take on different forms.
• class Overload
• {
• void sum (int a, int b)
• {
• System.out.println("sum of two integers:"+(a+b)) ;
• }
• void sum (float a, float b)
• {
• System.out.println("sum of two float numbers"+(a+b));
• }
• public static void main (String[] args)
• {
• Overload ob = new Overload();
• ob.sum (10,20); //sum(int a, int b) is method is called.
• ob.sum (4.6f, 3.8f); //sum(float a, float b) is called.
• }
• }
Java Math class
The Math class contains methods for performing basic numeric operations such as the
elementary exponential,
logarithm, square root, and trigonometric functions.
• Java Math class provides several methods to work on math calculations like min(), max(), avg(), sin(), cos(), tan(), round(), ceil(), floor(), abs()
etc.
• The Java Math class has many methods that allows you to perform mathematical tasks on numbers.
• Math.max(x,y)

• The Math.max(x,y) method can be used to find the highest value of x and y:

• Math.max(5, 10);

• public class Main {


• public static void main(String[] args) {
• System.out.println(Math.max(5, 10));
• }
• }
• Output: 10
Math.min(x,y)

The Math.min(x,y) method can be used to find the lowest value


of x and y:

Math.min(5, 10);

Math.sqrt(x)
The Math.sqrt(x) method returns the square root of x:

Math.sqrt(64);
1. public class JavaMathExample1
2. {
3. public static void main(String[] args)
4. {
5. double x = 28;
6. double y = 4;
7.
8. // return the maximum of two numbers
9. System.out.println("Maximum number of x and y is: " +Math.max(x, y));
10.
11. // return the square root of y
12. System.out.println("Square root of y is: " + Math.sqrt(y));
13.
14. //returns 28 power of 4 i.e. 28*28*28*28
15. System.out.println("Power of x and y is: " + Math.pow(x, y));
16.
17.
1.// return the logarithm of given value
2. System.out.println("Logarithm of x is: " + Math.log(x));
3. System.out.println("Logarithm of y is: " + Math.log(y));
4.
5. // return the logarithm of given value when base is 10
6. System.out.println("log10 of x is: " + Math.log10(x));
7. System.out.println("log10 of y is: " + Math.log10(y));
8.
9. // return a power of 2
10. System.out.println("exp of a is: " +Math.exp(x));
11.
12. }
13.}
Operators in java
• What are the Java Operators?
Arithimetic Operators:
• Arithmetic operators are used to perform
arithmetic operations on variables and data.
• 1. Addition(+): This operator is a binary
operator and is used to add two operands.

• num1 + num2

Example:
num1 = 10, num2 = 20 ;
sum = num1 + num2 ;
= 30
• 2. Subtraction(-): This operator is a binary operator and is used to subtract
two operands.
• Syntax:
num1 - num2

• Example:
num1 = 20, num2 = 10
sub = num1 - num2 = 10

3. Multiplication(*): This operator is a binary operator and is used to multiply


two operands.
num1 * num2

Example:
num1 = 20, num2 = 10 mult = num1 * num2 = 200
• 4. Division(/): This is a binary operator that is used to divide the
first operand(dividend) by the second operand(divisor) and give the
quotient as a result.
• num1 / num2
• num1 = 20, num2 = 10 div = num1 / num2 = 2
• 5. Modulus(%): This is a binary operator that is used to return the
remainder when the first operand(dividend) is divided by the
second operand(divisor).
• Syntax:
• num1 % num2
• num1 = 5, num2 = 2 mod = num1 % num2 = 1
• public class ArithmeticOperator
• {
• public static void main(String[] args) Addition num1+num2 13
• { Subtraction num1-num2 -3
• int add, Multiplication num1*num2 40
• sub, Division num1/num2 0
• mul, Modulus num2%num1 3
• div,
• mod;
• int num1 = 5,
• num2 = 8;
• add = num1 + num2;
• sub = num1 - num2;
• mul = num1 * num2;
• div = num1 / num2;
• mod = num2 % num1;
• System.out.println("Addition num1+num2 " + add);
• System.out.println("Subtraction num1-num2 " + sub);
• System.out.println("Multiplication num1*num2 " + mul);
• System.out.println("Division num1/num2 " + div);
• System.out.println("Modulus num2%num1 " + mod);
• }
2. Relation Operators
• Relational operators are used to check the relationship between two
operands.
• Relational operators are used in decision making and loops.
Logical Operators
• Logical operators are used to
perform logical “AND”, “OR” and
“NOT” operations.
• 1. Logical ‘AND’ Operator (&&)
• This operator returns true when
both the conditions under
consideration are satisfied or are
true. If even one of the two yields public class Land {
false, the operator results false. public static void main(String[] args) {
In Simple terms, cond1 && int x = 5;
System.out.println(x > 3 && x < 10); // returns true because
cond2 returns true when both is greater than 3 AND 5 is less than 10
cond1 and cond2 are true (i.e. }
non-zero). }

condition1 && condition2


2. Logical ‘OR’ Operator (||)
This operator returns true when one of the two conditions under consideration is satisfied or is true.
If even one of the two yields true, the operator results true. To make the result false, both the constraints need to return false.

Syntax:
condition1 || condition2

public class LOR {


public static void main(String[] args) {
int x = 5;
System.out.println(x > 3 || x < 4); // returns true because one of the conditions are true (5 is greater than
3, but 5 is not less than 4)
}
}
3. Logical ‘NOT’ Operator (!)
Unlike the previous two, this is a unary operator and returns true when the condition under consideration is not
satisfied or is a false condition. Basically, if the condition is false, the operation returns true and when the
condition is true, the operation returns false.

public class Main {


public static void main(String[] args) {
int x = 5;
System.out.println(!(x > 3 && x < 10)); // returns false
because ! (not) is used to reverse the result
}
}
Assignment operators
Assignment operators are used to assigning the value on its right to the variable on its left.
These operators are used to assign values to a variable.

The left side operand of the assignment operator is a variable and the right side operand of the assignment
operator is a value.
variable operator value;
Increment and Decrement Operators:
The increment (++) and decrement operator (--) are simply used to increase and decrease the value by one.
Increment and decrement operators are unary operators. We can only apply these operators on a single operand,
hence these operators are called as unary operators.

•Pre increment (++x)


•Post increment (x++)
Pre Increment Operator:
If an Increment operator is used in front of an operand, then it is called as Pre Increment operator.
Post Increment Operator:
If an Increment operator is used after an operand, then is called Post Increment operator.
Bitwise Operators
• Bitwise operators are used to performing the manipulation of
individual bits of a number.
• 3. Bitwise XOR (^)
• This operator is a binary operator, denoted by ‘^.’ It returns bit by
bit XOR of input values, i.e., if corresponding bits are different, it
gives 1, else it shows 0.
JAVA Methods:
• Public: The access level of a public modifier is
everywhere. It can be accessed from within the
class, outside the class, within the package and
outside the package. 1.//save by B.java
2.
1./save by A.java 3.package mypack;
4.import pack.*;
2. 5.
3.package pack; 6.class B{
7. public static void main(String args[]){
4.public class A 8. A obj = new A();
9. obj.msg();
5.{ 10. }
11.}
6.public void msg()
7.{System.out.println("Hello"); Output: Hello
8.}
9.}
Private:The private access modifier is accessible only
within the class.
1. class A{
2. private int data=40; //data member
3. private void msg()
4. {
5. System.out.println("Hello java");
6. }
7. }
8.
9. public class Simple{
10. public static void main(String args[]){
11. A obj=new A();
12. System.out.println(obj.data);//Compile Time Error
13. obj.msg();//Compile Time Error
14. }
15.}
Protected:The protected access modifier is
accessible within package and outside the
package but through inheritance only.
1.//save by A.java 1./save by B.java
2.package mypack;
2.package pack; 3.import pack.*;
3.public class A{ 4.
5.class B extends A{
4.protected void msg() 6. public static void main(String args[]){
7. B obj = new B();
5.{ 8. obj.msg();
6.System.out.println("Hello");} 9. }
10.}
7.} Output:Hello

In this example, we have created the two packages pack and mypack. The A class
of pack package is public, so can be accessed from outside the package. But msg
method of this package is declared as protected, so it can be accessed from
outside the class only through inheritance.
• Default
• If you don't use any modifier, it is treated as default by default. The
default modifier is accessible only within package.
• It cannot be accessed from outside the package. //save by B.java
package mypack;
import pack.*;
• /save by A.java class B{
public static void main(String args[]){
• package pack;
A obj = new A();//Compile Time Error
• class A{ obj.msg();//Compile Time Error
• void msg(){ }
}
• System.out.println("Hello");
• }
• }

• In this example, we have created two classes A


and Simple. A class contains private data
member and private method. We are accessing
these private members from outside the class,
so there is a compile-time error.

You might also like