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

1097 - File - JAVA - Notes (Unit 1)

Uploaded by

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

1097 - File - JAVA - Notes (Unit 1)

Uploaded by

ajith channel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

SRI KALISWARI COLLEGE (Autonomous), SIVAKASI

DEPARTMENT OF COMPUTER APPLICATIONS


CORE COURSE – V: JAVA PROGRAMMING (23UCAC31)

UNIT – I
Introduction: Review of Object Oriented Concepts – History of Java – Java
Buzzwords – JVM Architecture – Data Types – Variables – Scope and Life Time of
Variables – Arrays – Operators – Control Statements – Type Conversion and Casting –
Simple Java Program – Constructors – Methods – Static Block – Static Data – Static
Method String and String Buffer Classes.

Review of Object Oriented Programming Concepts


1. Object Oriented Programming is a paradigm that provides many concepts such
as inheritance, data binding, polymorphism etc.
2. Simula is considered the first object-oriented programming language. The
programming paradigm where everything is represented as an object is known
as a truly object-oriented programming language.
3. Smalltalk is considered as the first truly object-oriented programming language.
OOPs (Object Oriented Programming System)
Object means a real word entity such as pen, chair, table, etc. Object-oriented
programming is a methodology or paradigm used to design a program using classes
and objects. It simplifies the software development and maintenance by providing some
concepts:
 Object
 Class
 Inheritance
 Polymorphism
 Abstraction
 Encapsulation
Object
 Any entity with a state and behavior is known as an object, such as a chair, pen,
table, keyboard, bike, etc. It can be physical and logical.
Class
 Class is a user-defined data type. Class is a collection of data members and
member functions. It can be created using the keyword “class”.
Inheritance
 Deriving a new class (Sub Class) from an old class (Super Class) is called
Inheritance. It provides code reusability. It is used to achieve runtime
polymorphism.
Benefits of Inheritance
1. One of the key benefits of inheritance is to minimize the amount of duplicate
code in an application by sharing common code amongst several subclasses.
2. Inheritance can also make application code more flexible to change because
classes that inherit from a common superclass can be used interchangeably. If
the return type of a method is superclass
3. Reusability - facility to use public methods of a base class without rewriting the
same.
4. Extensibility - extending the base class logic as per the business logic of the
derived class.
Polymorphism
 When one task is performed in different ways i.e. known as polymorphism.
 For example: to draw different shapes using the same method.
 In Java, we use method overloading and method overriding to achieve
polymorphism.
Abstraction
 Hiding internal details and showing functionality is known as abstraction.
 For example: phone call, we don't know the internal processing.
 In Java, we use abstract classes and interfaces to achieve abstraction.
Encapsulation
 Binding (or wrapping) code and data together into a single unit is known as
encapsulation.
 For example: a capsule, is wrapped with different medicines.
 A Java class is an example of encapsulation.

***************************
History of JAVA
 James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java
language project in June 1991. The small team of sun engineers is called the
Green Team.
 Originally designed for small, embedded systems in electronic appliances like
set-top boxes.
 Firstly, it was called "Green Talk" by James Gosling and the file extension was. gt.
 After that, it was called Oak and was developed as a part of the Green project.
 In 1995, Oak was renamed as "Java"
 Initially developed by James Gosling at Sun Microsystems
 JDK 1.0 was released on January 23, 1996.
*************************
JAVA BUZZ Words (or) Features of JAVA
They are also known as java buzzwords. The Java Features given below are simple and
easy to understand.
1. Simple
2. Object-Oriented
3. Portable
4. Platform-independent
5. Secured
6. Robust
7. Architecture neutral
8. Dynamic
9. Interpreted
10. High Performance
11. Multithreaded
12. Distributed
1. Simple
 Java is very easy to learn, and its syntax is simple, clean, and easy to understand.
2. Object-oriented
 Java is an object-oriented programming language.
 Everything in Java is an object.
 Object-oriented means we organize our software as a combination of different
types of objects that incorporate both data and behavior.
3. Portable
 Java is portable because it allows you to carry the Java bytecode to any platform.
