java tutorial
  1. What is JAVA
  2. History of Java 
  3. Java Hello World Program
  4. Features of Java
  5. Difference between JDK, JRE and JVM
  6. Variables in Java
    1. Naming convention
    2. Instance Variables in JAVA
    3. Static Variables in Java
    4. Local Variables in Java
  7. Operators in Java
    1. Unary Operators
    2. Arithmetic Operators
    3. Shift Operators
    4. Relational Operators
    5. Bitwise Operators
    6. Logical Operators
    7. Assignment Operator
    8. Ternary Operator     
  8. Primitive Data types in Java
  9. Conditional Statements
    1. If else
    2. Switch
  10. Loops
    1. While loop Java
    2. For loop Java
    3. Do while Java
  11. Branching Statements in Java
    1. Break
    2. Continue
    3. Return
  12. Comment
  13.  Java Class
  14. Object
  15. Constructor in Java
  16. Super
  17. This
  18. Inheritance in Java
  19. Method Overloading in Java
  20. Method Overriding in Java
  21. Abstract class in Java
  22. Interface in Java
  23. Exception Handling in Java
    1. Try
    2. Catch
    3. Finally
    4. Throw
    5. Throws
  24. String

What is JAVA

Java is a high-level object-oriented programming language that was originally developed by Sun Microsystems.

It follows the principle of WORA(Write Once Run Anywhere) – you can run a java program as many times as you want on a java supported platform after it is compiled. There is no need for recompilation. 

History of JAVA

  • 1991: Java was first designed for the digital cable television industry
  • It was initially known as Green Team
  • Later it got renamed to Oak based on the Oak tree outside James Gosling’s Office
  • 1995: Oak got changed to Java based on the island in Indonesia from which the team used to have coffee.
  • Java was included in the Time magazine’s “Top Ten Best Product of 1995”
  • 1996: JDK 1.0 got released

Java’s Hello World

public class MyFirstCode {
	public static void main (String[] args) {
		//to print on console
System.out.println("Hello World!");
	}
}
  • Everything bold is a keyword which are words with some fixed meaning
  • ‘Class’ is used to declare class in Java
  • ‘Public’ is an access modifier which allows visibility to all
  • ‘Static’ doesn’t need object to get called and main gets called by JVM
  • ‘Void’ means that function will not return anything

Now, since we have some understanding of code, for running the code following are the steps:

  1. After setting up your environment, open cmd
  2. To compile, type javac MyFirstCode.java 
  3. To run, type java MyFirstCode

This will print your output: Hello World!

Features 

  • Simplicity: it is very easy to learn as syntax is similar to previously existing language like c and c++
  • Object-oriented: Java is based on objects which imitate real-world problems. It supports 4 pillars of the object-oriented language, i.e., Inheritance, Polymorphism, Abstraction and Encapsulation.
  • Platform Independent: It has its own virtual machine and converts the code into bytecode which can run in a java supported platform.
  • Secured: Java is way more secured because it has its own box responsible for handling its execution. It does not support pointers and multiple inheritances which can cause ambiguity or lead programs to crash.
  • Efficiency: It is much more efficient because it uses a JIT(Just In Time) compiler that basically utilises the best of 2 worlds i.e., compiler and interpreter.
  • Multi-threaded: Java supports thread, that basically allows multiple tasks to execute concurrently without occupying much memory.

JDK, JRE and JVM 

  • JVM: Java Virtual Machine
    • This is a virtual(abstract) machine that holds all java executions
    • It doesn’t exist in reality.
    • It also manages heap memory, garbage collector, etc.
  • JRE: Java Runtime environment
    • It is responsible for running pre-compiled java programs
    • It contains all files and libraries to facilitate the running of java code
    • It can’t help one in development.
  • JDK: Java Development toolkit
    • This is a software that helps one in the development of Java applications.
    • It is basically JRE+Development tools

Variables

  • Variable is the name of a memory location where the data is stored.
  • Syntax:  datatype varname = val;             

   Example:

