java Basics

 Input Output in Java

import java.util.Scanner; // Import the Scanner class

class Main {

  public static void main(String[] args) {

    Scanner myObj = new Scanner(System.in);


    System.out.println("Enter name, age and salary:");


    // String input

    String name = myObj.nextLine();


    // Numerical input

    int age = myObj.nextInt();

    double salary = myObj.nextDouble();


    // Output input by user

    System.out.println("Name: " + name); 

    System.out.println("Age: " + age); 

    System.out.println("Salary: " + salary); 

}

}


Method Description

nextBoolean() Reads a boolean value from the user

nextByte() Reads a byte value from the user

nextDouble() Reads a double value from the user

nextFloat() Reads a float value from the user

nextInt() Reads a int value from the user

nextLine() Reads a String value from the user

nextLong() Reads a long value from the user

nextShort() Reads a short value from the user


When we don't know number of input

// Check if an int value is available

        while (sc.hasNextInt())

        {

            // Read an int value

            int num = sc.nextInt();

            sum += num;

            count++;

        }


if else 

if (time < 18) {

  System.out.println("Good day.");

} else {

  System.out.println("Good evening.");

}

 

Switch

switch(expression) { case x: // code block break; case y: // code block break; default: // code block }


While loop

int i = 0; while (i < 5) { System.out.println(i); i++; }



Do-While loop

int i = 0; do { System.out.println(i); i++; } while (i < 5);


Break

for (int i = 0; i < 10; i++) { if (i == 4) { break; } System.out.println(i); }

Continue

for (int i = 0; i < 10; i++) { if (i == 4) { continue; } System.out.println(i); }


Array

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; for (int i = 0; i < cars.length; i++) { System.out.println(cars[i]); }

2nd Way Array (When value don't know)

int intArray[]; //declaring array intArray = new int[20]; // allocating memory to array OR int[] intArray = new int[20]; // combining both statements in one

note-The elements in the array allocated by new will automatically be
initialized to zero (for numeric types), false (for boolean), or null
(for reference types).


for - each loop

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; for (String i : cars) { System.out.println(i); }


Class in Java

class Student
{
    public int roll_no;
    public String name;
    Student(int roll_no, String name)
    {
        this.roll_no = roll_no;
        this.name = name;
    }
}


Multidimensional Array

int[][] intArray = new int[10][20]; //a 2D array or matrix int[][][] intArray = new int[10][20][10]; //a 3D array


Passing Array in Function

class Main { // Driver method public static void main(String args[]) { int arr[] = {3, 1, 2, 5, 4}; // passing array to method m1 avg(arr); } public static void avg(int[] arr) { // getting sum of array values int av = 0; for (int i = 0; i < arr.length; i++) av+=arr[i]; System.out.println("sum of array values : " + av/arr.length); } }



Returning Arrays from Methods

class Test { // Driver method public static void main(String args[]) { int arr[] = m1(); for (int i = 0; i < arr.length; i++) System.out.print(arr[i]+" "); } public static int[] m1() { // returning array return new int[]{1,2,3}; } }


Cloning of array(Deep Copy)

class Test { public static void main(String args[]) { int intArray[] = {1,2,3}; int cloneArray[] = intArray.clone(); // will print false as deep copy is created // for one-dimensional array System.out.println(intArray == cloneArray); for (int i = 0; i < cloneArray.length; i++) { System.out.print(cloneArray[i]+" "); } } }

Output:

false
1 2 3





Inbuilt List


// Java program to demonstrate a List

import java.util.*;

public class ListDemo {
public static void main(String[] args)
{
// Creating a list
List<Integer> l1
= new ArrayList<Integer>();

// Adds 1 at 0 index
l1.add(0, 1);

// Adds 2 at 1 index
l1.add(1, 2);
System.out.println(l1);

// Creating another list
List<Integer> l2
= new ArrayList<Integer>();

l2.add(1);
l2.add(2);
l2.add(3);

// Will add list l2 from 1 index
l1.addAll(1, l2);
System.out.println(l1);

// Removes element from index 1
l1.remove(1);
System.out.println(l1);

// Prints element at index 3
System.out.println(l1.get(3));

// Replace 0th element with 5
l1.set(0, 5);
System.out.println(l1);
                 //Sorting the list

                //Creating a list of fruits  
              List<String> list1=new ArrayList<String>();  
              list1.add("Mango");  
              list1.add("Apple");  
              list1.add("Banana");  
              list1.add("Grapes");  
              //Sorting the list  
              Collections.sort(list1);  

                // Remove via object
               list1.remove("Banana");
  
            System.out.println("After the Object Removal " + list1);

            // Iterating the list
                // for loop
            for (int i = 0; i < list1.size(); i++) {
  
            System.out.print(list1.get(i) + " ");
            }
  
            System.out.println();
  
            // Using the for each loop
            for (String str : list1)
                System.out.print(str + " ");
            
         
}
}

Output
[1, 2]
[1, 1, 2, 3, 2]
[1, 2, 3, 2]
2
[5, 2, 3, 2]
[2, 2, 3, 5]

[Apple, Banana, Grapes, Mango]

After the Object Removal [Apple, Grapes, Mango]

Apple Grapes Mango 
Apple Grapes Mango


String

String Literal
String Literal memory Allocates in String constant pool
String str = "Geeks";

Create String using new operator
String str = new String("Geeks");
If you want to store this string in the constant pool then you will need to “intern” it.

For example:

String internedString = str.intern(); 
// this will add the string to string constant pool.

public class StringExample{  
public static void main(String args[]){  
String s1="java";//creating string by java string literal  
char ch[]={'s','t','r','i','n','g','s'};  
String s2=new String(ch);//converting char array to string  
String s3=new String("example");//creating java string by new keyword  
System.out.println(s1);  
System.out.println(s2);  
System.out.println(s3);  

String str="python";  
System.out.println("string length is: "+str.length());  


}}  
}}

Output
java
strings 
example 
string length is: 6



StringBuffer
StringBuffer s = new StringBuffer("GeeksforGeeks");

StringBuilder
StringBuilder str = new StringBuilder();
str.append("GFG");


int to Integer conversion

public class IntToInteger{
 
  public static void main(String[] args) {
    int i = 78;
    
    
    Integer obj = new Integer(i);
    System.out.println(obj);
    
  }
}

output= 78

Integer to int conversion

import java.lang.*;

public class IntgerToInt {

public static void main(String[] args)
{

Integer posobject = new Integer(88);

// Returns the value of this Integer as an int
int i = posobject.intValue();
System.out.println("The integer Value of i = " + i);

                Integer negobject = new Integer(-89);
  
               // Returns the value of this Integer as an int
                int i2= negobject.intValue();
                 System.out.println("The integer Value of i2 = " + i2);

}
}


output= The integer Value of i = 88

The integer Value of i = -89


Inheritance

Inheritance is used to achieve runtime polymorphism.


Polymorphism
If one task is performed in different ways, it is known as polymorphism. 


Static Block and Static method
 First, JVM executes the static block, then it executes static methods, and then it creates the object needed by the program. Finally, it executes the instance methods. 
 
class  Demo  
{  
static                  //static block  
{  
System.out.println("Static block");  
}  
public static void main(String args[])  //static method  
{  
System.out.println("Static method");  
}  
 
Output:

Static block
Static method


A program that does not have the main() method gives an error at run time.

class DemoStaticBlock  
{  
Static                                  //static block  
{  
System.out.println("Static block");  
}  
}     
Output:

Error: Main method not found in the class Demo, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application



Method Overriding-
Static method can not override because It is related to class and gets memory to class area.


Access modifiers
Class can not private or protected instead of nested class.

If you are overriding any method, overridden method (i.e. declared in subclass) must not be more restrictive.



Calling order
Parent Class constrctor ->Instance Intializer Block ->constructor -> Method



Final-
If final Variable is not Intialize then it is known as blank final variable. It is intialise only in constructor.
If static final Variable is not Intialize then it is known as static blank final variable. It
 is intialise only in static block.

Final class can not extended (Hence Inheritance does not apply in final class).

final parameter can not change its value.



Upcasting-
If the reference variable of Parent class refers to the object of Child class, it is known as upcasting.


Compile Time Polymorphism-
Overloading of static method

Runtime Poly-
Reference of parent class point child class object calls overidden method of child class is decide at run time.
Runtime polymorphism can't be achieved by data members. 



Binding-
Connecting a method call to the method body is known as binding.

Static Binding -
Type of object determined at comile time
If there is any private, final or static method in a class, there is static binding.

Dynamic Binding -
Type of object determined at run time


Object have a type
An object is an instance of particular java class,but it is also an instance of its superclass.



Comments