It doesn't require any implementation.
4. Platform – Independent
 Java is a write-once, run-anywhere language.
 Java code can be executed on multiple platforms, for example, Windows, Linux,
Sun Solaris, Mac/OS, etc.
 Java code is compiled by the compiler and converted into bytecode.
 Write Once and Run Anywhere (WORA).
5. Secured
 Java is best known for its security.
 Java is secured because of the following
o No explicit Pointer
o Run inside a virtual machine sandbox
o Classloader
o Bytecode Verifier
o Security Manager
6. Robust
Java is robust because:
 It uses strong memory management.
 There is a lack of pointers.
 Java provides automatic garbage collection.
 There are exception-handling and the type checking mechanism in Java.
7. Architecture Neutral
 Java is architecture-neutral because there are no implementation-dependent
features, for example, the size of primitive types is fixed.
8. Dynamic
 Java is a dynamic language.
 It supports the dynamic loading of classes.
 It means classes are loaded on demand.
10. High Performance
 Java is faster than other traditional interpreted programming languages because
Java bytecode is "close" to native code.
11. Multithreaded
 A thread is like a separate program, executing concurrently.
 We can write Java programs that deal with many tasks at once by defining
multiple threads.
12. Distributed
 Java is distributed because it facilitates users to create distributed applications in
Java.
 RMI and EJB are used for creating distributed applications.
***********************
JVM Architecture (or) JAVA Bytecode
Bytecode
 Byte Code can be defined as an intermediate code generated by the compiler
after the compilation of source code (JAVA Program).
 This intermediate code makes Java a platform-independent language.
Working Principle
 The compiler converts the source code or the Java program into the Byte Code
(or machine code)
 Next, the Interpreter executes the byte code on the system.
 The Interpreter can also be called JVM (Java Virtual Machine).
 The byte code is the common piece between the compiler (which creates it) and
the Interpreter (which runs it).

*********************
JAVA Data Types – Refer already given Notes
JAVA Variables
 A variable is a container which holds the value.
 A variable is assigned with a data type.
 There are three types of variables in java: Local, Instance and Static.
 A variable is the name of a reserved area allocated in memory.
Types of Variables and its Scope
There are three types of variables in Java:
1. Local variable
2. Instance variable
3. Static variable
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.
 Scope: Within the block it is declared.
 Lifetime: Until control leaves the block in which it is declared.
Instance Variable
 A variable declared inside the class but outside the body of the method, is called
an instance variable.
 Scope: Throughout the class except in the static methods.
 Lifetime: Until the object of the class stays in the memory.
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.
 Scope: Throughout the class.
 Lifetime: Until the end of the program.
Example
public class var_ble
{
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
public static void main(String args[])
{
int data=50;//instance variable
}
}//end of class

*********************
Arrays
 An array is a collection of similar type of elements which has 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.
Types of Array
There are two types of array.
 One Dimensional Array
 Multidimensional Array
Declaration of Array
To declare an array in Java, use the following syntax:
type[] arrayName;
type: The data type of the array elements
arrayName: The name of the array.
Example
int[] numbers; // Declaring an integer array
 This statement declares an array named numbers that will hold integers.
Creating an Array
 To create an array, you need to allocate memory for it using the new keyword

int[] numbers;
numbers = new int[5];

 This statement initializes the numbers array to hold 5 integers.


One Dimensional Array
 The most common type of array is where elements are stored in a linear order.
 An array with a single subscript is called a one-dimensional array.
 Starting index is ‘0’.
int[] oneDimArray = {1, 2, 3, 4, 5};
Example
import java.io.*;
class new_array {
public static void main (String[] args) {
int [] arr=new int [4];
for(int i=0;i<arr.lenght;i++){
System.out.println(“Value is:”+arr[i]);
}
System.out.println("Array Size:"+arr.length);
}
}
Multidimensional Array
 Arrays with more than one dimension, such as two-dimensional arrays are called