public class VariableDemo {
	public static void main (String[] args) {
		//var declaration and initialization
		int roll_num=23;
		String first_name="adam";
		
		//just declaration
		int marks;
		
		//later initialization
		marks=89;
System.out.println("Hi I am "+first_name+" roll_no "+rollno+" and I scored "+marks);
	}
}

Output:

Hi I am adam rollno 23 and I scored 89

Naming Convention

  • Variable names should begin with a letter, $, or an underscore(_)
  • The first character can be then followed by any combination of letters or digits
  • A variable name cannot be the same as any keyword as they are reserved for special purposes
  • Variable names case sensitive
    • Eg: valid- apple, _name, $address1
    • Eg: invalid- 123apple, *roll, @email

There are 3 types of variables in Java

Instance variable

  • Variable declared outside of any methods but within the class
  • Can be accessed by the all the methods of class irrespective of its access specifier 
  • Every object of the class gets its own original copy of variable
  • Also known as class variables
  • Variables declared as static, maintains a single copy in memory and is shared by all the objects of the class
  • They can be directly called using class name as classname.var_name
  • Non-static methods can’t access or manipulate static variables

Local variable

  • Variables defined inside methods fall into this category.
  • They are accessible in the scope where it is declared.
  • They remain hidden outside of their methods.

Example:

class VariableDemo  {
	public static void main (String[] args) {
	    int i=100;//instance variable  
        static int j=200;//static variable  
        
        void method(){  
        int k=300;//local variable  
            } 	
      }
}

Operators

Unary operators

  • It needs one operand
  • We have 2 major operators here i.e, increment and decrement and each one have 2 variations of postfix and prefix
  • Increment – to increase the value by 1
    • postfix: first assign then increment
    • prefix: first increment then assign
  • Decrement – to decrease the value by 1
    • postfix: first assign then decrement
    • prefix: first decrement then assign

Example:

public class UnaryDemo {
	public static void main (String[] args) {
	    int a,b,c,d;
	    a=b=c=d=5;
	    a++;
	    ++b;
	    c--;
	    --d;
		System.out.println("a= "+a);
		System.out.println("b= "+b);
		System.out.println("c= "+c);
		System.out.println("d= "+d);
	}
}

Output:

a= 6
b= 6
c= 4
d= 4

Arithmetic operators

  • It comprises all binary arithmetic operations like add, subtract, multiply, divide etc.
  • Another addition operator is modulus(%), which gives you the remainder.

Example:

public class ArithmeticDemo {
	public static void main (String[] args) {
	    int a,b,c,d;
	    a=6+5;
	    b=6-5;
	    c=6*5;
	    d=6/5;
		System.out.println("a= "+a);
		System.out.println("b= "+b);
		System.out.println("c= "+c);
		System.out.println("d= "+d);
	}
}

Output:

a= 11
b= 1
c= 30
d= 1

Shift operators

  • Two variations – left and right shift
  • left shift: shift bits in left direction for specified value
  • right shift: shift bits in right direction for specified value

Example:

public class ShiftDemo {
	public static void main (String[] args) {
	    int a,b;
	    a=b=8;
	    a<<=2;
	    b>>=2;
		System.out.println("a= "+a);
		System.out.println("b= "+b);
	
	}
}

Output:

a= 32
b= 2

Relational operators

  • It comprises operators for comparisons
  • There are operators to check inequality i.e., < ,>, <=, >=
  • For equality check, we have 2 operators i.e., == and !=

Example:

public class RelationalDemo {
	public static void main (String[] args) {
	    int a,b,c;
	    a=1;
	    b=2;
	    c=1;
		System.out.println("a<b "+ (a<b));
		System.out.println("a>b "+ (a>b));
		System.out.println("a<=b "+ (a<=b));
		System.out.println("a>=c "+ (a>=c));
	    System.out.println("a!=b "+ (a!=b));
		System.out.println("a==c "+ (a==c));
	}
}

Output:

a<b true
a>b false
a<=b true
a>=c true
a!=b true
a==c true

Bitwise operators

