Home Blog

Quick Revision OOPS concepts of java – asked in interview

0
java oops concept quick revision

Hi Guy’s Welcome to Proto Coders Point. This Article is on basic quick revision oops concepts of java that can be asked in interview.

Object Oriented Programming System(OOPs)

If we take real world example, a Object are pen, table, personal computer… etc. In JAVA Programming OOPs is a methodology used to design programs using classes & objects. By using object oriented we can make software development simple. Here are the OOPS Concepts:

Quickly Revise OOPS Concepts

  1. Object.
  2. Class.
  3. Inheritance.
  4. Encapsulation.
  5. Abstraction.
  6. Polymorphism.
java oops concepts quick revision

Here inheritance, encapsulation, abstraction, & polymorphism are called as four pillars of JAVA Programming language.

1. Object

Any real world entity is an Object. It has Behavior and Attribute. Here:

Behavior can be defined as what an object does and what is can perform.

Attribute is used to describe a Object.

Here is a small example:

Chair: In Real word a chair is an object, which has behaviour feature like wheem movement, Height and recline adjectment. and chair’s attribute like it’s color, number of wheels, max height adjuctment, price etc.


2. Class

The collection of all related object is called as class, Consider general category as a class, which contains related objects within it.

Example: Chair

Object like Office Chair, Wheel chair, recliner chair, gaming chai etc all this below to one class that is Chair class.


3. Inheritance

To Understand Inheritance concept in java, let’s take real world eg: In child aquire the qualities from his/her parent. Similarly, a Child class can also inherit feature from it’s parent class.

Basically Inheritance is a machanism by which one class (child) can aquire all the properties/features of another class(parent).

Example: Phone

Parent class Phone can have two child classes -:

  • TelePhone
  • MobilePhone

Both of this child classes has inherited a calling feature behaviour.


4. Encapsulation

In Java Encapsulation means wrapping up of data into a single unit & securing it, By encapsulation process data will get secured from outside words.

Example:

Bank Locker: You create a bank locker where you keep all your valuable thinks lets say the locker as (single unit) and then you protect the locker using a key or digital passcode.

Medicine Capsules: It has a wraps from outside and all the medicine ingredient is wraps into that capsules for protecting it from outsite atmosphere.


5. Abstraction

The Inside working machanism is been hidden from the user, and the user can only be able to user those feature, which him/her know how the machanism actual works.

This helps the user to be focus on product usage.

Eg:

Car: A Car, is full of complexity machanism like engine, gear box. User no need to know in depth about this. Only the relevent part is shown like brakes, accelerator, gear’s how to use it.


6. Polymorphism

The word polymorphism means many forms, The meaning of polymorphism means same name can we used for different behavious.

Eg: Chess: All chess pieces like king, bishop, knight, rook … etc move in different directions, Bishop moves diagnallym Rooks move horizontal and verticle etc.

The common behaviour in chess game is “move”, but the different over here is direction.


Conclusion

This article is basic revise of Java OOPS Concepts, We can use OOP Concepts to map any real-world solutions into programming very easily.

That’s why OOP concept is designed close to real world.

A Better understanding of these concepts is going to decide how good programmers we will become in future. Have a look at Dart programming OOPS Concepts

Upload CSV file into Azure SQL Database – Import csv to sql server

0
Import csv to Azure SQL Database

Hi Guy’s Welcome to Proto Coders Point, In this Tutorials we will learn about the Microsoft Azure Database and How to import data from csv file to sql database

Requirements: –

  1. IDE or Notebook
  2. Database Credential
  3. JDBC Connection

1) IDE or Notebook

          It is web interface that contain runnable commands, visualizations, We create notebook using some default languages i.e. Python, SQL, Scala, R, Pyspark.

2) Database Credentials: –

          We need to make sure that all Database Credentials are required to connect with the Database i.e. Server Name, Database Name, ID, Password.

 3) JDBC Connection: –

          Connection is used to load the driver and help to establish connect with the Data Source.

4) CSV FILE:-

Comma-Separated Value is a text file which data is available in spreadsheet format.


Creating SQL Database on Azure Cloud

First of all, We Need to Create a SQL Database on Azure. We have shared some step that help you to create SQL Database.

  • Go to Search Tab in Azure.
  • Search for ‘SQL Database’ & click on It.
  • Click on ‘Create’.
    • Add project Details
      • Subscription
      • Resource Group
    • Database Details
      • Database Name (Add Database Name)
      • Server Name (Choose Same Region that are already defined in SQL Server)
      • Workload Environment – Choose development OR Production Environment
      • Compute + Storage –
    • Backup Storage Redundancy
      • Choose Locally OR Geo Storage Redundancy
  • Add extra content if you want like security, Networking otherwise keeps them Default Only.
  • Click on ‘Review + Create’.