as multi – dimensional arrays.
 Here the elements are stored in row and column order.
 First Subscript represents Row and Second Subscript represents Column
 Multidimensional arrays are arrays of arrays with each element of the array
holding the reference of other arrays.
int[][] multiDimArray = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Example
Refer JAVA Lab Note for Matrix Multiplication Program
*************************
Operators, Control Statements – Refer the already given Notes
Type Casting and Conversion
Type Casting
 A data type is converted into another data type is known as type casting.
 It is used if we want to change the target data type to another data type.
 Remember that the destination data type must be smaller than the source data
type.
In Java, there are two types of casting:
Widening Casting (automatically) - converting a smaller type to a larger type size
byte -> short -> char -> int -> long -> float -> double
Narrowing Casting (manually) - converting a larger type to a smaller size type
double -> float -> long -> int -> char -> short -> byte
Widening Casting
Widening casting is done automatically when passing a smaller size type to a larger size
type
Example
public class type_cast {
public static void main(String[] args) {
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double

System.out.println(myInt); // Outputs 9
System.out.println(myDouble); // Outputs 9.0
}
}
Narrowing Casting
Narrowing casting must be done manually by placing the type in parentheses () in front
of the value
Syntax
target_datatype new_variable = (target_datatype) old_variable;
Target_datatype: It is the data type in which we want to convert the destination data
type.
Example
public class type_cast {
public static void main(String[] args) {
double myDouble = 9.78;
int myInt = (int) myDouble; // Manual casting: double to int

System.out.println(myDouble); // Outputs 9.78


System.out.println(myInt); // Outputs 9
}
}
*************************
Constructor
 A constructor is a special method that is used to initialize objects.
 The constructor is called when an object of a class is created.
 It can be used to set initial values for object
 The constructor name and the class name should be the same.
 The constructor doesn’t have a return type.
 All classes have constructors by default.

Rules for creating Java constructor


There are three rules defined for the constructor.
1. The constructor name must be the same as its class name
2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized

Types of Constructor
There are 2 types of constructor
1. Default Constructor
2. Parameterized Constructor

1. Default Constructor
 A constructor without parameters is called a default constructor.
 Default constructor is invoked if there is no constructor available in the class.
Syntax
Class_name(){
//code
}
Example
class Bike1{
Bike1(){
System.out.println("Bike is created");
}
public static void main(String args[]){
Bike1 b=new Bike1 ();
}
}

2. Parameterized Constructor
 A constructor which has a specific number of parameters is called a
parameterized constructor.
 The parameterized constructor is used to provide different values to distinct
objects.
Syntax
Class_name(Parameters){
//code
}
Example
class Student4{
int id;
String name;

Student4(int i,String n){


id = i;
name = n;
}

void display(){
System.out.println(id+" "+name);
}

public static void main(String args[]){


Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}
}

***********************
Methods
 A method is a block of code which only runs when it is called.
 You can pass data, known as parameters, into a method.
 Methods are used to perform certain actions, and they are also known as
functions.
Creating a Method
 A method must be declared within a class.
 It is defined with the name of the method, followed by parentheses ().
 Java provides some pre-defined methods, such as System.out.println().
Example
public class test {
static void myMethod() {
// code to be executed
}
}
Where,
 myMethod() is the name of the method
 static means that the method belongs to the Main class and not an object of the
Main class.
 void means that this method does not have a return value.
Calling the Method
 To call a method in Java, write the method's name followed by two parentheses
() and a semicolon;
 A method can also be called multiple times
Example
public class test {
static void myMethod() {
System.out.println("I just got executed!");
}

public static void main(String[] args) {


myMethod();
}
}
 In the above example, myMethod() is used to print a text “I just got executed”
when it is called

***********************
Static Keyword in JAVA

 Static keyword in Java is used for memory management.


 We can apply static keyword with variables, methods, blocks and nested classes.
The static can be:
 Variable (also known as a class variable)
 Method (also known as a class method)
 Block