It computes by going bit by bit. Both sides are checked irrespective of what the first expression computes to. Four major bit operators are:

  • & – bitwise and, which returns 1 if both bits are 1 else 0.
  • | – bitwise or, which returns 1 if either of bits is 1 else 0.
  • ^ – bitwise xor, which returns 1 if both bits are different else 0.
  • ~ – bitwise not, which changes 1 to 0 and vice versa.

Example:

public class BitwiseDemo {
	public static void main (String[] args) {
	    int a,b;
	    a=1;
	    b=2;
		System.out.println("a&b  = "+ (a&b));
		System.out.println("a|b  = "+ (a|b));
		System.out.println("a^b  = "+ (a^b));
		System.out.println("~a  = "+ (~a));
	   
	}
}

Output:

a&b = 0
a|b = 3
a^b = 3
~a = -2

Logical operators

These are used for conditions comparison that basically checks for the validity of them. They are also used in loops as part of termination conditions. If the first condition is enough to give the final verdict, it will not evaluate the second one.

There are 3 logical operators:

  • && – logical AND, returns true when both conditions evaluate to true
  • || – logical OR, returns true when either of the conditions evaluates to true
  • ! – logical not, return true when the condition evaluates to false

Example:

public class LogicalDemo {
	public static void main (String[] args) {
	    int a,b;
	    a=1;
	    b=2;
		System.out.println("a==1 && b==1 "+ (a==1 && b==1));
		System.out.println("a==1 || b==1 "+ (a==1 || b==1));
		System.out.println("!a "+ !(a==1));

	}
}

Output:

a==1 && b==1 false
a==1 || b==1 true
!a false 

Assignment operator 

Assignment operator(=) is used to assign right-hand side value to the left-hand side variable.

Ternary operator(?:)

An alternative of if-else. Condition is placed before ‘?’ and if evaluates to true then LHS of the colon gets executed else RHS of the colon will be executed.

Example:

public class MiscDemo {
	public static void main (String[] args) {
	    int a;
	    //assignment operator
	    a=1;
		System.out.println("(a==1?\"expression is true\":\"expression is false\" = \n "+ (a==1?"expression is true":"expression is false"));
		

	}
}

Output:

(a==1?"expression is true":"expression is false" = 
expression is true

Primitive Data types in Java 

There are different types of data that one deals with in real life. To process them we need different types of containers or data types as storage. In java, there are 8 primitive data types:

  • byte – size is 1 byte and by default, it holds 0
  • int – size is 4 byte and by default, it holds 0
  • short – size is 2 byte and by default, it holds 0
  • long – size is 8 byte and by default it holds 0L
  • char – size is 2 byte and by default, it holds ‘\u0000’
  • boolean – size is 1 bit and by default it holds false
  • float – size is 4 byte and by default it holds 0.0f
  • double – size is 8 byte and by default, it holds 0.0d

There are also some non-primitive data types like arrays, classes such as String etc.

Conditional Statements

if-else

The if-else statement consists of 2 keywords, if and else. This is a way where there are 2 paths possible depending upon a condition. I.e., ‘if’ condition manipulates to true then it gets executed otherwise code ‘else’ will execute. You can multiple ‘else if’ followed by else if there are more possible paths. Also, nested if and else are possible.

Control flow diagram:

Example:

public class IfElseDemo  {
	public static void main (String[] args) {
		int a=5,b=6;
		if(a+b==11)
		    System.out.println("equal");
		else
		    System.out.println("not equal");
	}
}

Output:

true

switch

It is an elegant way to replace multiple else-if

Syntax:

switch(expression)
{
    case val: ... ; 
              break;
    case val: ... ; 
              break;
    case val: ... ; 
              break;
    default: ...;
}

Here depending upon the answer evaluated by the condition, case code gets executed. Every case must be followed by break unless it is required not to as per logic. Otherwise, all cases will start executing from the matched case till either break is encountered or all cases get exhausted.

‘default’ is optional and holds the code which should be executed if no catches get matched.

‘val’ can be integer, char or String in java.

Example:

public class SwitchDemo {
	public static void main (String[] args) {
		String day="sun";
		switch(day)
		{
		    case "mon": System.out.println("Today is monday");
		                   break;
		    case "tues": System.out.println("Today is tuesday");
		                   break;
		    case "wed": System.out.println("Today is wednesday");
		                   break;
		    case "thurs": System.out.println("Today is thursday");
		                   break;
		    case "fri": System.out.println("Today is friday");
		                   break;
		    case "sat": System.out.println("Today is saturday");
		                   break;
		    case "sun": System.out.println("Today is sunday");
		                   break;
		    default : System.out.println("day is invalid!");
		}
	}
}

Output:

Today is sunday

Loops

Three major loops are ‘for’, ‘while’, and ‘do while’

for loop java:

It is best to use when we know the specified number of times the code should execute.

Syntax:

for( initialization; termination; updation){
}
  • ‘initialization’ is used to initialize the variable, which is being used for iteration.
  • ‘termination’ – comprises conditions which determine till when iteration will continue.
  • ‘updation’ – how our variable will get updated.

Example:

public class ForDemo {
	public static void main (String[] args) {
		for(int i=0;i<5;i++)
		    System.out.println("current value of i : "+i);
	}
}

Output:

current value of i : 0
current value of i : 1
current value of i : 2
current value of i : 3
current value of i : 4

while loop java

It is best to use when we know the specified expression depending on whose value the code should execute.

Syntax:

while( expression ){
}

‘expression’ is used to dictate the condition who is responsible for loop continuation.

Example:

public class WhileDemo {
	public static void main (String[] args) {
		int i=0;
		while(i<5){
		    System.out.println("current value of i : "+i);
		    i++;
		}
	}
}

Output:

current value of i : 0
current value of i : 1
current value of i : 2
current value of i : 3
current value of i : 4

do-while loop java :

It is best to use when we know that at least code must execute once irrespective of the condition.

Syntax:

do{
}while( expression );

‘expression’ is used to dictate the condition who is responsible for loop continuation.

Example:

public class DoWhileDemo {
	public static void main (String[] args) {
		int i=0;
		do{
		    System.out.println("current value of i : "+i);
		    i++;
		}while(i<5);
	}
}

Output:

current value of i : 0
current value of i : 1
current value of i : 2
current value of i : 3
current value of i : 4

Branching Statements in Java

break

It is a keyword that basically terminates the current loop and moves execution out of the loop

for(.........){
break;
} ==>execution comes here when the break is encountered

Example:

public class BreakDemo {
	public static void main (String[] args) {
		int i=0;
		while(i<5){
		    System.out.println("current value of i : "+i);
		    i++;
		    if(i==3)
		        break;
		}
		
		System.out.println("Out of loop!");
	}
}

Output:

current value of i : 0
current value of i : 1
current value of i : 2
Out of loop!

continue

It is a keyword that basically terminates the current iteration and moves execution to the update part of the loop. In ‘while’ and ‘do-while’, when continue is encountered, it will ignore the rest of the code

for(.. ; .... ; ...)==>execution comes here when break is encountered
{
continue;
} 

Example:

public class ContinueDemo {
	public static void main (String[] args) {
		for(int i=0;i<5;i++){
	   
		    if(i==3)
		        continue;
		    System.out.println("current value of i : "+i);
		   
		}
		
		System.out.println("Out of loop!");
	}
}

Output:

current value of i : 0
current value of i : 1
current value of i : 2
current value of i : 4
Out of loop!

return

It returns from its block of code i.e. if it is inside a function, it will exit from it.

main(.........){
return;
} 
==>exists from the program

Example:

public class ReturnDemo {
	public static void main (String[] args) {
		for(int i=0;i<5;i++){
	   
		    if(i==3)
		        return;
		    System.out.println("current value of i : "+i);
		   
		}
		
		System.out.println("Out of loop!");
	}
}

Output:

current value of i : 0
current value of i : 1
current value of i : 2

Comment

Comments are used to give a brief description of what is the logic behind code. They are just ignored by the compiler at the time of execution.

In java, we have sing line and multi-line comments:

// - single line

and 

/*
….
…. 
*/ - multi line

 

Java Class

It is a blueprint of a real-life entity and consists of the data and methods. Basically, it is the implementation of Encapsulation which is one of the OOPs pillars.

Keyword class is used to declare the class in java. As per naming convention, the class name follows that the first letter of every word should be in uppercase. Also, all code must be in some class and the single document can have multiple classes but only 1 public class

Example

class Container{
   
//data members 
     int weight;
    String color;
    double price;
    
//methods
    void setWeight(int w){
        weight=w;
    }
    void setColor(int c){
        color=c;
    }
    void setPrice(int p){
        price=p;
    }
    void print(){
        System.out.println(weight+" "+color+" "+price);
    }
}

Object

It is basically a physical entity of class, a class’s instance. The new keyword is used to create objects and allocate memory in Heap. When we create an object, it calls for the constructor of a class.

Example:

Container c1=new Container();

Constructor in Java

The constructor is a special method that is used to allocate memory and initialize objects. It doesn’t have any return type and its name is same as of its class name. The compiler implicitly provides a default constructor to allocate the memory if no constructor is explicitly defined.

Constructor having parameters are categorised as parameterised constructor. When new is encountered, it calls for the constructor. Parameters passed at the time of the creation of the object determines which constructor should be called.

Example:

class Container{
    int weight;
    String color;
    double price;
    
    //parameterized constructor
    Container(int w,String c,double p)
    {
        weight=w;
        color=c;
        price=p;
        System.out.println("I am a parameterized constructor");
    }
    
    //default constructor
    Container()
    {
        System.out.println("I am a default constructor");
    }
    
    void print(){
        System.out.println(weight+" "+color+" "+price);
    }
}
public class ConstructorDemo {
	public static void main (String[] args) {
	    Container c1=new Container();
	    Container c2=new Container(10,"red",567.85);
	    c1.print();
	    c2.print();
	}
}

Output:

I am a default constructor
I am a parameterized constructor
0 null 0.0
10 red 567.85 

Super 

‘Super’ is generally associated with parent class. It extends keyword used for an inheritance that will establish a child-parent relationship. You can call parent’s method, data members and constructor using super. While calling the parent’s constructor using super, it should be the 1st line in the code block

This

‘This’ is generally associated with the current class. You can call current class method, data members and constructor using this. While calling the current class constructor using this, it should be the 1st line in the code block.

Example:

//parent class
class Hostel{
    String address;
    String name;
    
    //parameterized constructor to initialize add and name
    Hostel(String address,String name){
        /*
            using this to point to the Hotel's address and name
            if there is no this, the parameter will assign values to local var and the class var will still have default values.
        */
        this.address=address; 
        this.name=name;         
    }
    
    //parameterized constructor to initialize just name
    Hostel(String name){
        this.name=name;
    }
    
    //method to print address
    void printAddress(){
        System.out.println("address : "+address);
    }
    
}

//child class
class Room extends Hostel{
    int number;
    String name;

    //parameterized constructor to initialize address, name and number
    Room(String address,String name,int number){
        super(name); //calling parent's constructor
        this.address=address;
        this.name=name;
        this.number=number;
    }
    
    //method to print all details of room
    void printRoomDetails(){
        System.out.println("name : "+name);
        super.printAddress();
        System.out.println("room no. : "+number);
    }
}

class Demo {
	public static void main (String[] args) {
	    Room r1=new Room("12th street,NY","CS Block ",43);
	    r1.printRoomDetails();
	}
}

Output:

name : CS Block 
address : 12th street,NY
room no. : 43 

Inheritance in Java

One of the very important pillars of OOPs, it facilitates the reusability of code as a child can inherit from the parent. Child can also implement additional data members or methods of its own. This is a IS-A relationship between child and parent.

Example: We did this in the above example where Room(child) inherits from Hostel(parent).

There are 4 types of inheritance supported by java:

Java doesn’t suppose classic multiple inheritances due to ambiguity that it may cause. But you can have multiple inheritance via interfaces.

Method Overloading in Java

This basically is a compile-time polymorphism. There can be multiple methods with the same name but different parameters list which may differ in types or number of arguments

‘Method’ cannot be overloaded by just changing the return type of methods.It provides an ease to the programmer and helps in the understanding of code

Example:

public class OverloadingDemo {
    
    int multiply(int a,int b){
        return a*b;
    }
    
    //overloaded multiply with 3 parameters
    int multiply(int a,int b,int c){
        return a*b*c;
    }
    
    //overloaded multiply with 2 parameters of different type
    double multiply(int a,double b){
        return a*b;
    }
    
	public static void main (String[] args) {
	    OverloadingDemo ob=new OverloadingDemo();
		System.out.println(ob.multiply(3,5));
		System.out.println(ob.multiply(3,5,3));
		System.out.println(ob.multiply(3,5.5));
	}
}

Output:

15
45
16.5

Method Overriding in Java

This is runtime polymorphism. Here if a child class wants to override parent’s method i.e., wants to give its own implementation then it can do that by having exactly the same signature with its implementation.

Example:

class Parent{
    void hobbies()
    {
        System.out.println("Reading Books");
    }
}

class Child extends Parent{
    
    //same method as of parent but different implementation
    void hobbies()
    {
        System.out.println("Travelling");
    }
}


class OverridingDemo {
	public static void main (String[] args) {
		Child ob=new Child();
		ob.hobbies();
	}
}

Output:

Travelling 

Abstract class in Java

If a method doesn’t have its implementation then it is known as ‘abstract’ method. A class having 1 or more abstract methods is known as an abstract class. It actually implements OOPs abstraction to a certain extent

Abstract keyword is used for declaring abstract class. An abstract class can have abstract and non-abstract methods and it can’t be instantiated.

Rather it has to be extended and abstract methods have to be given their implementation.

Example:

abstract class Keyboard{
    abstract void working();
    void name(){
        System.out.println("This is Keyboard component");
    }
}

class Hp extends Keyboard{
    //implementing abstract method
    void working(){
        System.out.println("This is hp Keyboard");
    }
    
}
public class AbstractClassDemo {
	public static void main (String[] args) {
		Hp ob=new Hp();
		ob.working();
		ob.name();
	}
}

Output:

This is hp Keyboard
This is Keyboard component

Interface in Java

It enforces 100% abstraction. Here all methods are abstract by default and thus it is not necessary to write abstract keyword while declaring them

Example:

interface Toy{
    void start();
    void run();
}

class Car implements Toy{
    public void start(){
        System.out.println("car started");
    }
    
    public void run(){
        System.out.println("car running");
    }
}
class InterfaceDemo {
	public static void main (String[] args) {
		Car ob=new Car();
		ob.start();
		ob.run();
	}
}

Output:

car started
car running

Compiler implicitly adds a public abstract in front of every method of the interface

T:\>javap Toy
Compiled from "GFG.java"
interface Toy{
    public abstract void start();
    public abstract void run();
  • implements keyword is used by the class that wants to use it and has to give a definition for every method
  • While implementing interface methods, specifying public access modifiers is must
  • A class can implement multiple interfaces which enable a sort of multiple inheritances

Exception Handling in Java

An exception is an abnormal condition that may happen at runtime and disturb the normal flow of the program. So we can handle exceptions in order to ensure our code gets executed normally

There are 2 major category of exception 

  • Checked 
    • Those exception that are checked at compile-time comprises of checked exception
    • They are child classes of Exception except RuntimeException
    • Example: IOException, ClassNotFoundException etc.
  • Unchecked
    • Those exception that are checked at runtime comprises of unchecked exception
    • They are child classes of RuntimeException.
    • Example: ArithmeticException, NullPointerException etc.

Basic syntax:

try{

}catch(Exception e){

}
  • There are 5 keywords in Java exception handling:
    • try
    • catch
    • finally
    • throw
    • throws
  • ‘try’ block contains the code that might throw an exception. Don’t write anything extra in try as statements after the exception will not get executed if the exception occurred
  • ‘catch’ block is used to catch the exception thrown by statements in the try block. It must follow try else it will give a compile-time error.

Example:

public class ExceptionDemo {
	public static void main (String[] args) {
		int a=10;
		for(int i=3;i>=0;i--)
		   try{
		     System.out.println(a/i);  
		   }catch(ArithmeticException e){
		       System.out.println(e);
		   }
	}
}

Output:

3
5
10
java.lang.ArithmeticException: / by zero 

There can be multiple catch, which should be placed from child to parent in order to get the desired output. finally block contains code that must be executed no matter if an exception is thrown or not. finally generally contains code of file release, memory cleaning etc.

Exception: 

public class ExceptionDemo {
	static void canVote(int age){
		if(age<18)
            try{
                throw new Exception();
            }catch(Exception e){
                System.out.println("you are not an adult!");
            }
		else
		   System.out.println("you can vote!");
	}
	public static void main (String[] args) {
		canVote(20);
		canVote(10);
	}
}

Output:

5
I am finally

throw keyword is used to explicitly throw an exception which normally doesn’t throw an exception.

Exception:

public class ExceptionDemo {
	static void canVote(int age){
		if(age<18)
            try{
                throw new Exception();
            }catch(Exception e){
                System.out.println("you are not an adult!");
            }
		else
		   System.out.println("you can vote!");
	}
	public static void main (String[] args) {
		canVote(20);
		canVote(10);
	}
}

Output:

you can vote!
you are not an adult!

throws basically say what sort of exception the code can throw and relies on the caller to handle it

Example:

public class ExceptionDemo {
	static void func(int a) throws Exception{
		   System.out.println(10/a);  
	}
	public static void main (String[] args) {
		try{
		    func(10);
		    func(0);
		}catch(Exception e){
		   System.out.println("can't divide by zero");
		}
	
	}
}

Output:

1
can't divide by zero 

String

A string is a sequence of characters. It’s a class in java and there are 2 ways to create a string:

  • String str = “hello”;
  • String str = new String(“hello”);

We have special memory termed as string constant pool inside heap and,

  • In the first way, a copy is created in heap and in SCP too if it was not already there
  • In the second way, copy is created in heap only

String can also be created using char array

  • char[] ch={‘h’,’e’,’l’,’l’,’o’};
  • String str=new String(ch);

String is immutable that means once created it cannot be manipulated

There are three ways to check for equality in String:

  • == : checks for same reference
  • .equals() : checks for same content
  • .compareTo() : compares content lexicographically
    • return +ve num : str1>str2
    • return -ve num : str1<str2
    • return 0 : str1==str2

Example:

public class StringDemo {
	public static void main (String[] args) {
		String s1=new String("cat");
		String s2="cat";
		String s3="cat";
		System.out.println(s1==s2);
		System.out.println(s2==s3);
		System.out.println(s1==s3);
		System.out.println(s1.equals(s3));
		System.out.println(s1.compareTo(s2));
	}
}

Output:

false
true
false
true
0

String has many methods that help in working with strings. Some of them are:

  • length()
  • toUpperCase()
  • toLowerCase()
  • contains()
  • indexOf()
  • substring()
  • split()
  • replace()
public class StringDemo {
	public static void main (String[] args) {
	    String str="Today is monday.";
		System.out.println(str.length());
		System.out.println(str.toLowerCase());
		System.out.println(str.toUpperCase());
		System.out.println(str.contains("is monday"));
		System.out.println(str.indexOf("monday"));
		System.out.println(str.substring(4,8));
		System.out.println(str.replace("monday","tuesday"));
	}
}

Output:

16
today is monday.
TODAY IS MONDAY.
true
9
y is
Today is tuesday.

For mutable String, java does have 2 more classes

  • StringBuilder (non synchronized i.e, not thread-safe)
  • StringBuffer (synchronized i.e, thread-safe)

If you are looking for more such tutorials in other tech domains, check out Great Learning Academy.

0

LEAVE A REPLY

Please enter your comment!
Please enter your name here

nine − seven =