Unit 2 Java
Unit 2 Java
----------------------------------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------
importance is on doing things not on data importance is on data rather than procedure
Main focus is on the function and procedure Main focus is on the data that is being operated
that operate on data
Top Down approach in program design Bottom Up approach in program design
Large programs are divided into smaller Large programs are divided into classes and
programs known as functions objects
Most of the functions share global data Data is tied together with function in the data
structure.
Data moves openly in the system from one Data is hidden and cannot be accessed by external
function to another function functions
Adding of data and function is difficult Adding of data and function is easy
Concepts like inheritance, polymorphism, data Concepts like inheritance, polymorphism, data
encapsulation, abstraction, access specifier are encapsulation, abstraction, access specifier are
missing available and can be used easily
Examples: C, Fortran, Pascal, etc… Examples: C++, Java, C#, etc…
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
Object
Any entity that has state and behavior is known as an object. For example, a chair, pen, table, keyboard,
bike, etc. It can be physical or logical.
An Object can be defined as an instance of a class.
An object contains an address and takes up some space in memory. Objects can
communicate without knowing the details of each other's data or code. The
only necessary thing is the type of message accepted and the type of response
returned by the objects.
Example: A dog is an object because it has states like color, name, breed, etc. as
Inheritance
When one object acquires all the properties and behaviors of a parent object, it is known as inheritance.
It provides code reusability. It is used to achieve runtime polymorphism
Polymorphism
If one task is performed in different ways, it is known as polymorphism.
For example: to convince the customer differently, to draw something, for
example, shape, triangle, rectangle, etc.
In Java, we use method overloading and method overriding to achieve
polymorphism.
Another example can be to speak something; for example, a cat speaks meow, dog
barks woof, etc.
Abstraction
Hiding internal details and showing functionality is known as abstraction.
For example phone call, we don't know the internal processing.
Encapsulation
Binding (or wrapping) code and data together into a single unit are known as
encapsulation.
For example, a capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated
class because all the data members are private here.
Q.3 – Explain public, private, protected, default ?
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.
Private: The access level of a private modifier is only within the class. It cannot be accessed from outside
the class.
Protected: The access level of a protected modifier is within the package and outside the package
through child class. If you do not make the child class, it cannot be accessed from outside the package.
Default: The access level of a default modifier is only within the package. It cannot be accessed from
outside the package. If you do not specify any access level, it will be the default.
Q.4 – Explain This Keyword.?
class Test
{
public static void main(String args[])
{
Student s1=new Student(111,"Nirmal",5000f);
Student s2=new Student(112,"Nihar",6000f);
s1.display();
s2.display();
}
}
-----------------------------------------------------------------------------------------------
Output :
111 Nirmal 5000.0
112 Nihar 6000.0
Example:
//Java Program to demonstrate the use of static variable
class Student
{
int rollno; //instance variable
String name;
static String college ="Prayosha"; //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
//we can change the college of all objects by the single line of code
//Student.college="GP Himatnagar";
s1.display();
s2.display();
}
}
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.
class Bike
{
final int speedlimit=90; //final variable
void run()
{
speedlimit=400;
}
public static void main(String args[])
{
Bike obj=new Bike9();
obj.run();
}
Default Constructor: A constructor is called "Default Constructor" when it doesn't have any parameter.
class Bike
{
Bike() //creating a default constructor
{
System.out.println("Bike is created");
}
//main method
public static void main(String args[])
{
//calling a default constructor
Bike b=new Bike();
}
}
class Student
{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n)
{
id = i;
name = n;
}
//method to display the values
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
//creating objects and passing values
Student s1 = new Student(111,"Prayosha");
Student s2 = new Student(222,"Onewayakshar");
Copy Constructor: There are many ways to copy the values of one object into another in Java.
They are:
By constructor
By assigning the values of one object into another
By clone() method of Object class
//Java program to initialize the values from one object to another object.
class Student
{
int id;
String name;
//constructor to initialize integer and string
Student(int i,String n)
{
id = i;
name = n;
}
//constructor to initialize another object
Student(Student s)
{
id = s.id;
name =s.name;
}
void display()
{
System.out.println(id+" "+name);
}
Class has multiple methods having same name but different in parameters, it is known as Method
Overloading.
If we have to perform only one operation, having same name of the methods increases the readability of
the program.
Suppose you have to perform addition of the given numbers but there can be any number of arguments, if
you write the method such as a(int,int) for two parameters, and b(int,int,int) for three parameters then
it may be difficult for you as well as other programmers to understand the behavior of the method
because its name differs.
Example :
class Adder
{
static int add(int a,int b)
{
return a+b;
}
static int add(int a,int b,int c)
{
return a+b+c;
}
}
class TestOverloading
{
public static void main(String[] args)
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}
}
Constructor overloading in Java is a technique of having more than one constructor with different
parameter lists.
They are arranged in a way that each constructor performs a different task.
They are differentiated by the compiler by the number of parameters in the list and their types.
The wrapper class in Java provides the mechanism to convert primitive into object and object into
primitive.
Java is an object-oriented programming language, so we need to deal with objects many times like in
Collections, Serialization, Synchronization, etc. Let us see the different scenarios, where we need to use
the wrapper classes.
Change the value in Method: Java supports only call by value. So, if we pass a primitive value, it will not
change the original value. But, if we convert the primitive value in an object, it will change the original
value.
Serialization: We need to convert the objects into streams to perform the serialization. If we have a
primitive value, we can convert it in objects through the wrapper classes.
Synchronization: Java synchronization works with objects in Multithreading.
java.util package: The java.util package provides the utility classes to deal with objects.
The eight classes of the java.lang package are known as wrapper classes in Java. The list of eight
wrapper classes are given below:
import java.util.ArrayList;
CharAt() :
*********************************************************
public class Main
{
public static void main(String[] args)
{
String myStr = "Hello";
char result = myStr.charAt(0);
System.out.println(result);
}
}
Output : H
contains():
****************************************************
public class Main {
public static void main(String[] args)
{
String myStr = "Hello";
System.out.println(myStr.contains("Hel"));
System.out.println(myStr.contains("e"));
System.out.println(myStr.contains("Hi"));
}
}
Output:
true
true
false
format() :
****************************************************
class Main
{
public static void main(String[] args)
{
String str = "Java";
// format string
String formatStr = String.format("Language: %s", str);
System.out.println(formatStr);
length() :
**************************************************************
public class Main
{
public static void main(String[] args)
{
String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println(txt.length());
}
}
Output : 26
The Scanner class is used to get user input, and it is found in the java.util package.
To use the Scanner class, create an object of the class and use any of the available methods found in
the Scanner class documentation. In our example, we will use the nextLine() method, which is used to
read Strings:
Example:
import java.util.Scanner; // import the Scanner class
class Main
{
public static void main(String[] args)
{
Scanner myObj = new Scanner(System.in);
String userName;
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.
class CommandLineExample
{
public static void main(String args[])
{
System.out.println("Your first argument is: "+args[0]);
}
}
***************************
compile by > javac CommandLineExample.java
Output:
Nirmal
Patel
1
3
abc