Connect databricks to sql server using python code

After creating a Database in Azure we will try to connect to Database Using Data bricks: –

While accessing a Database azure we have certain ways to connect like CLI, Programming, SQL Server Management Studio.

We are going to use Python Programming for accessing Database with JDBC Connection (databricks connect to sql server python).

Step 1:- First will connect with the SQL Database by using JDBC Port:

from pyspark.sql import *
import pandas as pd

jdbchost_name = "firstserver31.database.windows.net" //Server Name 
jdbcPort = "1433"
jdbcDatabase = "task1" //Database Name
properties = {
    "user" : " ",
    "password" : " "
}
url = "jdbc:sqlserver://{0}:{1};database={2}".format(jdbchost_name, jdbcPort, jdbcDatabase)

Step 2:- After connecting with the Database we will read a CSV file

file_df = sqlContext.read.csv("/FileStore/tables/emp/employees.csv", header = True)
file_df.show(5)

Step 3:- Write CSV File into the Database.

filedf1 = DataFrameWriter(file_df)
filedf1.jdbc(url=url, table="employee1", mode="overwrite", properties=properties)
print("Successfully added Into Database")

#Output :-

imported csv to sql using python

In Next Tutorial we will come with the Simple ETL Process by Using the Same Technologies.

How to create Reorderable Listview in flutter

0
Flutter reorderable list view with example
Flutter reorderable list view with example

Hi Guy’s Welcome to Proto Coders Point. In this Flutter tutorial let’s learn how to implement Reorderable listview in flutter app.

What is Reorderable Listview in flutter

Basically a reorderable listview looks similar to listview, the only difference over here is that the user can interact with listview by long press on list item drag & drop to reorder the listview item as per user needs.

Example: Can be used this in developing a simple ToDo application in flutter where a user can reorder his todo list and keep priority task on top.

Video Tutorial

Flutter ReorderableListView Widget & it’s Syntax

In flutter we have a widget i.e. ReorderableListview, It has 2 main properties to be passed (children & onReorder).
and alternatively we have ReorderableListView.builder, It has 3 mandatory properties (itemBuilder, ItemCount, OnReorder). Example below.

Syntax of ReorderableListview

ReorderableListView(
        children: [
              // listview items
        ],
        onReorder: (int oldIndex, int newIndex){
              // list items reordering logic
        },
      )

Syntax of ReorderableListView.builder(….)

ReorderableListView.builder(
          itemBuilder: itemBuilder,    // widget to show in listview Eg: ListTile
          itemCount: itemCount, // number of item to generate in listview
        onReorder: (int oldIndex, int newIndex){
          // list items reordering logic
        },
  )

Reorderable ListView in Flutter – Complete Source Code

Initialize Dummy List by using list generator

 final List<int> _itemList = List<int>.generate(60, (index) => index);

Example 1 – With Video Tutorial

ReorderableListView(
        onReorder: (int oldIndex, int newIndex) {
          setState(() {
            if(newIndex > oldIndex){
              newIndex -=1;
            }
            final int temp = _itemList[oldIndex];
            _itemList.removeAt(oldIndex);
            _itemList.insert(newIndex, temp);
          });
        },
        children: [
          for(int index = 0;index<_itemList.length;index++)
            ListTile(
              key:Key('$index'),
              title: Text('Item ${_itemList[index]}'),
            )
        ],
   ),

Example 2 – With Video Tutorial

ReorderableListView.builder(
          itemBuilder: (BuildContext context,int index){
            return Card(
              key: Key('${index}'),
              child: ListTile(

                title: Text('Item ${_itemList[index]}'),
              ),
            );
          },
          itemCount: _itemList.length,
          onReorder: (int oldIndex,int newIndex){
              setState(() {
                if(newIndex > oldIndex){
                  newIndex -=1;
                }
                final int tmp = _itemList[oldIndex];
                _itemList.removeAt(oldIndex);
                _itemList.insert(newIndex, tmp);
              });
      })

Example 3 – Make API Http call request & create a Reorderable Listview – Complete Code

Demo