Static Variable (or) Data


 If we declare any variable as static, it is known as a static variable.
 The static variable can be used to refer to the common property of all objects
 The static variable gets memory only once
 Static variables are shared among all instances of the class
 They can be accessed directly using the class name without needing to create an
instance of the class.
Example
class Student{
int rollno;//instance variable
String name;
static String college ="ITS";//static variable

//constructor
Student(int r, String n){
rollno = r;
name = n;
}
//method to display the values
void display (){
System.out.println(rollno+" "+name+" "+college);
}
}
//Test class to show the values of objects
public class TestStaticVariable1{
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
//we can change the college of all objects by the single line of code
Student.college="BBDIT";
s1.display();
s2.display();
}
}

Static Method
 If we apply a static keyword with any method, it is known as a static method.
 A static method belongs to the class rather than the object of a class.
 A static method can be invoked without the need for creating an instance of a
class.
 A static method can access static data members and can change their value of it.

Example
class Student{
int rollno;
String name;
static String college = "ITS";
//static method to change the value of static variable
static void change(){
college = "BBDIT";
}
//constructor to initialize the variable
Student(int r, String n){
rollno = r;
name = n;
}
//method to display values
void display(){
System.out.println(rollno+" "+name+" "+college);
}
}
//Test class to create and display the values of object
public class TestStaticMethod{
public static void main(String args[]){
Student.change();//calling change method
//creating objects
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
Student s3 = new Student(333,"Sonoo");
//calling display method
s1.display();
s2.display();
s3.display();
}
}
Static Block
 Java supports a special block, called a static block (also called static clause) that
can be used for static initialization of a class.
 Code inside the static block is executed only once.
 Static block executes automatically when the class is loaded in memory.
Example
public class StaticBlock
{
StaticBlock()
{
System.out.println("Inside the constructor of the class.");
}

// print method of the StaticBlock class


public static void print()
{
System.out.println("Inside the print method.");
}

static
{
System.out.println("Inside the static block.");
}
public static void main(String[] args)
{

// instantiating the class StaticBlock


StaticBlock sbObj = new StaticBlock();
sbObj.print(); // invoking the print() method

// invoking the constructor inside the main() method


new StaticBlock();

}
}
**********************
String
 Strings are the type of objects that can store the character of values and in Java.
 A string acts the same as an array of characters
Example
public class StringExample {
public static void main(String args[])
{
String str = new String("example");
System.out.println(str);
}
}
Creating a String
There are two ways to create a string in Java
1. String Literal
2. Using new Keyword
1. String Literal
 No new objects are created if it exists already in the string constant pool
Example:
String demoString = “GeeksforGeeks”;
2. Using new Keyword
 String s = new String(“Welcome”);
 In such a case, JVM will create a new string object in normal (non-pool) memory
String Buffer Class in Java
 StringBuffer is a class in Java that represents a mutable sequence of characters.
 It provides an alternative to the immutable String class, allowing you to modify
the contents of a string without creating a new object every time.
Constructors of StringBuffer class
1. StringBuffer(): creates an empty string buffer with an initial capacity of 16.
2. StringBuffer(String str): creates a string buffer with the specified string.
3. StringBuffer(int capacity): creates an empty string buffer with the specified
capacity as length.
Methods of the StringBuffer class:
1. The append() method is used to add characters, strings, or other objects to the
end of the buffer.
2. The insert() method is used to insert characters, strings, or other objects at a
specified position in the buffer.
3. The delete() method is used to remove characters from the buffer.
4. The reverse() method is used to reverse the order of the characters in the
buffer.
5. replace() method replaces the given string from the specified begin Index and
end Index-1.
Example
public class StringBufferExample {
public static void main(String[] args)
{
StringBuffer sb = new StringBuffer();
sb.append("Hello");
sb.append(" ");
sb.append("world");
String message = sb.toString();
sb.insert(1, "Java");
System.out.println(sb);
sb.replace(1, 3, "Java");
System.out.println(sb);
sb.delete(1, 3);
System.out.println(sb);
sb.reverse();
System.out.println(sb);
System.out.println(message);
}
}
*************************

You might also like