Java Programming-10
Java Programming-10
int a = 3;
float b = a; //no issues
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.
● 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
● 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
● In case one writes its own constructor then compiler do not provide one
● 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
Only be used as a superclass for other classes that extend the abstract class
}
}
Abstract Methods
● Methods can contain no implementation
}
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 A{
int x;
void fun();
}
Interface
}
Abstract class and Interface
}
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.
}
Abstract class and Interface
Abstract class can have final or not final members.
Interface can have only final member variables.
}
Abstract class and Interface
Interface do not have constructors unlike abstract
class.
}
String class
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
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
try{
<code>
● 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
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)
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
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
interface Printable{
void print();
}
printThing(()-> System.out.println("Hello"));
}
static void printThing(Printable thing){
thing.print();
}
}
Lambda
interface Printable{
void print(String s);
}
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!'"); }
}
} }
}