0% found this document useful (0 votes)
4 views163 pages

Java Introduction Commands Basics History

This presentation covers the very basic fundamentals of Java programming. It covers history, conmands, and other stuff.

Uploaded by

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

Java Introduction Commands Basics History

This presentation covers the very basic fundamentals of Java programming. It covers history, conmands, and other stuff.

Uploaded by

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

Introduction to Java

Introduction to Java
• Java is a purely an object – oriented language.

• In 1991, James Gosling and Patrick Naughton developed


named “OAK” at Sun Microsystems.

• Java is simple and platform-independent.

• In 1995, this language was renamed as “Java”.

• Java history is interesting to know. The history of java


starts from Green
Introduction to Java
• Java team members (also known as Green Team), initiated
a revolutionary task to develop a language for digital
devices such as set-top boxes, televisions etc.

• For the green team members, it was an advance concept


at that time. But, it was suited for internet programming.
Later, Java technology as incorporated by Netscape.

• Currently, Java is used in internet programming, mobile


devices, games and e-business solutions etc.
Introduction to Java - History
• There are given the major points that describes the history
of java.

• James Gosling, Mike Sheridan, and Patrick Naughton


initiated the Java language project in June 1991. The small
team of sun engineers called Green Team.

• Originally designed for small, embedded systems in


electronic appliances like set-top boxes.

• Firstly, it was called "Greentalk" by James Gosling and file


extension was .gt.
Introduction to Java – History – Why Oak name?

• After that, it was called Oak and was developed as a


part of the Green project.

• Why Oak? Oak is a symbol of strength and choosen as a


national tree of many countries like U.S.A.,France,
Germany, Romania etc.

• In 1995, Oak was renamed as

"Java" because it was already a

trademark by Oak Technologies.


Introduction to Java – History – Why Java name?

• Why they choosed java name for java language? The team
gathered to choose a new name. The suggested words were
"dynamic", "revolutionary", "Silk", "jolt", "DNA" etc.

• They wanted something that reflected the essence of the


technology: revolutionary, dynamic, lively, cool, unique, and
easy to spell and fun to say.

• According to James Gosling "Java was one of the top choices


along with Silk". Since java was so unique, most of the team
members preferred java.
Introduction to Java – History
• Java is an island of Indonesia where first coffee was
produced called java coffee.

• Notice that Java is just a name not an acronym.

• Originally developed by James Gosling at Sun


Microsystems (which is now a subsidiary of Oracle
Corporation) and released in 1995.

• In 1995, Time magazine called Java one of the Ten Best


Products of 1995. JDK 1.0 released in(January 23, 1996).
Introduction to Java – Versions
• Sun Microsystems has been releasing new versions of
JDK. The originally version of Java released in 1995, was
called JDK1.0 version.

• The versions are JDK1.1, JDK1.2, JDK1.3, JDK1.4 and


JDK1.5, JDK1.6, JDK1.7 and JDK1.8………JDK24.

• Homework - History of different versions and its


features
Features of Java
Features of Java
• There is given many features of java. They are also
known as java buzzwords. The Java Features given
below are simple and easy to understand.

1. Simple 7. Portable
2. Object-Oriented 8. Dynamic
3. Platform independent 9. Interpreted
4. Secured 10.High Performance
5. Robust 11.Multithreaded
6. Architecture neutral 12.Distributed
EXECUTION OF JAVA
PROGRAM
Introduction to Java - JVM
• CPUs are capable of executing only the machine instructions.

• Different types of CPUs have different sets of machine


instructions.

• To enable Java programs to be executed on multiple CPUs


without modifications, java programs are compiled into machine
instructions that can be understood and executed by an
idealized CPU. Such a CPU is called Java Virtual Machine (JVM).

• Actually, the JVM is simulated by a program, which is executed


on the actual CPU.
Introduction to Java – Bytecode, JIT

• A Java program is first compiled into the machine code


that is understood by JVM. Such a code is called Byte
Code.

