Friday 26 June 2015

for each loop in java


What is for each loop?
for each loop in java is the enhanced version of for loop. It is introduced from JDK 5. It is used to iterate all elements of an array or Collection.

Syntax:

for ( data-type variableName :  array or collection )
{
    //statements
}

Consider the following program:

public class ForEachLoop
{
    public static void main(String[] args)
    {
        int[] array ={ 1, 2, 3, 4, 5 };
        System.out.println("Array elements: ");

        for(int element: array)
               System.out.print(element+"  ");

    }
}


Write the above program in Notepad and save it as ForEachLoop.java 
Compile and run it to get the following output:

Array elements: 
1  2  3  4  5

the loop for(int element: array)
fetches the elements of array and assign it to variable element so we can use element to access the elements of array

Consider the following program to access elements of multi-dimensional array


public class ForEachLoop
{
    public static void main(String[] args)
    {
     int[][] array ={ {1, 2, 3, 4,},{ 5,6,7,8} }; //array with 2 rows and 4 columns
        System.out.println("Array elements: ");
        for(int[] row: array)
            for(int element: row)
               System.out.print(element+"  ");
    }
}

Write the above program in Notepad and save it as ForEachLoop.java 
Compile and run it to get the following output:

Array elements: 
1  2  3  4  5  6  7  8

the loop for(int[ ] row: array)
fetches one row of array and assign it to variable row so we can use row to access one row(or one dimensional array) of array

the loop for(int element: row)
fetches the elements of row and assign it to variable element so we can use element to access the elements of row

Command Line Arguments



public class CommandLineArguments
{
    public static void main(String[] args)
    {
        System.out.println("Total number of Command Line Arguments: "+args.length);
        System.out.println("Command Line Arguments:");
        for(int i=0;i<args.length;i++)
            System.out.println(args[i]);
    }
}

Type the above program in Notepad and Save it as CommandLineArguments.java
Compile like this:

javac  CommandLineArguments.java

Run like this:

java  CommandLineArguments   Arguments

For example: 

java  CommandLineArguments   Hello World
output:

Total number of Command Line Arguments: 2
Command Line Arguments:
Hello
World



If you run like this:
java  CommandLineArguments
output:

Total number of Command Line Arguments: 0
Command Line Arguments:



Note: Each argument in command line arguments is seperated by a space

Learn Java Part 10

Wednesday 17 June 2015

Program to reverse each word of a given string



//Program to reverse each word of a given string

import java.io.*;  //for IOException, BufferedReader, InputStreamReader
import java.util.*;  //for StringBuffer
public class WordReverse {
    public static void main(String[] args)throws IOException
    {
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Enter the string:");
    String str=br.readLine();
    StringTokenizer st=new StringTokenizer(str);
    String temp="";
    while(st.hasMoreTokens())
    {
        temp=temp+new StringBuffer(st.nextToken()).reverse().toString()+" ";
    }
        System.out.println("Reversed String is:");
        System.out.println(temp);
    }   
}



Output:

Enter the string:
Hello this is GsbProgramming
Reversed String is:
olleH siht si gnimmargorPbsG 

Sunday 14 June 2015

Program to calculate how many times a word occurs in a given string in just one line



//Program to calculate how many times a word occurs in a given string in just one line

import java.io.*;  //for IOException, BufferedReader, InputStreamReader
class CountWord
{
  public static void main(String args[]) throws IOException
  {
     System.out.println("Enter the string: ");
     BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
     String s=br.readLine();  //Gets a string from user
     System.out.println("Enter the word to search for: ");
     String word=br.readLine();  //Gets a string from user

     int count=(s.length()-s.replace(word+"", "").length())/word.length();     

   System.out.println(word+" occurs in given string for: "+count+" times");
  }
}

How to get an alert when anyone logs into your Facebook account from a new device or browser?


Follow these steps:


  • Log In into your Facebook account and goto Settings.
  • Then Jump to “Security Settings” Tab and You can see a Login “Login Alerts” and Click on “Edit”.
  • Check the Get notifications
  • If you want to receive emails alerts then check it
  • If you want to receive text messages alerts then check it
  • Click Save Changes and enter your current password and click Submit



  • Your changes will be saved and now will get an alert when anyone logs into your Facebook account from a new device or browser

Learn Java Part 7

Saturday 13 June 2015

Program to calculate how many times a word occurs in a given string



//Program to calculate how many times a word occurs in a given string