reorderable listview flutter
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
 
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  
  var jsonList;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getData();
  }

  void getData() async{

    http.Response response = await http.get(Uri.parse("https://protocoderspoint.com/jsondata/superheros.json"));
    if(response.statusCode == 200){
       setState(() {
           var newData = json.decode(response.body);
           jsonList = newData['superheros'] as List;
       });
    }else{
      print(response.statusCode);
    }
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Flutter Reorderable Listview"),
      ),
      body: ReorderableListView.builder(
          itemBuilder: (BuildContext context,int index){
            return Card(
              key: Key('${index}'),
              child: ListTile(
                leading: ClipRRect(
                  borderRadius: BorderRadius.circular(80),
                    child: Image.network(
                        jsonList[index]['url'],
                      fit: BoxFit.fill,
                      width: 50,
                      height: 100,
                    )
                ),
                title: Text(jsonList[index]['name']),
                subtitle: Text(jsonList[index]['power'],maxLines: 4,),
              ),
            );
          },
          itemCount: jsonList == null ? 0 : jsonList.length,
          onReorder: (int oldIndex,int newIndex){
            setState(() {
              if(newIndex > oldIndex){
                newIndex -=1;
              }
              final tmp = jsonList[oldIndex];
              jsonList.removeAt(oldIndex);
              jsonList.insert(newIndex, tmp);
            });
          })
    );
  }
}

Flutter make Get/Post request using GetX Package

0
Flutter GETPOST request using GETX Library

Hi Guys, Welcome to Proto Coders Point, In this flutter Article let’s learn How to make Get/Post request in flutter app by using GetX package GetConnect() class.

What is GetX in Flutter

In Flutter GetX is an multi functiional powerful library which is open source to use in flutter app.

GetX provides massive high performance in teams of state management in flutter, route management, dependencies injection & basic functionalities such as showing snackbar, dialog Box popup, getStorage for storing data as mini database, Internationalization & much more can be used by just adding one line of code.

Although flutter getx has multiple feature in it, Here GetX library is built in such a way that each feature has it’s separate container & thus only the used once in your flutter app is been compiled.

Therefore, Getx library is very light weight as it does not increase app size much.

GET/POST request in flutter

In flutter app, we can make internet calls i.e GET/POST request by using GETX GetConnect class, you will be suprised by the lines of code your need to write to make Get/Post request.

Step to make GET/POST request using GETX Flutter library

1. Install GetX Dependencies

In your flutter project to use GetX you need to install it , Run below commond in IDE terminal

flutter pub add get

2. Import get.dart

Now, Once getx package is added as dependenies library, to use it, import where require Eg: main.dart

import 'package:get/get.dart';

3. Create Instance of GetConnect Class

Now, you need an instance of GetConnect() class. Let’s create it.

 final _getConnect = GetConnect();

now, use this GetConnect instance to make GET/POST requests.


4. A Function that makes GET Request

 void _sendGetRequest() async {
    final response =
    await _getConnect.get('API URL Here');

    if (kDebugMode) {
      print(response.body);
    }
  }

5. A Function That makes POST request

 void _sendPostRequest() async {
    final response = await _getConnect.post(
      'http://192.168.29.167:3000/register',  // rest api url
      {
        'username': 'rajat123@gmail.com',
        'password': '554433#221100',
      },
    );

    if (kDebugMode) {
      print(response.body);
    }
  }

Flutter Get/Post Request – Complete Example

I have created a backend NodeJS API, Which simply stores the data in Mongodb database when API Router is been triggered from frontend.

In this Article our frontend is flutter app, which has 2 TextField (username & password) and a Button (basic registration form), when button clicked, data entered in TextField is been sent through POST method of Flutter GetX library to backend NodeJS server which while store the entered data into MongoDB database.

api call using getx flutter

Nodejs Backend create user store user data in database
Nodejs Backend create user store user data in database

Get NodeJS Backend code from my github repository


MongoDB data stored screenshot

nodejs api stored data in mongodb database
nodejs api stored data in mongodb database

Flutter App Complete Source Code

main.dart

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(

        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  final _getConnect = GetConnect();
  final TextEditingController emailText = TextEditingController();
  final TextEditingController passwordText = TextEditingController();

  // send Post request
  void _sendPostRequest(String email,String password) async {
    final response = await _getConnect.post(
      'http://192.168.29.167:3000/register',
      {
        'username': email,
        'password': password,
      },
    );
    if (kDebugMode) {
      print(response.body);
    }
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Padding(
          padding: EdgeInsets.all(30),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              TextField(
                controller: emailText,
                decoration: InputDecoration(
                  border: OutlineInputBorder(),
                  labelText: "Enter Email Or Username",

                ),
              ),
              SizedBox(height: 5,),
              TextField(
                controller: passwordText,
                decoration: InputDecoration(
                  border: OutlineInputBorder(),
                  labelText: "Enter Password",

                ),
              ),
              ElevatedButton(
                  onPressed: ()=>_sendPostRequest(emailText.text,passwordText.text),
                  child: const Text('Register')),
            ],
          ),
        ),
      ),
    );
  }
}