• Although the details of the JVM will differ from platform


to platform, they all interpret the Java Byte Code into
executable native machine code.

• The Just In Time (JIT) compiler compiles the byte code


into executable machine code in real time, on a piece-by-
piece demand basis.
Introduction to Java – JDK
• The JIT cannot compile the entire byte code of a Java
program into executable machine code all at once,
because Java Runtime Environment carries out various
run time checks that can be performed only at run time.

• The collection of the three entities name the Java


language, the Java language packages and the set of
Java development tools is called the Java Development
Kit (JDK).
Introduction to Java - JDK Tools
• The important development tools included in JDK are
Java compiler, Java interpreter, Java disassembler, Java
debugger, tool for C header files, tool for creating HTML
documents and tool for viewing Java applets.

• The purpose of each one of these development tools is


briefly described in the following table.
Introduction to Java – JDK Tools
Tool in JDK Purpose
appletviewer This tool helps us to execute a special type of Java program
known as applets.
java This tool is the Java interpreter. It interprets the bytecode into
machine code and then executes it
javac This tool is Java compiler. It compiles the Java source code into
the bytecode, which can be understood by JVM.

javadoc This tool is used to create documentation in HTML.


javah This tool produces C header files for use with a special type of
Java methods, known as native methods.
javap This tool is the Java disassembler. It helps use to convert
bytecode files into Java program descriptions.
jdb This tool is the Java debugger. It enables us to detect the erros
in the Java programs.
Introduction to Java – Types of applications

• Three types of programs, can be developed using Java, Namely


applets, servlets and stand-alone applications.

• Applet is a Java program that is developed exclusively for the


Internet.

• Applets are embedded in HTML documents that take care of


the design of web pages.

• Servlets are used to create dynamic web content.

• Stand-alone applications can be executed without the internet


connectivity. These applications are executed in local machine.
Features of Java
Features of Java
• There is given many features of java. They are also
known as java buzzwords. The Java Features given
below are simple and easy to understand.

1. Simple 7. Portable
2. Object-Oriented 8. Dynamic
3. Platform independent 9. Interpreted
4. Secured 10.High Performance
5. Robust 11.Multithreaded
6. Architecture neutral 12.Distributed
Features of Java - Simple
• According to Sun, Java language is simple
because:
 syntax is based on C++ (so easier for programmers to

learn it after C++).


 removed many confusing and/or rarely-used features

e.g., explicit pointers, operator overloading etc.


 No need to remove unreferenced objects because

there is Automatic Garbage Collection in java.


Features of Java - Object-oriented
• Object-oriented means we organize our software as a combination of

different types of objects that incorporates both data and behavior.

• Object-oriented programming(OOPs) is a methodology that simplify

software development and maintenance by providing some rules.

• Basic concepts of OOPs are:


 Object
 Class
 Inheritance
 Polymorphism
 Abstraction
 Encapsulation
Features of Java - Platform Independent
• A platform is the hardware or software environment in
which a program runs.
• There are two types of platforms, software-based and
hardware-based.
• Java provides software-based platform.
• The Java platform differs from most other platforms in
the sense that it is a software-based platform that runs
on the top of other hardware-based platforms.
• It has two components:
1. Runtime Environment
2. API(Application Programming Interface)
Features of Java - Platform Independent

• Java code can be run on multiple platforms e.g.


Windows, Linux, Sun Solaris, Mac/OS etc.

• Java code is compiled by the compiler and converted


into bytecode.

• This bytecode is a platform-independent code because


it can be run on multiple platforms i.e. Write Once and
Run Anywhere(WORA).
Features of Java - Platform Independent
Features of Java - Secured
• Java is secured because:
 No explicit pointer

 Java Programs run inside virtual machine sandbox


Features of Java - Secured
• Classloader: adds security by separating the package for
the classes of the local file system from those that are
imported from network sources.

• Bytecode Verifier: checks the code fragments for illegal