import java.io.*;  //for IOException, BufferedReader, InputStreamReader
class CountWord
{
  public static void main(String args[]) throws IOException
  {
     System.out.println("Enter the string: ");
     BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
     String s=br.readLine();  //Gets a string from user
     System.out.println("Enter the word to search for: ");
     String word=br.readLine();  //Gets a string from user

     int count=0,pos=0;
     while(true)
     {
        pos=s.indexOf(word,pos);
        if(pos==-1)
            break;
        else
        {
            count++;
            pos++;
        }
      }

   System.out.println(word+" occurs in given string for: "+count+" times");
  }
}


Program to calculate the frequency of each character in given String

//Program to calculate the frequency of each character in given String

import java.io.*; //for IOExecption, BufferedReader, InputStreamReader
class CharacterFrequency
{
  public static void main(String args[]) throws IOException
  {
     System.out.println("Enter the string: ");
     BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
     String s=br.readLine(); //gets a string from user
     String temp=s;
     System.out.println("\nFollowing are the characters in string");
    
     while(temp.length()!=0)
     {
        char ch=temp.charAt(0);
        int count=0;
        for(int i=0;i<temp.length();i++)
          if(temp.charAt(i)==ch)
            count++;
        System.out.println(ch+": "+count);
   temp=temp.replace(ch+"","");  //replaces the current character with empty string
     }
  }
}

Friday 12 June 2015

How to make a div scroll-able?


To make div horizontally scroll-able add overflow-x:scroll style to div as:

<div style="overflow-x: scroll; width: 300px;">
In HTML, span and div elements are used to define parts of a document so that they are identifiable when no other HTML element is suitable.
<div>


To make div vertically scroll-able add overflow-y:scroll style to div as:

<div style="overflow-y: scroll; height: 300px;">
In HTML, 
span and div elements are used 
to define parts of a document 
so that they are identifiable 
when no other HTML element is suitable. 
<div>

To make div  scroll-able both horizontally & vertically then  add overflow:scroll style to div as:

<div style="overflow: scroll; height: 300px; width:400px;">
In HTML, 
span and div elements are used 
to define parts of a document 
so that they are identifiable 
when no other HTML element is suitable. 
<div>

Saturday 6 June 2015

Naming, Compiling and Running Java Files Containing More Than One Class Definitions



Today we will see how to name, compile and running java files containing more than one class definitions.

1). Consider the following program.













class ClassOne
{
     public static void main(String[] args)
     {
         ClassTwo.methodOfClassTwo();
     }
}
class ClassTwo
{
     static void methodOfClassTwo()
     {
         System.out.println("From Class Two");
     }
}

Naming : You can save this program with any name. It can be ClassOne.java or it can be ClassTwo.java or it can be anything.java.

Compile : You have to compile this program with the name you have given like >javac ClassOne.java or >javac ClassTwo.java or >javac anything.java.
When you compile a java file, the number of .class files generated will be equal to number of class definitions in it. i.e If a java file has one class definition, one .class file will be generated. If it has two class definitions, two .class file will be generated and so on.
Running : That means for the above program, two .class files will be generated. Then which one to run? is it >java ClassOne or is it >java ClassTwo…..    It must be >java ClassOne, because execution of any java program start with main() method. If you try to run >java ClassTwo, you will get an error: Main method not found in class ClassTwo, please define the main method as public static void main(String[] args).

2). Now consider same example with litte modification, just declare ClassOne as public.















public class ClassOne
{
     public static void main(String[] args)
     {
          ClassTwo.methodOfClassTwo();
     }
}
class ClassTwo
{
     static void methodOfClassTwo()
     {
          System.out.println("From Class Two");
     }
}
Naming : The name of above java file must be and only “ClassOne.java”. You can’t give any other name. If you give any other name you will get compile time error : class ClassOne is public, should be declared in a file named ClassOne.java.
Compile : Only one name is allowed here so you have to compile with that name i.e >javac ClassOne.java.
Running : That must be >java ClassOne. because this is only class that has main() method.


3). Now make little more modifications to the program. Declare ClassTwo as public and ClassOne as default.

class ClassOne
{
     public static void main(String[] args)
     {
          ClassTwo.methodOfClassTwo();
     }
}
public class ClassTwo
{
     static void methodOfClassTwo()
     {
          System.out.println("From Class Two");
     }
}

Naming : You have to save this file with name as “ClassTwo.java”. If you give any other name you will get compile time error becuase ClassTwo is public.
Compile : It must be >javac ClassTwo.java.
Running : You must name this program as ClassTwo.java, you must compile this program as >javac ClassTwo.java but you have to run it as >java ClassOne not as >java ClassTwo. Because only ClassOne has main() method. ClassTwo doesn’t have main() method. If you run it as >java ClassTwo, you will get run time errorMain method not found in class ClassTwo, please define the main method as public static void main(String[] args).