What’s new in Flutter 3.3

0
What's New in Flutter 3.3
Flutter 3.3

Hi Guy’s Welcome to Proto Coders Point. Flutter have recently announced it thrilled & amazing flutter 3.3 which focuses on refinement of recent release i.e flutter 3.

Flutter 3.3 new features

1. Selectable Text in flutter

Till now Flutter did not support text selection to copy the content shown in app, Flutter Web App running on browser user were not able to copy the text from widgets.

Now with flutter 3.3, They have introduced a new widget i.e. SelectableArea, when used flutter user will be able to select on both mobile & web app.

Example:

Flutter Selectable Text Widget example

Learn more on Flutter selectableText widget.


2. Trackpad Input

Flutter 3.3 now support for trackpad input. This not only support smoother & richer control, but also reduces misinterpretation in certain situation.

For Example: check out Drag a UI element page in the Flutter cookbook, Scroll to bottom of page to get dartpad instance and perform the following steps:

  • Size window smaller so the the upper part present a scrollbar at side.
  • now, hover over the upper part.
  • use a trackpad to scroll.
  • before you have install 3.3 flutter sdk, scrolling on the trackpad drags the item because flutter was dispatching general events.
  • Now, do the same thing after installing flutter 3.3, scrolling on a trackpad correctly scrolls the list because flutter is scrolling gesture, which isn’t recognized by the cards but is recogized by the scroll view.

3. Flutter Scribble

Flutter now came up with an amazing feature i.e. Scribble handwritting text input, Instead of using keyboard to type text into the textfield, If you have a stylus pen, simple use stylus on TextField, flutter will automatically read the freehand drawing from textField & convert it into text.

flutter scribble textfield

4. Text Input

From platform TextInputPlugin, They release an ability to ceceive granular text updates, Previously TExtInputClient only delivered the new editing stat which no delta between the old and newm TextEditingDeltas and the deltaTextInputClient fill the information gap.

Having access to there eltas allows you to build an input field with styled ranges that expands and contract as you type.

Learn more Check out Rich Text Editor Demo

5. Flutter Material Design 3

Flutter team continues to add more and more material design componets in flutter, with flutter3.3 update they have added Material Design 3. This update includes IconButton, Flutter Chips, different variants to add appbar in flutter

6. Flutter IconButton

In Material Design, We have IconButton been added, This are picture printed on Material Widget that react to touches by filling with color,

Commonly Icon Button are very useful in Appbar actions field, and can even be used in many places as well.

flutter icon button

What is GraphQL? Will it replace RESTAPIs

0
What is GraphQL Will it Replace RESTFUL API

What is GraphQL?

Basically GraphQL is a Query language used to develop API’s, GraphQL is been developed by Meta(Facebook). It gives power to client to ask for any data as per client need, it provides ful described data in the API.

Usually GraphQL servers works as a middleware, it sits between client side and backend services to communicate data within.

It can aggregate multiple RESTfull API request into a single Query.

It also support various queries like, mutations(used for data modification before sending to front end client) and subsriptiions(schema modification on receiving notifications).

Different between RESTAPI and GraphQL

REST APIGraphQL
Architectureserver-drivenclient-driven
Organized in terms ofEnd PointSchema & type System
OperationsCRUD OperationQuery mutation Subscription
Data fetchingFixed data with multiple api callsSingle API call
PerformanceMultiple network calls will increase response timeFaster
Development speedMediumSuper Faster
Learning curveEasily to LearnDifficult to learn
Self – documentingNoYes
File UploadingSupportedNot Supported
Web CachingYesNo, caches. but using libraries we can.
Stabilitybetter choise for complex queriesless error prone, automatic validation
Use CasesSimple App’s monolithic architectureBest for microservices application, Mobile Applications

How GraphQL Query request

Will graphQL replace restful api

As you all hearing a lot boom about the popularity gain of GraphQL and it ability in building efficient, powerful & flexible API’s as compared with REST.

REST is a one among famous API development technology but after launch of GraphQL in 2015 by FACEBOOK(META), It got boom in market and many API developer are trying to get upgraded in this GraphQL.

Pros and Cons of RestAPIs and GraphQL

RestAPI’s

proscons
Supports different data formats (Html, JSON, etc.)An annoying and confusing pagination system
Resources efficiencyDifficulty to get issues general information
Better scalability

GraphQL

proscons
Eliminates over-fetching & under-fetching.Lacks built-in caching.
Provides consistent, uniform dataComplicated error handling.
Speeds up the development processLacks industry adoption & support.

Best To Buy from Amazon