code that can violate access right to objects.

• Security Manager: determines what resources a class can


access such as reading and writing to the local disk.
• These security are provided by java language. Some
security can also be provided by application developer
through SSL, JAAS, Cryptography etc.
Features of Java - Robust
• Robust simply means strong.

• Java uses strong memory management.

• There are lack of pointers that avoids security problem.

• There is automatic garbage collection in java.

• There is exception handling and type checking


mechanism in java.

• All these points makes java robust.


Features of Java - Architecture-neutral

• There is no implementation dependent features e.g. size


of primitive types is fixed.

• In C programming, int data type occupies 2 bytes of


memory for 32-bit architecture and 4 bytes of memory
for 64-bit architecture.

• But in java, it occupies 4 bytes of memory for both 32


and 64 bit architectures.
Features of Java - Portable
• We may carry the java bytecode to any platform.
Features of Java – High-performance

• Java is faster than traditional interpretation since byte


code is "close" to native code still somewhat slower
than a compiled language (e.g., C++)
Features of Java – Distributed
• We can create distributed applications in java.

• RMI and EJB are used for creating distributed


applications.

• We may access files by calling the methods from any


machine on the internet.
Features of Java – Multi-threaded
• 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.

• The main advantage of multi-threading is that it doesn't


occupy memory for each thread. It shares a common
memory area.

• Threads are important for multimedia, Web applications