4). Now make little more modifications to the program. Declare both the classes as public.














public class ClassOne
{
     public static void main(String[] args)
     {
          ClassTwo.methodOfClassTwo();
     }
}
public class ClassTwo
{
     static void methodOfClassTwo()
     {
          System.out.println("From Class Two");
     }
}

Naming : Whatever you give the name, whether it is ClassOne.java or ClassTwo.java or anything.java,  you will get compile time error. Because One java file should contain only one or zero public class. It should not contain more than one public class.

5) Look at the following program.















class ClassOne
{
     public static void main(String[] args)
     {
          System.out.println("From Class One");
     }
}
class ClassTwo
{
     public static void main(String[] args)
     {
          System.out.println("From Class Two");
     }
}
Naming : You can save this program with any name. It can be ClassOne.java or it can be ClassTwo.java or it can be anything.java as there is no public class.

Compile : You have to compile this program with the name you have given i.e >javac ClassOne.java or >javac ClassTwo.java or >javac anything.java.
Running : Notice that both the classes have main() method. You can run both the classes with their name. i.e  If you trigger >java ClassOne, you will get From Class One as output. If you trigger >java ClassTwo, you will get From Class Two as output.

Learn Java Part 2

Types of SQL keys

We have following types of keys in SQL which are used to fetch records from tables and to make relationship among tables or views.
  1. Super Key

    Super key is a set of one or more than one keys that can be used to identify a record uniquely in a table.Example :Primary key, Unique key, Alternate key are subset of Super Keys.
  2. Candidate Key

    A Candidate Key is a set of one or more fields/columns that can identify a record uniquely in a table. There can be multiple Candidate Keys in one table. Each Candidate Key can work as Primary Key.
  3. Primary Key

    Primary key is a set of one or more fields/columns of a table that uniquely identify a record in database table. It can not accept null, duplicate values. Only one Candidate Key can be Primary Key.
  4. Alternate key

    A Alternate key is a key that can be work as a primary key. Basically it is a candidate key that currently is not primary key.
  5. Composite/Compound Key

    Composite Key is a combination of more than one fields/columns of a table. It can be a Candidate key, Primary key.
  6. Unique Key

    Uniquekey is a set of one or more fields/columns of a table that uniquely identify a record in database table. It is like Primary key but it can accept only one null value and it can not have duplicate values.
  7. Foreign Key

    Foreign Key is a field in database table that is Primary key in another table. It can accept multiple null, duplicate values.

What is functional dependency?

A functional dependencies is denoted by X--->Y  between two sets of attributes X and Y that are subsets of R. This means that the value of X component of a tuple uniquely determines the value of component Y

What is normalization?

It is a process of analysing the given relation schemas based on their Functional Dependencies(FDs) and primary key to achieve the properties:
  • Minimizing redundancy.
  • Minimizing insertion, deletion and update anomalies.

What is SDL(Storage Definition Language)?

This language is to specify the internal schema. This language may specify the mapping between two schemas

What is VDL(View Definition Language)?

It specifies user views and their mappings to the conceptual schema.

Integrity rules

In SQL we have two integrity rules:
  • Entity Integrity- states that PRIMARY KEY cannot have NULL values.
  • Referential Inntegrity- states that foreign key can be either a NULL value or should be PRIMARY KEY value of other relation

Describe subquery

A subquery is a query that is composed of two queries. The first query (inner query) is within the WHERE clause of the outer query. In some cases the inner query provides results for the outer query to process. In other cases, the outer query results provide results for the inner query

What is a cascading update?

Referential integrity constraints require that foreign key value in one table correspond to primary key values in another. If the value of the primary key is changed, that is, updated, the value of the foreign key must immediately be changed to match it. Cascading updates will set this change to be done automatically by the DBMS whenever necessary

What is PL/SQL?

PL/SQL is Oracle's Procedural Language extension to SQL. The language includes object oriented programming techniques such as encapsulation, function overloading, information hiding (all but inheritance), and so, brings state-of-the-art programming to the Oracle database server and a variety of Oracle tools

What is a Candidate Key?

A table may have more than one combination of columns that could uniquely identify the rows in a table, each combination is a Candidate Key

Difference betwween UNION and UNION ALL

UNION will remove the duplicate rows from the result set while UNION ALL does not.

