0% found this document useful (0 votes)
63 views147 pages

Java Programming-10

This document provides an overview of Java programming concepts including: 1. Java is case sensitive like C/C++ and nearly 100% object oriented. All functions must be part of a class. 2. The document includes a sample "Hello World" program and discusses Java keywords, data types, variables, constants, type conversion, classes and objects. 3. Additional concepts covered are static members, wrapper classes, command line arguments, packages, access modifiers, constructors, and constructor chaining.

Uploaded by

Aryan Arora
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
63 views147 pages

Java Programming-10

This document provides an overview of Java programming concepts including: 1. Java is case sensitive like C/C++ and nearly 100% object oriented. All functions must be part of a class. 2. The document includes a sample "Hello World" program and discusses Java keywords, data types, variables, constants, type conversion, classes and objects. 3. Additional concepts covered are static members, wrapper classes, command line arguments, packages, access modifiers, constructors, and constructor chaining.

Uploaded by

Aryan Arora
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 147

JAVA Programming

Advanced Programming Lab - 2


Note:
1. Java is case sensitive like C and C++
2. Java is nearly 100% object oriented
3. In Java it is not possible to make a function which is not the member of a
class.
Sample Program:

public class HelloWorld{


public static void main(String[] args){
System.out.println("Hello World");
}
}
Keywords in Java
Data Type
Data types are different sizes and values that can be stored in the variable that is
made as per convenience and circumstances to cover up all test cases.
● Language can be:
○ Statically typed language or Strongly typed eg. C, C++ and Java
○ Dynamically typed language eg. Ruby and Python

● Date type can be divided into:


○ Primitive data type
○ User defined data type
Variables and Constants
● Variables are declared just like C and C++
● Java do not support constants directly but they can be declared using the
following syntax:

static final int MAX= 100;

● final keyword will have dedicated discussion later


Type Conversion in Java
● Widening conversions no issues

int a = 3;
float b = a; //no issues

● Narrowing conversions will lead to an error unless explicitly done