etc.
DATA TYPES IN JAVA
Types of Array in javaSyntax
Automatic casting/ Widening
Casting
public class Main {
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/Explicit Casting
public class Main1 {
public static void main(String[] args) {
double myDouble = 9.78d;
int myInt = (int) myDouble; // Manual casting: double to int

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


System.out.println(myInt); // Outputs 9
}
}
Java Comments
Unary operator
public class Unary1
{
public static void main(String args[]) {
int x = 10;

System.out.println(x++);
System.out.println(++x);
System.out.println(x--);
System.out.println(--x);
}
}
JAVA USER INPUT
BufferedReader and
InputStreamReader
import java.io.*;

public class ReadInput {


public static void main(String[] args) throws IOException {
// Step 1: Create InputStreamReader to read bytes and convert to characters
InputStreamReader isr = new InputStreamReader(System.in);

// Step 2: Wrap it in BufferedReader to read lines


BufferedReader br = new BufferedReader(isr);

// Step 3: Read a full line of input


System.out.print("Enter your name: ");
String name = br.readLine();

System.out.println("Hello, " + name);


BufferedReader and
InputStreamReader
import java.io.*;

public class ReadAge {


public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

System.out.print("Enter your age: ");


String ageStr = br.readLine(); // Read as String
int age = Integer.parseInt(ageStr); // Convert to int

System.out.println("You are " + age + " years old.");


}
1.compile by > javac CommandLineExam
ple.java
2.run by > java CommandLineExample so
noo Output: Your first argument is: sonoo
1.compile by > javac A.java
2.run by > java A sonoo jaiswal 1 3 a
bc
Output: sonoo jaiswal 1 3 abc
TEST QUESTIONS
• Q: Write a Java program to display the Fibonacci series.
• Q: Write a Java program to reverse a number.
• Q. Java Program: Swap Two Numbers Using Only Two Variables
ACCESS MODIFIERS IN
JAVA
Access Modifiers in Java

• Access modifiers help to restrict the scope of a class,


constructor, variable, method, or data member.

• There are four types of access modifiers available in


Java:
1.Default – No keyword required
2.Private
3.Protected
4.Public
2. Private Access Modifier

• The private access modifier is specified using the keyword private.


• The methods or data members declared as private are accessible
only within the class in which they are declared.
• Any other class of the same package will not be able to access these
members.
• Top-level classes or interfaces can not be declared as private because
• private means “only visible within the enclosing class”.
• protected means “only visible within the enclosing class and any subclasses”
• Hence these modifiers in terms of application to classes, apply only to
nested classes and not on top-level classes
• In this example, we will create two classes A and B within the same
package p1. We will declare a method in class A as private and try to
access this method from class B and see the result.
class A{
private int data=40; class A{
private void msg(){System.out.println("Hello java");} private int data=40;
} private void msg()
{
public class Simple{
public static void main(String args[]){
System.out.println("Hello java");
A obj=new A(); }
System.out.println(obj.data);//Compile Time Error public static void main(String args[])
obj.msg();//Compile Time Error {
}
A obj=new A();
}

System.out.println(obj.data);//Compi
le Time Error
obj.msg();//Compile Time Error
}
// Private Modifier
package p1; class B {
class A { public static void main(String args[])
private void display()
{
{
System.out.println("GeeksforGeeks");
A obj = new A();
} // Trying to access private method
} // of another class
obj.display();
}
}

O/P - error: display() has private access in A


obj.display();
Default Access Modifier

• The data members, classes, or methods that are not


declared using any access modifiers .
• default access modifiers are accessible only within the
same package.
• In this example, we will create two packages and the
classes in the packages will be having the default
access modifiers and we will try to access a class from
one package from a class of the second package.
// Java program to illustrate error while
// Java program to illustrate default // using class from different package with
modifier
// default modifier
package p1; package p2;
import p1.*;
// Class Geek is having Default access
modifier // This class is having default access modifier
class GeekNew
class Geek
{
{ public static void main(String args[])
void display() {
{ // Accessing class Geek from package p1
Geek obj = new Geek();
System.out.println("Hello World!");
} obj.display();
} }
O/p: Compile time error }
3. Protected Access Modifier

• The protected access modifier is specified using the


keyword protected.
• The methods or data members declared as protected
are accessible within the same package or
subclasses in different packages.
• In this example, we will create two packages p1 and p2.
Class A in p1 is made public, to access it in p2. The
method display in class A is protected and class B is
inherited from class A and this protected method is then
accessed by creating an object of class B.
// Java Program to Illustrate // Java program to illustrate
// protected modifier
// Protected Modifier
package p2;
package p1;
// importing all classes in package p1
// Class A import p1.*;

public class A { // Class B is subclass of A


protected void display() class B extends A {
{ public static void main(String args[])
{
B obj = new B();
System.out.println("GeeksforGee
Output:
obj.display();
ks");
GeeksforGeeks }
}
Public Access modifier

• The public access modifier is specified using the


keyword public.
• The public access modifier has the widest
scope among all other access modifiers.
• Classes, methods, or data members that are declared
as public are accessible from everywhere in the
program. There is no restriction on the scope of public
data members.
CLASS AND OBJECTS
SAMPLE PROGRAM
• What is a class in Java
• A class is a group of objects which have common properties. It is a
template or blueprint from which objects are created. It is a logical entity.
It can't be physical.

• A class in Java can contain:


• Fields
• Methods
• Constructors
• Blocks
• Nested class and interface
Syntax to declare a class:

• class <class_name>
{
field;
method;
}
new keyword in Java

• The new keyword is used to allocate memory at


runtime. All objects get memory in Heap memory area.
Main within Class
Object and Class Example: main within the class
1.//Defining a Student class.
2.class Student{
3. //defining fields
4. int id;//field or data member or instance variable
5. String name;
6. //creating main method inside the Student class
7. public static void main(String args[]){
8. //Creating an object or instance
9. Student s1=new Student();//creating an object of Student
10. //Printing values of the object
11. System.out.println(s1.id);//
accessing member through reference variable
12. System.out.println(s1.name);
13. }
main outside the class
Object and Class Example: main outside the class

1.//Java Program to demonstrate having the main method in


2.//another class
3.//Creating Student class.
4.class Student{
5. int id;
6. String name;
7.}
8.//Creating another class TestStudent1 which contains the main method
9.class TestStudent1{
10. public static void main(String args[]){
11. Student s1=new Student();
12. System.out.println(s1.id);
13. System.out.println(s1.name);
14. }
3 Ways to initialize object

• There are 3 ways to initialize object in Java.

1.By reference variable


2.By method
3.By constructor
Initialization through reference

1.class Student{
2. int id;
3. String name;
4.}
5.class TestStudent2{
6. public static void main(String args[]){
7. Student s1=new Student();
8. s1.id=101;
9. s1.name="Sonoo";
10. System.out.println(s1.id+" "+s1.name);//
printing members with a white space
11. }
Initialization through method
class Student class TestStudent4{
{ public static void main(String args[])
int rollno; {
Student s1=new Student();
String name; Student s2=new Student();
void insertRecord(int r, String n) s1.insertRecord(111,"Karan");
{ s2.insertRecord(222,"Aryan");
rollno=r; s1.displayInformation();
name=n; s2.displayInformation();
} }
void displayInformation()
{
System.out.println(rollno+" "+name);
}
}
Initialization through a
constructor
class Rectangle{ class TestRectangle1{
int length; public static void main
int width; (String args[])
void insert(int l, int w) {
{ Rectangle r1=new Rectangle();
length=l; Rectangle r2=new Rectangle();
width=w; r1.insert(11,5);
} r2.insert(3,15);
void calculateArea() r1.calculateArea();
{ r2.calculateArea();
System.out.println(length*width);} }
} }
Constructors

• In Java, a constructor is a block of codes similar to the method.


It is called when an instance of the class is created. At the time
of calling constructor, memory for the object is allocated in the
memory.
• It is a special type of method which is used to initialize the
object.
• Every time an object is created using the new() keyword, at least
one constructor is called.
• It calls a default constructor if there is no constructor available
in the class. In such case, Java compiler provides a default
constructor by default.
Rules for creating Java constructor
• Constructor name must be the same as its class name
• A Constructor must have no explicit return type
• A Java constructor cannot be abstract, static, final, and synchronized
Types of Constructor in JAva
• no-arg constructor
• parameterized constructor.
• Copy Constructor
Java Default Constructor

• A constructor is called "Default class Bike1{


Constructor" when it doesn't have any
parameter. //creating a default constructor
Syntax of default constructor: Bike1()
<class_name>() { System.out.println("Bike is created");
{
}
//main method
}
public static void main(String args[])
It will be invoked at the time of object
creation. {
//calling a default constructor
The default constructor is used to provide Bike1 b=new Bike1();
the default values to the object like 0, null, }
etc., depending on the type. }
Java Parameterized Constructor
• A constructor which has a specific number //method to display the values
of parameters is called a parameterized
void display()
constructor.
{
• WHY: The parameterized constructor is
used to provide different values to distinct System.out.println(id+" "+name);
objects. However, you can provide the }
same values also. public static void main(String args[])
class Student4{ {
int id; //creating objects and passing values
String name; Student4 s1 = new Student4(111,"Karan");
//creating a parameterized constructor Student4 s2 = new Student4(222,"Aryan");
Student4(int i,String n) //calling method to display the values of object
s1.display();
{ id = i;
s2.display();
name = n;
}
} }
Copy Constructor

• In Java, a copy constructor is public class Fruits


a special type of constructor {
that creates an object using private double price;
another object of the same
Java class. It returns a private String name;
duplicate copy of an existing //copy constructor
object of the class. public Fruits(Fruits fruits)
• Creating a Copy Constructor {
• Create a constructor that //getters
accepts an object of the same }
class as a parameter. }
public class Fruit
double showPrice()
{ {
private double fprice; return fprice;
}
private String fname; //creating a method that returns the name of the fruit
// String showName()
constructor to initialize roll number and name of the {
student return fname;
}
Fruit(double fPrice, String fName)
//
{ class to create student object and print roll number and nam
e of the student
fprice = fPrice; public static void main(String args[])
fname = fName; {
Fruit f1 = new Fruit(399, "Ruby Roman Grapes");
}
System.out.println("Name of the first fruit: "+ f1.showName()
//creating a copy constructor );
System.out.println("Price of the first fruit: "+ f1.showPrice());
Fruit(Fruit fruit)
{ //passing the parameters to the copy constructor
Fruit f2 = new Fruit(f1);
System.out.println("\
System.out.println("Name of the second fruit: "+ f2.showNa
nAfter invoking the Copy Constructor:\n"); me());
fprice = fruit.fprice; System.out.println("Price of the second fruit: "+ f2.showPrice
());
fname = fruit.fname; }
o/p
Constructor Overloading in Java
• In Java, a constructor is just like a method but
without return type. It can also be overloaded
like Java methods.
• 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.
Example of Constructor
Overloading
//Java program to overload constructors
class Student5{ void display(){System.out.println(id+"
int id; "+name+" "+age);}
String name; public static void main(String args[]){
int age;
//creating two arg constructor Student5 s1 = new Student5(111,"Karan");
Student5(int i,String n){ Student5 s2 = new
id = i;
Student5(222,"Aryan",25);
name = n;
} s1.display();
//creating three arg constructor
s2.display();
Student5(int i,String n,int a){
id = i; }
name = n;
}
age=a;
}
this keyword in Java
This keyword
1) this: to refer current class
instance variable
• The this keyword can be used to
refer current class instance void display(){System.out.println(rollno+" "+
variable. If there is ambiguity name+" "+fee);}
between the instance variables and
parameters, this keyword resolves }
the problem of ambiguity.
class TestThis1{
class Student{
public static void main(String args[]){
int rollno; Student s1=new Student(111,"ankit",5000f);
String name; Student s2=new Student(112,"sumit",6000f)
float fee; s1.display();
Student(int rollno,String name,float fee){
s2.display();
rollno=rollno;
name=name; }}
fee=fee;
Understanding the problem without this keyword

class Student{ void display()


{System.out.println(rollno+" "+name+" "+fee)
int rollno; ;}
String name; }
float fee;
class TestThis2{
Student(int rollno,String name,flo
public static void main(String args[]){
at fee){
Student s1=new Student(111,"ankit",5000f);
this.rollno=rollno; Student s2=new Student(112,"sumit",6000f);
this.name=name; s1.display();
this.fee=fee; s2.display();
} }}
Program where this keyword is
not required
class Student{ class TestThis3
int rollno;
{
String name;
float fee;
public static void main(String ar
)
Student(int r,String n,float f){
rollno=r; {
name=n; Student s1=new Student(111,"an
fee=f; ,5000f);
} Student s2=new Student(112,"su
void display() ",6000f);
{System.out.println(rollno+" "+name s1.display();
+" "+fee);
} s2.display();
}
WEEK2 TUTORIAL
1. Calculate and print the factorial of a given non-negative integer using a for
loop.
2.Calculate and print the simple interest for a given principal, rate, and number
of years using a for loop.
3. Print the multiplication table of a given number using While loop
4. Calculate the average of a series of numbers entered by the user using a
while loop.
5.Find the sum of even numbers from 1 to a given number using a dowhile
loop.
6. Continuously prompt the user to enter a positive number until they provide
a valid input.
ACCESS MODIFIERS IN
JAVA
Access Modifiers in Java

• Access modifiers help to restrict the scope of a class,


constructor, variable, method, or data member.

• There are four types of access modifiers available in


Java:
1.Default – No keyword required
2.Private
3.Protected
4.Public
class B{
private int data=40;
private void msg(){System.out.println("Hello java");}
}
class First
{
public static void main(String args[]){
B obj=new B();//Compile Time Error
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}
class B{
private int data=40;
private void msg(){System.out.println("Hello java");}
//}
//class First
//{
public static void main(String args[]){
B obj=new B();//Compile Time Error
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}
STATIC Keyword in java
Java static keyword
• The static keyword in Java is used for memory management mainly.
• We can apply static keyword with variables, methods, blocks and nested
classes. The static keyword belongs to the class than an instance of the
class.
• The static can be:

• Variable (also known as a class variable)


• Method (also known as a class method)
• Block
• Nested class
Java static variable

• The static variable can be used to refer to the common


property of all objects (which is not unique for each
object), for example, the company name of employees,
college name of students, etc.
• The static variable gets memory only once in the class
area at the time of class loading.
Java static variable //method to display the values
void display ()
class Student{ {
int rollno;//instance variable System.out.println(rollno+" "+name+" "+colle
String name; }
static String college =“ITS";//static //Test class to show the values of objects
variable public class TestStaticVariable1{
public static void main(String args[]){
//constructor
Student s1 = new Student(11,"MMM");
Student(int r, String n){ Student s2 = new Student(22,"NNN");
rollno = r;
name = n; s1.display();
} s2.display();
}
Understanding the problem without static variable

class Student{
int rollno;
String name;
String college="ITS";
}
With and without static
class Counter class Counter2
{ {
int count=0;//will get memory each time when the static int count=0;//will get memory only once and retain
instance is created its value
Counter() Counter2(){
{ count++;//incrementing the value of static variable
count++;//incrementing value System.out.println(count);
System.out.println(count); }
} public static void main(String args[]){
public static void main(String args[]){ //creating objects
//Creating objects Counter2 c1=new Counter2();
Counter c1=new Counter(); Counter2 c2=new Counter2();
Counter c2=new Counter(); Counter2 c3=new Counter2();
Counter c3=new Counter(); }
} }
2) Java static method

• If you apply static keyword with any method, it is known


as 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 member and can
change the value of it.
//method to display values
// void display()
Java Program to demonstrate the use of a static method. {System.out.println(rollno+" "+name+" "+colle
ge);}
class Student{ }
int rollno; //
Test class to create and display the values of obj
String name; ect
static String college = "ITS"; public class TestStaticMethod{
// public static void main(String args[]){
static method to change the value of static variable Student.change();//calling change method
static void change(){ //creating objects
Student s1 = new Student(111,"Karan");
college = "BBDIT";
Student s2 = new Student(222,"Aryan");
}
Student s3 = new Student(333,"Sonoo");
//constructor to initialize the variable //calling display method
Student(int r, String n){ s1.display();
rollno = r; s2.display();
name = n; s3.display();
}
}
}
//
Java Program to get the cube of a gi
ven number using the static method

class Calculate{
static int cube(int x){
return x*x*x;
}

public static void main(String args[]){


int result=Calculate.cube(5);
System.out.println(result);
}
}
Restrictions for the static method
There are two main restrictions for the static method. They are:

The static method can not use non static data member or call non-static method
directly.
this and super cannot be used in static context.

class A{
int a=40;//non static

public static void main(String args[]){


System.out.println(a);
}
}
Inheritance in Java
• Inheritance in Java is a mechanism in which one
object acquires all the properties and behaviors of a
parent object.
• 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.

• Inheritance represents the IS-A relationship which is


also known as a parent-child relationship
Why use inheritance in java

• For Method Overriding (so runtime polymorphism can


be achieved).
• For Code Reusability.
Terms used in Inheritance

• Class: A class is a group of objects which have common properties.


It is a template or blueprint from which objects are created.
• Sub Class/Child Class: Subclass is a class which inherits the
other class. It is also called a derived class, extended class, or child
class.
• Super Class/Parent Class: Superclass is the class from where a
subclass inherits the features. It is also called a base class or a
parent class.
• Reusability: As the name specifies, reusability is a mechanism
which facilitates you to reuse the fields and methods of the existing
class when you create a new class. You can use the same fields and
methods already defined in the previous class.
The syntax of Java Inheritance

class Subclass-name extends Superclass-name


{
//methods and fields
}
Types of inheritance in java
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int benefits=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+
p.salary);
System.out.println("Bonus of Programmer is:
"+p. benefits );
}
}
Single Inheritance Example
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
Multilevel Inheritance Example
When there is a chain of class BabyDog extends Dog{
inheritance, it is known void weep()
as multilevel inheritance. {System.out.println("weeping...");}
}
class Animal{ class TestInheritance2{
void eat() public static void main(String args[
{System.out.println("eating...");} ]){
} BabyDog d=new BabyDog();
class Dog extends Animal{ d.weep();
void bark() d.bark();
{System.out.println("barking...");} d.eat();
} }}
Hierarchical Inheritance Example

• When two or more classes class Cat extends Animal{


inherits a single class, it is known void meow()
as hierarchical inheritance. {System.out.println("meowing...");}
class Animal{ }
void eat() class TestInheritance3{
{System.out.println("eating...");} public static void main(String args[
} ]){
class Dog extends Animal{ Cat c=new Cat();
c.meow();
void bark()
{System.out.println("barking...");} c.eat();
//c.bark();//C.T.Error
} }}
Muliple Inheritance not supported in
Java
class A
{
void msg(){System.out.println("Hello");}
}
class B
{
void msg(){System.out.println("Welcome");}
}
class C extends A,B
{//suppose if it were

public static void main(String args[])


{
C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
}
Super Keyword in Java
Super Keyword in Java

• The super keyword in Java is a reference variable which


is used to refer immediate parent class object.
• Whenever you create the instance of subclass, an
instance of parent class is created implicitly which is
referred by super reference variable.
1) super is used to refer immediate parent class instance
variable.

class Animal{ class TestSuper1{


String color="white"; public static void main(Str
} ing args[]){
class Dog extends Animal{ Dog d=new Dog();
String color="black"; d.printColor();
void printColor(){ }}
System.out.println(color);//
prints color of Dog class
System.out.println(super.color);/
/prints color of Animal class
}
}
2) super can be used to invoke parent class method

class Animal{
void eat()
class TestSuper2{
{System.out.println("eating...");} public static void main(St
} ring args[]){
class Dog extends Animal{
Dog d=new Dog();
void eat()
{System.out.println("eating bread...");} d.work();
}}
void bark()
{System.out.println("barking...");}
void work(){
super.eat();
bark();
}
3) super is used to invoke parent class constructor.

class Animal{ class TestSuper3


Animal() {
{ public static void main(Strin
System.out.println("animal is created g args[])
");
{
}
Dog d=new Dog();
}
class Dog extends Animal{ }
Dog(){ }
super();
System.out.println("dog is created");
Another example of super keyword where super() is provided by the compiler implicitly.

class Animal
{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog()
{
System.out.println("dog is created");
}
}
class TestSuper4{
public static void main(String args[]){
Dog d=new Dog();
}
super example: real
class Person{
int id;
use
String name;
Person(int id,String name){ class TestSuper5
this.id=id; {
this.name=name;
public static void main(Strin
}
}
g[] args)
class Emp extends Person{ {
float salary; Emp e1=new Emp(1,"ankit",4
Emp(int id,String name,float salary){ 5000f);
super(id,name);//
reusing parent constructor e1.display();
this.salary=salary; }
} }
void display()
{System.out.println(id+" "+name+" "+s
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.
1) Java final variable

• If you make any variable as final, you cannot change


the value of final variable(It will be constant).
• Example of final variable
• There is a final variable speedlimit, we are going to
change the value of this variable, but It can't be
changed because final variable once assigned a value
can never be changed.
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class
2) Java final method
If you make any method as final, you cannot override it.

Example of final method


class Bike{
final void run(){System.out.println("running");}
}

class Honda extends Bike{


void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda honda= new Honda();
honda.run();
}
}
Test it Now
3) Java final class
If you make any class as final, you cannot extend it.
Example of final class
final class Bike{}

class Honda1 extends Bike{


void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda1 honda= new Honda1();
honda.run();
}
}

You might also like