Difference between TRUNCATE and DELETE

  • Both result in deleting of the rows in the table
  • TRUNCATE call cannot be rolled back  and all memory space for that table is released back to the server while DELETE call can be rolled back
  • TRUNCATE call is DDL command while DELETE call is DML command
  • TRUNCATE call is faster than DELETE call

What are Embedded SQL statements?

Embedded SQL statements are used to incorporate DDL, DML and TCL statements within the body of a procedural language program. These are:
  • DEFINE- used to define cursors
  • OPEN-  used to allocate cursors
  • DECLARE- used to assign variable names
  • EXECUTE- used to execute SQL statements
  • FETCH- used to retrieve data from database

What are DQL statements?

DQL(Data Query Language) statement is used to query data from the database.
  • SELECT- used to get rows and/or columns from tables or views

What are TCL statements?

TCL(Transaction Control Language) statements manage the change made by DML statements, and group DML statements into transactions. These are:
  • COMMIT- used to make a transaction's changes permanent
  • ROLLBACK- used to undo changes in a transaction, either since the transaction started or since a savepoint
  • SAVEPOINT- used to set point to which a transaction can be rolled back
  • SET TRANSACTION- used to establish properties for a transaction

What are DCL statements?

DCL(Data Control Language) are used to grant or revoke privileges from a user. These are:
  • GRANT- used to grant a privilege
  • REVOKE- used to revoke a privilege
  • COMMENT- used to add a comment to the data dictionary

What are DML statements?

DML(Data Manipulation Language) statements enable users to query or manipulate data in existing schema objects. These are:
  • DELETE- used to remove rows from tables or views
  • INSERT- used to add new rows of data into tables or views
  • SELECT- used to retrieve data from one or more tables
  • UPDATE- used to change column values in existing rows of a table or view

What are DDL statements?

DDL (Data Defintion Language) are those statements which are used to define, alter, or drop database objects. These are:
  • CREATE- used to create schema objects
  • ALTER- used to alter schema objects
  • DROP- used to delete schema objects
  • RENAME- used to rename schema objects

What are various categories or statements in SQL?

Oracle divides SQL statements into various categories, which are:
  • DDL (Data Definition Language)
  • DML (Data Manipulation Language)
  • DCL (Data Control Language)
  • TCL (Transaction Control Language)
  • Embedded SQL statements

What is SQL?

SQL stands for Structured Query Language. SQL is a simple and powerful language used to create, access, and manipulate data and structure in a database. SQL is like plain English, easy to understand and write. SQL is a non-procedural language.
Features of SQL:
  1. Easy to read and understand.
  2. Can be used by those having little or no programming experience.
  3. It is a non-procedural language.
  4. It is based upon relational algebra and relational tuple calculus.
SQL was designed by Donald D. Chamberlin and Raymond F. Boyce. 

Hide or Display Computer/Recycle bin Icon from desktop

To hide or display the Computer/Recycle bin Icon from desktop follow these steps:
  • Right click anywhere on the desktop
  • Select Personalize
  • In next screen Click on ‘Change desktop icons’.
  • Select the icons that you want to display in your desktop. Checking Computer’ check box will show the my computer icon.
  • Click Ok to save the changes

How to delete all the inbox or archived messages in facebook?

Using GOOGLE CHROME 
  • Go to SETTINGS
  • Then on the upper left side click on EXTENSIONS
  • Then at the bottom click on GET MORE EXTENSIONS
  • Then on the top left side there's a SEARCH BAR write FACEBOOK DELETE ALL MESSAGES
  • Then click on the + to ADD EXTENSION ....Then close GOOGLE CHROME
  • Then re-open google chrome go to facebook click on the MESSAGE ICON and then See All
  • Just click on THE FACEBOOK DELETE EXTENSION ICON  and click launch
     
  • if u have any messages in OTHER or ARCHIVE put them all in INBOX and this EXTENSION will delete all of those inbox messages.

Changing default directory of CMD

To change default directory of CMD follow these steps:

  • Open CMD and type regedit and press Enter
  • Registry Editor will open. 

  • Navigate to the key HKEY_CURRENT_USER \ Software \ Microsoft \ Command Processor from left side. Now Right click on right panel. Select New, then String Value


  • Name it as Autorun

  • Now double click Autorun and type cd /d "New Path" in Value Data textbox. For example if you want that whenever you open CMD the default path will be E:\GSBPROGRAMMING then you will type as: cd /d E:\GSBPROGRAMMING then click OK and close the Registory Editor and also CMD.

  • Now open CMD again and it will open with new default directory everytime