float a = 3;
int b = a; //error
int b = (int)a; //no issues
Class and Object
● Class a template used to create objects and to define object data types and
methods.
● Classes are categories, and objects are items within each category.
● It is the object which gets memory.
Objects in C++ vs Java
● In C++
○ Person P;
○ Person *P = new person();
● In Java
○ Person P = new person();
Example.java
class Person{
private String name;
public class Example{
private int age;
public static void main(String[] args){
public void setName(String n){
Person p= new Person();
name = n;
p.setName("Rahul");
}
p.setAge(12);
public void setAge(int a){
p.getName();
age = a;
p.getAge();
}
}
public void getName(){
}
System.out.println(name);
}
public void getAge(){
System.out.println(age);
}
}
static
● We can have static member function, variable, inner class.
● We can’t have static variables in methods.
● static members are declared using static keyword.
● They are initialized to their default values.
● We have single copy of the static variables are they are not included in the
memory allocated for objects.
StaticExample.java
public class StaticExample{
static class Test2{
int x;
public static void f5(){
static int y;
System.out.println("Static member function of
public void f1(){
static inner
System.out.println("Instance member function: f1");
class");
}
}
public static void f2(){
}
System.out.println("Static member function: f2"); }
}
public class Test1{ public static void main(String [] args){
public void f3(){ StaticExample se = new StaticExample();
System.out.println("Member function of inner se.f1();
class"); StaticExample.f2();
} StaticExample.Test set = new StaticExample.Test();
} set.f4();
static class Test{ StaticExample.Test1 et = se.new Test1();
public void f4(){ et.f3();
System.out.println("Member function of static StaticExample.Test2.f5();
inner class"); }
}
} }
Java is nearly OOP
● Java is an object-oriented language and as said everything in Java is an
object.

● They are sort of left out in the world of Objects, that is they cannot participate
in the object activities
Wrapper Classes
● As a solution to this problem, Java allows you to include the primitive in the
family of objects by using what are called wrapper class.

● There is a wrapper class for every primitive type in Java


Useful methods of wrapper class
● valueOf()
○ Static method.
○ Return Object reference of relative wrapper class
● parseXxx()
○ Static method
○ Xxx can be replaced by any primitive type
○ It returns xxx type value
● xxxValue()
○ Instance method of wrapper class
○ Xxx can be replaced by any primitive type
○ Returns corresponding primitive type
WrapperExample.java

public class WrapperExample{


public static void main(String[ ] args) {
Integer i1= Integer.valueOf("123");
Double d1= Double.valueOf("3.14");
int a = Integer.parseInt("123");
double b= Double.parseDouble("13.45");
int c=i1.intValue();
}
}
Command Line Arguments
A Java application can accept any number of arguments from command line
CommandLineExample.java

public class CommandLineExample{


public static void main(String[] args) {
for(int i=0; i<args.length; i++)
System.out.println(args[i]);
}
}
Packages in Java

● Packages are nothing more than the way we organize files in to


different directories according to their functionality, usability as well as
category they should belong to

● Files in one directory (or package) would have different functionality


from those of another directory.
Import

● Import is a keyword in Java

● It is used to import classes of other packages


Access Modifiers
Java supports four categories of accessibility rules

● private
● protected
● public
● default

Modifiers can be used for class, member variables and member functions
With class
● Outer class can be either public or default

● For inner class any modifier can be used


Note:
● There can be only one public class in a single file.

● The name of the java a file must be same as the name of the public class

● Only public class can be accessed directly from outside the package
PackageExample1.java PackageExample2.java
package a; package b;
public class PackageExample2
import b.PackageExample2;
{
public class PackageExample1 extends PackageExample2{ protected void callMe()
{
public static void main(String[] args) {
System.out.println("I am in package b");
System.out.println("I am in package a");
}
PackageExample1 p1 = new PackageExample1(); }
p1.callMe();
}
}
Access Specifiers
Constructors in Java
● Constructor is a member function of a class

● The name of the Constructor is same as the name of the class

● Constructor has no return type


Properties of Constructor
● Constructor initialises the object just after the memory allotment

● Not mandatory to write a constructor as compiler provides one

● In case one writes its own constructor then compiler do not provide one

● Constructor can be parameterized and can be overloaded


ConstuctorExample.java
class Person{ public class ConstructorExample{
String name; public static void main(String [ ] args){
int age;
public Person(String n, int a){ Person p = new Person("Ram", 20);
name = n; p.display();
age = a; Employee e = new Employee("Manager");
}
public Person(){ e.display();
} }
public void display(){ }
System.out.println(name + "," + age);
}
}
class Employee extends Person{
String post;
public Employee(String p){
post = p;
}
public void display(){
System.out.println(name + "," + age +"," +post);
}
}
Constructor chaining

● Constructor can call other constructors of the same class or


superclass but not both

● Constructor call from a constructor must be the in the first line

● Such series of invocations of constructor is known as constructor


chaining
super() or this()

● First line of constructor can be either super()(by default) or this()

● Constructor never contains super() and this()


ChainExample.java
class Base{ class ChainExample extends Base{
String name; ChainExample(){
Base(){ System.out.println("No-argument constructor "
this(" "); +
System.out.println("No-argument constructor of" + "of derived");
}
" base class");
ChainExample(String name){
}
super(name);
Base(String name){ System.out.println("Calling parameterized " +
this.name = name; "constructor of derived");
System.out.println("Calling parameterized }
constructor"
+ " of base"); public static void main(String args[]){
} ChainExample obj = new ChainExample("test");
} ChainExample obj1 = new ChainExample();
}
}
Initialization Block
● Instance Initialization block

● Static Initialization block


Instance Initialization Block
● An instance initializer or Initialization block declared in a class is executed
when an instance of the class is created

● return keyword cannot be used in initialization block

● Instance initializers are permitted to refer to the current object via the keyword
this and to use the keyword super.
Static Initialization Block
● An static initializer declared in a class is executed when the class is initialized

● Static initializers may be used to initialize the class variables of the class

● return keyword cannot be used in static initialization block

● this or super can not be used in static block


Initialization.java
class Initilization { Initilization(int x)
static int a =10; {
static System.out.println(x);
{ }
System.out.println("Static Init block"); {
} System.out.println("second");
}
{
public static void main(String args[ ])
System.out.println("init");
} {
Initilization() System.out.println(Initilization.a);
{ new Initilization();
System.out.println("default"); new Initilization(10);
} }
}
Method Overloading in Java

● If two methods of a class


○ Either inherited
○ Or declared in the same class
○ Or one inherited and one declared

have the same name but different signatures then the


method is said to be overloaded
● Method overloading is a way to implement polymorphism
Method Overriding in Java

● Method in defining a method in the child class having the


same signature in the parent class
● Why to override?
The final keyword

● final can be used for an


○ Instance variable
○ Static variable
○ Local variable
○ Class
○ Methods
Final Instance Variable
● It can be initialized:
○ In the constructor
○ Using Initialization block
○ At the time of declaration
Final static Variable
● It can be initialized:
○ Using static initialization block
○ At the time of declaration
Final local Variable
● Local variables are by default blank with or without final
● They should be initialized before use
● In the case of final local variables; they can only be
initialized only once
Final class and final methods
● Final class cannot be inherited
● Final member function can not be overridden.
Uses of this keyword
class A{ class ThisExample{
String a;
void sendIt(String a){ public static void main(String[] args){
this.a = a; A a = new A();
B b = new B();
a.sendIt("Hello Dear!");
b.receive(this);
} A b = new A();
String getMessage(){ b.sendIt("");
return a;
} }
}
}
class B{
String b;
void receive(A objA){
b = objA.getMessage();
System.out.println("The Messaage is... " + b);
}
}
Abstract class in Java
● Abstract classes are declared with the abstract keyword

● An abstract class cannot be instantiated


Abstract class
Used to declare common characteristic of subclass

Only be used as a superclass for other classes that extend the abstract class

Rest of the things are exactly like other classes


Abstract class
You can not create object of abstract class but you can create reference variable
of abstract class.
AbstractExample.java
abstract class A{
void fun1(){
System.out.println("Method of A");
}
}
class B extends A{
void fun1(){
System.out.println("Method of B");
}
}
class AbstractExample{
public static void main(String [ ] args){
A a = new B();
a.fun1();

}
}
Abstract Methods
● Methods can contain no implementation

● Do not contain a body

● Therefore declaration must end with semicolon rather than a block


Abstract Methods
A class having any abstract method must be declared abstract
AbstractExample.java
class A{
void fun1();
}
class B extends A{

}
class AbstractExample{
public static void main(String [] args){
B b = new B();

}
}
AbstractExample.java
abstract class A{
abstract void fun1();
}
class B extends A{

}
class AbstractExample{
public static void main(String [] args){
B b = new B();

}
}
AbstractExample.java
abstract class A{
abstract void fun1();
}
abstract class B extends A{

}
class AbstractExample{
public static void main(String [] args){
B b = new B();

}
}
AbstractExample.java
abstract class A{
abstract void fun1();
}
abstract class B extends A{

}
class AbstractExample{
public static void main(String [] args){
//B b = new B();

}
}
Why do we make abstract methods?
Interface

Interface definition begins with a keyword interface


Interface SomeInterface{
}
Interface
● Methods in interfaces are implicitly public and abstract

● Fields are implicitly public static final.

interface A{
int x;
void fun();
}
Interface

● An interface like that of a abstract class cannot be instantiated

● Interface do not have constructors


Interface

● Any class implementing an interface should define all the methods


of the interface otherwise that has to be declared as abstract class

● You can create a reference variable of the interface

● This reference variable can refer to any of its subclass object


ExampleInterface.java
interface I1{ class A implements I3{
public void func1(){
void func1(); System.out.println("I am I1 func");
} }
interface I2{ public void func2(){
System.out.println("I am I2 func");
void func2(); }
} public void func3(){
System.out.println("I am I3 func");
interface I3 extends I1, I2{
}
void func3(); }
} class ExampleInterface{
public static void main(String [ ] args){
I1 i1 = new A();
i1.func1();
}
}
Abstract class and Interface

Abstract class can have any modifiers for members.


Interface can have only public members

interface I1{ abstract class A {


double PI = 3.14; int P1;
static void fun(){
System.out.println("HI there"); void fun();
} void fun1(){
void fun1(); System.out.println("HI there");
}
}

}
Abstract class and Interface

Abstract class may or may not contain abstract


method. Interface can not have defined methods if
they are not static.

interface I1{ abstract class A {


double PI = 3.14; int P1;
static void fun(){
System.out.println("HI there"); void fun();
} void fun1(){
void fun1(); System.out.println("HI there");
}
}

}
Abstract class and Interface
Abstract class can have static or non static members.
Interface can have only static member variables. If the
member functions are static then they have to have a
body otherwise they are abstract only.

interface I1{ abstract class A {


double PI = 3.14; int P1;
static void fun(){
System.out.println("HI there"); void fun();
} void fun1(){
void fun1(); System.out.println("HI there");
}
}

}
Abstract class and Interface
Abstract class can have final or not final members.
Interface can have only final member variables.

interface I1{ abstract class A {


double PI = 3.14; int P1;
static void fun(){
System.out.println("HI there"); void fun();
} void fun1(){
void fun1(); System.out.println("HI there");
}
}

}
Abstract class and Interface
Interface do not have constructors unlike abstract
class.

interface I1{ abstract class A {


double PI = 3.14; int P1;
static void fun(){
System.out.println("HI there"); void fun();
} void fun1(){
void fun1(); System.out.println("HI there");
}
}

}
String class

● A java.lang.String class is final

● String class in immutable: once created can not be changed on the


same reference.
Creating String Object

● A simple string can be created using a string literal enclosed inside


couple quotes
● String str1 = "How have you been";
Creating String with new keyword

String str1 = "How have you been";


String str2 = "How have you been";
String str3 = "How have" + "you been";

All the reference variables point to same memory location


Creating object with new

● String str1 = new String("How have you been");

● With new every time a new object is created


Concatenation Operator

String object can be used with the += and + operators for concatenation
StrEx.java
class StrEx{
public static void main(String [] args){
String s1 = "operating system";
String s2 = "operating system";
String s3 = new String ("operating system");
System.out.println("Result 1:" + (s1==s2));
System.out.println("Result 2:" + s1.equals(s2));
System.out.println("Result 3:" + (s1==s3));
System.out.println("Result 4:" + s1.equals(s3));

}
}
StrEx.java
class StrEx{
public static void main(String [] args){
String s1 = "operating system";
String s2 = "operating system";
String s3 = new String ("operating system");
System.out.println("Result 1:" + (s1==s2));//true
System.out.println("Result 2:" + s1.equals(s2));//true
System.out.println("Result 3:" + (s1==s3));//false
System.out.println("Result 4:" + s1.equals(s3));//true

}
}
Case conversion

● toUpperCase()
● toLowerCase()
They return the output and original string is unchanged
indexOf

● indexOf(int ch)
● indexOf(int ch, int fromIndex)
● indexOf(String str)
● indexOf(String str, int fromIndex)
● lastIndexOf(int ch)
● lastIndexOf(int ch, int fromIndex)
● lastIndexOf(String str)
● lastIndexOf(String str, int fromIndex)
Comparison

● equals()
● equalsIgnoreCase(String anotherString)
● compareTo(String str) //returns a number as the result
-ve: Dictionary order
+ve: Opp Dictionary order
Substring

● substring(int begIndex)
● substring(int begIndex,int endIndex)
Returns the substring
Exceptions in Java

Any abnormal unexpected events or extraordinary conditions


that may occur at runtime
So what is an exception?

Java Application Java Application


… …
Exception occured Exception occured

Our handling code
Default catch
mechanism
Four options for throwing the objects after exception

● Default throw and default catch


● Default throw and our catch
● Our throw and default catch
● Our throw and our catch
Exceptional handling

Java exception handling is used to handle error condition in a


program systematically by taking necessary action.
throw and catch

Java exceptions are raised with the throw keyword and


handled within a catch block
Exception.java
class Exception {
public static void main(String[ ] args) {
System.out.println("Previous line");
System.out.println("Result" + 3 / 0);
System.out.println("Last line");
}
}
NullPointer.java

class NullPointer{
public static void main(String[ ] args) {
String s1 = null;
System.out.println("Previous line");
System.out.println(s1.length());
System.out.println("Last line");
}
}
Throwable

● The Throwable class provides a String variable that can


be set by subclasses to provide a detail message that
provides more information of the exception occured.
● All classes of Throwable define a one parameter
constructor that takes a string as the detailed message.
● The class Throwable provides getMessage() function to
retrieve an exception.
Exceptions are of two types

● The class exception represents exceptions that a


program faces due to abnormal or special conditions
during execution

● Exception can be of 2 types: Checked( Compile time


exception) / Unchecked ( Run time Exceptions)
Unchecked Exceptions

● Unchecked exceptions are RuntimeException and any


of its subclasses

● ArrayIndexOutOfBounds, NullPointerException and so


on are subclasses of java.lang.RuntimeException class,
which is a subclass of the Exception class.
Default throw and our catch

try{
<code>

}catch (<exception type> <parameter>){


// some statements
}
finally{
//finally block statements
}
ExceptionHandling.java
class ExceptionHandling {
public static void main(String[] args) {
try {
String s1 = null;
System.out.println(s1.length());
System.out.println("After exception in try");
} catch (NullPointerException e) {
System.out.println("The problem is " + e.getMessage());
}
catch (ArithmeticException e) {
System.out.println("The problem is " + e.getMessage());
}finally {
System.out.println("Last line");
}
}
}
Four options for throwing the objects after exception

● Default throw and default catch


● Default throw and our catch
● Our throw and default catch
● Our throw and our catch
Explicit throw

● A program can explicitly throw an exception using the


throw statement besides the implicit exception thrown
● Syntax
○ throw <throwableInstance>;
Explicit throw

● throw <throwableInstance>;
● The exception reference must be of type Throwable
class or one of its subclasses.
● A detailed message can be passed to the constructor
when the exception object is created.
OurThrowJavaCatch.java

class OurThrowJavaCatch {
public static void main(String[] args) {
int balance = 500;
int withdrawal = 600;
if (withdrawal > balance){
throw new ArithmeticException("Not sufficient balance");
}
balance =- withdrawal;
System.out.println("Transaction successful");
}
}
OurThrowOurCatch.java

class OurThrowOurCatch {
public static void main(String[] args) {
int balance = 500;
int withdrawal = 600;
try{
if(withdrawal > balance)
throw new ArithmeticException("Not sufficient balance");
balance =- withdrawal;
System.out.println("Transaction successful");
}catch( ArithmeticException e){
System.out.println(e.getMessage()); }
System.out.println("Transaction unsuccessful");
}
}
OurThrowOurCatch.java
class OutThrowOurCatch {
public static void main(String[] args) {
int balance = 500;
int withdrawal = 600;
try {
// if(withdrawal > balance)
// throw new ArithmeticException("Not sufficient balance");
balance = -withdrawal;
System.out.println("Transaction successful");
} catch (ArithmeticException e) {
System.out.println(e.getMessage());
} finally {
System.out.println("Transaction unsuccessful");
}
System.out.println("Program continues");
}
Handling checked Exceptions
● There is a compile time error when the checked exception is not reported/handled

● Java forces programmers to deal with the exceptions that may be thrown

● IOException, SQlExceptions are the examples of checked exceptions


throws
● throws clause can be used in the method prototype to indicate that the method can
throw one or more exceptions

● Method() throws Exception1, Exception2 ….{


}

● Arguments of throws are exception classes.


What is a thread?
● A thread is an independent path of execution in a
program.

● Many threads can run concurrently within a program.

● Multithreading refers to two or more tasks executing


concurrently with in a single program
Thread Class
● Every thread in Java is created and controlled by
java.lang.Thread class
Creating Thread
● There are two ways to create thread in java
○ Implement the Runnable interface
(java.lang.Runnable)
○ By Extending the Thread class
(java.lang.Thread)
ThreadInterface.java
class A implements Runnable{ class ThreadInterface{
public void run(){ public static void main(String[ ] args){
for(int i=0;i<10;i++) Thread t1 = new Thread(new A());
System.out.println("Thread A:" + i); Thread t2 = new Thread(new B());
} t1.start();
} t2.start();
class B implements Runnable{ }
public void run(){ }
for(int i=0;i<10;i++)
System.out.println("Thread B:" + i);
}
}
ThreadClass.java
class A extends Thread{ class ThreadClass{
public void run(){ public static void main(String[]
for(int i=0;i<10;i++) args){
System.out.println("Thread A:" + A t1 = new A();
i); B t2 = new B();
} t1.start();
} t2.start();
class B extends Thread{ }
public void run(){ }
for(int i=0;i<10;i++)
System.out.println("Thread B:" +
i);
}
}
ThreadInterface.java: Threads accessing common item
class A implements Runnable{ class ThreadInterface{
public void run(){ public static int count;
public static void main(String[] args) throws
for(int i=0;i<10;i++){
InterruptedException{
System.out.println("Thread A:" + i); Thread t1 = new Thread(new A());
ThreadInterface.count++; Thread t2 = new Thread(new B());
} t1.start();
} t2.start();
t1.join();
}
t2.join();
class B implements Runnable{ System.out.println("The value of count is" +
public void run(){ count);
for(int i=0;i<10;i++){ }
System.out.println("Thread B:" + i); }
ThreadInterface.count++;
}
}
}
Thread States
● A Java thread is always in one of the several states
which could be running, sleeping, dead, etc.
● States:
○ New thread
○ Runnable
○ Blocked
○ Waiting
○ Timed Waiting
○ Terminated
New Thread
● When the Thread object is created but it has not
started running
● A thread starts life in the Ready-to-run state.
● Only start() or stop() can be called in this state
otherwise an exception named
IllegalThreadStateException will be raised
Runnable
● When the start() method is invoked on a New Thread
it gets to the runnable or running state by calling the
run() method.
● A runnable thread may actually be running, or may be
waiting its turn to run
Not Runnable
● When sleep() method is invoked
● When suspend() method is invoked
● When the wait() method is invoked
● A thread is blocking on I/O
Switching from not runnable to runnable
● If sleep() method is invoked, then after number of
millisecond
● When suspend() method is invoked then after
resume()
● When the wait() method is invoked then other threads
must call notify() or notifyAll()
● A thread is blocking on I/O then I/O must complete
Dead State
● When run() has finished or when stop() is invoked
Synchronized block/method
● Java programming language provides a very handy
way of synchronizing either task by using
synchronized blocks/methods
● You keep the shared resources within the block.
synchronized(objectreference){
}
● You write the synchronized keyword before any
method of shared object.
import java.util.Scanner; public void run(){
class Account{ Scanner sc = new Scanner(System.in);
int balance; System.out.println("Enter the amount to be withdrawn by
public Account(int balance){ "+this.name);
this.balance = balance; int amt = sc.nextInt();
} if(acc.checkBalance(amt)){
System.out.println("Sucessful withdrawl by
boolean checkBalance(int withAmt){ "+this.name);
if(balance >= withAmt) acc.withdraw(amt);
return true; }
else return false;} else
void withdraw(int withAmt){ System.out.println("Insuffcient Balance");
balance-= withAmt; }
System.out.println(" Balance is "+ balance); }
} class SynExample{
} public static void main(String args[]){
class Customer implements Runnable{ Account acc = new Account(1000);
Account acc; Customer c1 = new Customer(acc, "First");
String name; Customer c2 = new Customer(acc, "Second");
public Customer(Account acc, String name){ Thread t1 = new Thread(c1);
this.acc = acc; Thread t2 = new Thread(c2);
this.name = name; t1.start();
} t2.start();
}
}
import java.util.Scanner; public void run(){
class Account{ Scanner sc = new Scanner(System.in);
int balance; System.out.println("Enter the amount to be withdrawn by
public Account(int balance){ "+this.name);
this.balance = balance; int amt = sc.nextInt();
synchronized(acc){
} if(acc.checkBalance(amt)){
System.out.println("Sucessful withdrawl by
boolean checkBalance(int withAmt){ "+this.name);
if(balance >= withAmt) acc.withdraw(amt);
return true; }
else return false;} else
void withdraw(int withAmt){ System.out.println("Insuffcient Balance");
balance-= withAmt; }
System.out.println(" Balance is "+ balance); }
}
}
class SynExample{
} public static void main(String args[]){
class Customer implements Runnable{ Account acc = new Account(1000);
Account acc; Customer c1 = new Customer(acc, "First");
String name; Customer c2 = new Customer(acc, "Second");
public Customer(Account acc, String name){ Thread t1 = new Thread(c1);
this.acc = acc; Thread t2 = new Thread(c2);
this.name = name; t1.start();
} t2.start();
}
}
Nested Class (Inner Class)
● Classes in Java can have another class as its
members.
● This class is called nested class
● The class that hosts the inner class is called outer
class
Syntax
class Outer{
class Inner {
}
}
Types of inner class
● Static inner class
● Non static inner class
Difference
● Static inner class instance can be created outside the
outer class with the following syntax
○ Outer.Inner obj = new Outer.Inner();
● Object of outer class need not be created in this case
● Whereas in instance inner class the syntax is
○ Outer.Inner obj = outObj. new Inner();
Where outObj is the object of outer class
Access modifiers of classes
● Outer class can have only public and default access
modifiers
● Inner class can have any access modifiers
NonStaticInnerClass
class OuterClass {
int x = 10;
class InnerClass {
int y = 5;
}
}

public class NonStaticInnerClass {


public static void main(String[ ] args) {
OuterClass myOuter = new OuterClass();
OuterClass.InnerClass myInner = myOuter.new InnerClass();
System.out.println(myInner.y + myOuter.x);
}
}
StaticInnerClass
class OuterClass {
int x = 10;
static class InnerClass {
int y = 5;
}
}

public class NonStaticInnerClass {


public static void main(String[ ] args) {
OuterClass myOuter = new OuterClass();
OuterClass.InnerClass myInner = new OuterClass.InnerClass();
System.out.println(myInner.y + myOuter.x);
}
}
Anonymous class
● Always the inner classes without a name

● They are always the child class of some class


Definition of an Anonymous class
Let there be a class called Wishes
Then an instance of an anonymous class is created as:
Wishes w = new Wishes(){
public void aWish(){
system.out.println(“Hello”);
}
}
Note
Let there be a class called Wishes
Then an instance of an anonymous class is created as:
Wishes w = new Wishes(){
public void aWish(){
system.out.println(“Hello”);
}
}
● We created an instance of a subclass
● Anonymous class is a subclass of Wishes
AnonymousClass.java
class Wishes{
public void aWish(){
System.out.println("Good Morning");
}
}

class AnonymousClass{
public static void main(String[] args){
AnonymousClass a = new AnonymousClass();
a.w.aWish();
}
Wishes w = new Wishes(){
public void aWish(){
System.out.println("Hello");
}
};
}
Generics
Java Generic methods and generic classes enable
programmers to specify, with a single method declaration,
a set of related methods or, with a single class declaration,
a set of related types
WithoutGenerics.java: (The problem)

iclass IntegerPrinter{ class WithoutGenerics{


Integer thingToPrint; public static void main(String[] args){
IntegerPrinter(Integer thingToPrint){ IntegerPrinter printerI = new IntegerPrinter(23);
this.thingToPrint = thingToPrint;
printerI.printInteger();
}
void printInteger(){ StringPrinter printerS = new StringPrinter("Hello
System.out.println(thingToPrint); World");
} printerS.printString();
} }
class StringPrinter{
}
String thingToPrint;
StringPrinter(String thingToPrint){
this.thingToPrint = thingToPrint;
}
void printString(){
System.out.println(thingToPrint);
}
}
Generic Class
A generic class declaration looks like a non-generic class
declaration, except that the class name is followed by a
type parameter section.
Generic and generic methods can have one or more type
parameters separated by commas.
Generic class
class Printer<T>{
T thingToPrint;
Printer(T thingToPrint){
this.thingToPrint = thingToPrint;
}
void print(){
System.out.println(thingToPrint);
}
}
class WithGenerics{
public static void main(String[] args){
Printer <Integer> printerI = new Printer<>(23);
printerI.print();
Printer <String>printerS = new Printer<>("Hello World");
printerS.print();
}
}
Generic Method
class GenericMethod {
public static void main(String[] args) {
DemoClass demo = new DemoClass();
demo.<String>genericsMethod("Java Programming");
demo.<Integer>genericsMethod(25);
}
}

class DemoClass {
public <T> void genericsMethod(T data) {
System.out.println("Generics Method:");
System.out.println("Data Passed: " + data);
}
Rules
All generic method declarations have a type parameter
section delimited by angle brackets(< and >) that precedes
the method’s return type
Each type parameter section contains one or more type
parameters separated by commas
The type parameters can be used to declare the return
type
Important
Type parameters can represent only reference types, not
primitive types(like int, double and char)
GenericsExample.java

public class GenericsExample{


public static void main(String[] args){
shout("John", 74);
}
private static <T, V> void shout(T thing, V otherthing){
System.out.println(thing + "!!!!");
System.out.println(otherThing + "!!!!");
}
}
Bounded Types

class Bound<T extends A>{ class C extends A{


private T objRef; public void displayClass() {
public Bound(T obj){ System.out.println("Inside sub class C");
this.objRef = obj; }
} }
public void doRunTest(){
objRef.displayClass();
public class BoundedClass{
} public static void main(String a[]){
}
Bound<C> bec = new Bound<C>(new C());
class A{ bec.doRunTest();
public void displayClass() {
System.out.println("Inside super class A"); Bound<B> beb = new Bound<B>(new B());
} beb.doRunTest();
}

class B extends A{
public void displayClass() {
Bound<A> bea = new Bound<A>(new A());
System.out.println("Inside sub class B"); bea.doRunTest();
}
} }
}
Bounded Types

class Bound<T extends A>{ class C extends A{


private T objRef; public void displayClass() {
public Bound(T obj){ System.out.println("Inside sub class C");
}
this.objRef = obj; }
}
public class BoundedClass{
public void doRunTest(){ public static void main(String a[]){
objRef.displayClass();
} Bound<C> bec = new Bound<C>(new C());
} bec.doRunTest();

class A{ Bound<B> beb = new Bound<B>(new B());


beb.doRunTest();
public void displayClass() {
System.out.println("Inside super class A");
} Bound<A> bea = new Bound<A>(new A());
} bea.doRunTest();

class B extends A{ Bound<String> bes = new Bound<String>(new String());


public void displayClass() { bea.doRunTest();
System.out.println("Inside sub class B");
}
}
}
}
Multiple Bounded Types

class Bound<T extends A & B>{ class A implements B{


public void displayClass() {
private T objRef; System.out.println("Inside super class A");
public Bound(T obj){ }
this.objRef = obj; }
}
public class BoundedClass{
public void doRunTest(){
public static void main(String a[]){
this.objRef.displayClass();
} Bound<A> bea = new Bound<A>(new A());
} bea.doRunTest();
}
interface B{ }
public void displayClass();
}
Lambda
interface Printable{ class Lambda{
void print(); public static void main(String[] args){
} Cat mycat = new Cat();
public class Cat implements Printable{ myCat.print();
public String name; }
public int age; static void printThing(Printable thing){
public Cat(){} thing.print();
public void print(){ }
System.out.println("Hello"); }
}
}
Lambda
interface Printable{ class Lambda{
void print(); public static void main(String[] args){
} Cat mycat = new Cat();
public class Cat implements Printable{ printThing(mycat);
public String name;
public int age; }
public Cat(){} static void printThing(Printable thing){
public void print(){ thing.print();
System.out.println("Hello"); }
} }
} All this just for providing the implementation of
print() method
Lambda
interface Printable{ class Lambda{
public static void main(String[] args){
void print(); Cat mycat = new Cat();
} printThing(
()->{
public class Cat implements Printable{ System.out.println("Hello");
public String name; }
public int age; );
}
public Cat(){}
public void print(){
}
System.out.println("Hello"); static void printThing(Printable thing){
} thing.print();
}
} }
Lambda syntax:
We delete access specifier, return type and name of
function
We add the arrow after parentheses
Lambda

interface Printable{
void print();
}

public class Lambda{


public static void main(String[] args){

printThing(()-> System.out.println("Hello"));
}
static void printThing(Printable thing){
thing.print();
}
}
Lambda
interface Printable{
void print(String s);
}

public class Lambda{


public static void main(String[] args){

printThing((s)-> System.out.println("Hello" + s)); //Type of parameter not required


}
static void printThing(Printable thing){
thing.print(“World”);
}
}
Lambda
interface Printable{
void print(String s);
}

public class Lambda{


public static void main(String[] args){

printThing(s-> System.out.println("Hello" + s)); //Parenthesis not required in case of


//single parameter
}
static void printThing(Printable thing){
thing.print(“World”);
}
}
Lambda
interface Printable{
String print(String s);
}

public class Lambda{


public static void main(String[] args){

printThing(s-> "Hello" + s); //return keyword not required in case of single expression
}
static void printThing(Printable thing){
thing.print(“World”);
}
}
Reflection
class GFG {
Reflection public static void main(String args[]) throws Exception{
Test obj = new Test();
Class cls = obj.getClass();
System.out.println("The name of class is "
import java.lang.reflect.Constructor; + cls.getName());
Constructor constructor = cls.getConstructor();
import java.lang.reflect.Field;
System.out.println("The name of constructor is "
import java.lang.reflect.Method;
+ constructor.getName());
System.out.println("The public methods of class are : ");
class Test { Method[] methods = cls.getMethods();
for (Method method : methods)
private String s; System.out.println(method.getName());
public Test() { s = "Hello"; } Method methodcall1
= cls.getDeclaredMethod("method2", int.class);
methodcall1.invoke(obj, 19);
public void method1() { Field field = cls.getDeclaredField("s");
System.out.println("The string is " + s); field.setAccessible(true);
} field.set(obj, "JAVA");
Method methodcall2
public void method2(int n) { = cls.getDeclaredMethod("method1");
System.out.println("The number is " + n); methodcall2.invoke(obj);
Method methodcall3
}
= cls.getDeclaredMethod("method3");
private void method3() { methodcall3.setAccessible(true);
System.out.println("Private method invoked"); methodcall3.invoke(obj);
} }
} }
public class ReflectionEx{
Reflection public static void main(String[] args) throws Exception{
Person newPerson = new Person("John", 35);
import java.lang.reflect.Field;
Field[] personFields=
import java.lang.reflect.Method;
class Person{ newPerson.getClass().getDeclaredFields();
private final String name; for(Field field: personFields){
private int age; System.out.println(field.getName());
public Person(String name, int age){ }
this.name = name;
this.age=age;
for(Field field: personFields){
} if(field.getName().equals("name")){
public String getName(){ field.setAccessible(true);
return name; field.set(newPerson, "Tred");
}
public int getAge(){
return age; }
} }
public void setAge(int age){ System.out.println(newPerson.getName());
this.age=age; Method[] personMethods =
} newPerson.getClass().getDeclaredMethods();
public void greet(){
System.out.print("Hello"); for(Method method: personMethods){
} System.out.println(method.getName());
private void heyThisIsPrivate(){ }
System.out.print("How did you call this??"); for(Method method: personMethods){
}
public static void thisIsPublicStaticMethod(){
if(method.getName().equals("heyThisIsPrivate")){
System.out.println("I'm public and static!'"); method.setAccessible(true);
} method.invoke(newPerson);
public static void thisIsPrivateStaticMethod(){ }
System.out.println("I'm private and static!'"); }
}
} }
}

You might also like