Monday, 11 July 2016

Arrays in JAVA(ch-5)

                                                       
                               Arrays

A variable which can hold multiple values of similar data type.
Can be of two types
1.    Single Dimensional
2.    Array of Array or Jagged Array

Single Dimensional array
  • Can have only one row and many columns.

Syntax
  • datatype []arrayname=new datatype[size];
  • datatype arrayname[]=new datatype[size];
  • The size can also be user defined.


Example
WAP to ask the user how many numbers, he or she wants. Create an array of that size. Input the data in that array and show the sum of all those numbers.

import java.util.*;
public class ArrayTest1
{
    public static void main(String args[])
    {
        Scanner s=new Scanner(System.in);
        System.out.print("How many numbers : ");
        int size=s.nextInt();
       
        int []ar=new int[size];
        System.out.printf("Enter %d numbers : ",size);
        for(int i=0;i<size;i++)
            ar[i]=s.nextInt();
       
        int sum=0;
        for(int i=0;i<size;i++)
            sum=sum+ar[i];
        System.out.println("Sum is "+sum);
       
    }
}

Note:
Every array provides length property to get size of array.
Example
WAP create an array having some values and show sum of all those values.


public class ArrayTest2
{
    public static void main(String args[])
    {
        int []ar={6,7,5,4,4,6,6,4,4,4,8,9};
        int sum=0;
        for(int i=0;i<ar.length;i++)
            sum=sum+ar[i];
        System.out.println("Sum is : "+sum);
    }
}

Using for-each loop
Another variant of for loop which works with arrays and collections. It works automatically without knowing size of array and without using array indexing.
Syntax
for(datatype variable : arrayname)
{
          Statements;
}




public class ForEachTest
{
    public static void main(String args[])
    {
        int []ar={6,7,5,4,4,6,6,4,4,4,8,9};
        int sum=0;
        for(int n : ar)
            sum=sum+n;
        System.out.println("Sum is : "+sum);
    }
}


Array of Array or Jagged Array
All Java arrays are array of array or single dimensional arrays. Every row can have same or different number of columns.

Syntax 1: Equal number of columns in each row
int [][]ar=new int[3][4];

Syntax 2: un-equal number of columns in each row
int [][]ar=new int[3][];
ar[0]=new int[5];
ar[1]=new int[7];
ar[2]=new int[11];

Example
WAP to create an array having 5 columns in first row, 7 columns in second row and 11 columns in third row. Input the data in the array and show that data.
import java.util.Scanner;
public class JaggedArrayTest
{
    public static void main(String args[])
    {
        Scanner s=new Scanner(System.in);
        int [][]ar=new int[3][];
        ar[0]=new int[5];
        ar[1]=new int[7];
        ar[2]=new int[11];

        for(int i=0;i<ar.length;i++)
        {
            for(int j=0;j<ar[i].length;j++)
            {
                System.out.printf("Enter data in ar[%d][%d] : ",i,j);
                ar[i][j]=s.nextInt();
            }
        }
        for(int i=0;i<ar.length;i++)
        {
            for(int j=0;j<ar[i].length;j++)
                System.out.printf("%4d", ar[i][j]);
            System.out.println();
        }
    }
}



What is mean by triple dot (…)?

Called as ellipses and used to indicate a dialog inside the menus and button and also allows to create the method which can accept variable number of arguments.

Example
WAP having a method which can take variable number of arguments and returns sum of all those arguments.

public class VarArgs
{
    public static void sum(int... num)
    {
        int s=0;
        for(int n: num)
            s=s+n;
        System.out.println("Sum is : "+s);
    }
    public static void main(String... args)
    {
        sum(5,6,7);
        sum(9,8,3,4,5,66,7,77);
    }

}
-------------------------------------------------------------------------------------------
Hope you have learned something new from this post.
-------------------------------------------------------------------------------------------
Thank You
Keep coding :)
Keep learning  :)

CORE JAVA(ch-4->creating user defined static members and wrapper classes )


Hey!guys this is hitesh,and today we'll learn to create user defined static members.
After that we will also see some basic concepts of data conversion using wrapper classes.


How we can create our own static members?

Create some class and create the static reference of your own classes then use anywhere.
import java.io.*;
import java.util.*;
public class My
{
    public static Scanner sc=new Scanner(System.in);
    public static BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
}
import static java.lang.System.*;
import java.io.*;
public class VoterTest1
{
    public static void main(String args[]) throws IOException
    {
        out.print("Name : ");
        String name=My.br.readLine();
        out.print("Age : ");
        int age=My.sc.nextInt();
       
        if(age>=18)
            out.printf("%s you can vote", name);
        else
            err.printf("%s you cannot vote",name);
    }
}

-------------------------------------------------------------------------------------------------------------------------------------
Wrapper Classes
Special classes corresponding to data types which provides advance functions on the data types and data conversion from string to value types
Data type       Wrapper Class
byte                 Byte
short                Short
int                    Integer
long                 Long
float                 Float
double             Double
char                 Character
boolean           Boolean

Example 1
WAP to input a number and show that number in decimal, octal, hexa and binary
import java.util.Scanner;
public class WrapperTest1
{
    public static void main(String args[])
    {
        Scanner s=new Scanner(System.in);
        System.out.print("Enter a number : ");
        int num=s.nextInt();
        System.out.println("Decimal is : "+num);
        System.out.println("Hexa is : "+Integer.toHexString(num));
        System.out.println("Binar is : "+Integer.toBinaryString(num));
        System.out.println("Octal is : "+Integer.toOctalString(num));
    }
}

Example 2
WAP to input a character and check it to be alphabet, digit or special character

Use read() method of System.in to read a character
            int read() throws IOException

public class WrapperTest2
{
    public static void main(String args[]) throws java.io.IOException
    {
        System.out.print("Enter a character : ");
        char ch=(char)System.in.read();
       
        if(Character.isLetter(ch))
            System.out.printf("%c is an alphabet",ch);
        else if(Character.isDigit(ch))
            System.out.printf("%c is a digit", ch);
        else
            System.out.printf("%c is special character", ch);
    }
}

Data conversion from string to value type

datatype variable=wrapperclass.parseDatatype(stringdata);

Example
WAP to input name and age of a person and check it to be valid voter.

import java.io.*;
public class Voter
{
    public static void main(String args[]) throws IOException
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Name : ");
        String name=br.readLine();
       
        System.out.print("Age : ");
        int age=Integer.parseInt(br.readLine());
       
        if(age>=18)
            System.out.printf("Dear %s you can vote",name);
        else
            System.out.printf("Dear %s you cannot vote",name);
    }
}


THAT's all about wrapper classes and we also learned about static members and to create them.

Thank you

Keep coding :)
Keep learning :)

Sunday, 10 July 2016

CORE JAVA(ch-3,taking input from user)

 Hello guys!This is hitesh,and today we will discuss and learn about buffered reader and scanner classes.

  • These classes are used to take input from user!
  • They are used for different purpose.


->We will also learn about Classes and Objects.

Getting Interactive Input from User
-         Java provides built-in classes for data input
o   Scanner class under java.util package
o   BufferedReader class under java.io package

Package
A package is a folder which contains related set of classes.
1.    java.lang
a.     Default package provides commonly used classes
b.    System, Math, String etc.
2.    java.util
a.     Provides collections and utility
b.    LinkedList, Array, Stack
c.     Date, Scanner, DateFormat
3.    java.io
a.     Provides classes for input and output with file handling
b.    File, FileReader, FileWriter
c.     BufferedReader, InputStreamReader

Before using any class of a package we need to import the class into the program using import keyword.
Syntax 1: for single class
import <packagename.classname>;
Syntax 2: for all the classes
import <packagename.*>;


These classes contains two kinds of members
1.    Static or class members
2.    Non-static or instance members
The static members are the common members which do not require an instance of a class and called directly with the class name.
Math.pow(n,p)

Non-static members always need an instance to call them.
String s="Amit Kumar";
s.toUpperCase();

Note:
Reference is also a kind of variable related with some class.
Example
double num; //variable – to hold some data
Double num; //reference – to hold some address

What is class?
A set of specifications or blueprint about an entity describing all possible data members and the methods applicable on that entity to create similar kind of multiple objects.
Use class keyword to define a class.


What is instance or object?
The real entity created based on class specifications is called as instance.
To create an instance we need special method called as constructor along with new.

The constructor is a method having some special features
1.    Same name as class name
2.    No return type
3.    Used to initialize data members of an instance
Example
String s=new String(“Amit Kumar”);

Full Code
public class Test
{
    public static void main(String args[])
    {
        System.out.println(new String("Vikas Kumar").toUpperCase());
       
        String name=new String("Kapil Kumar");
        System.out.println(name.toUpperCase());
        System.out.println(name.toLowerCase());
        System.out.println(name.length());
    }
}

Using Scanner class
-         To input the data from user
-         It provides various methods
o   String next()
o   int nextInt()
o   float nextFloat()
o   double nextDouble()
o   long nextLong()
-         Before using any such function create an instance of Scanner class

Scanner sc=new Scanner(System.in);
Example
WAP to input a number and its power then show number to the power.

import java.util.Scanner;
public class PowerTest
{
    public static void main(String args[])
    {
        Scanner s=new Scanner(System.in);
        System.out.print("Number : ");
        double n=s.nextDouble();
        System.out.print("Power : ");
        double p=s.nextDouble();
       
        double r=Math.pow(n, p);
       
        System.out.printf("%.2f to the power %.2f is %.2f", n,p,r);
    }
}

Ex-2:WAP to insert age and name of person and check it to be a valid voter.

import java.util.Scanner;
public class VoterTest
{
    public static void main(String args[])
    {
        Scanner s=new Scanner(System.in);
        System.out.print("Name : ");
        String name=s.next();
        System.out.print("Age : ");
        int age=s.nextInt();
       
        if(age>=18)
            System.out.printf("%s you can vote", name);
        else
            System.out.printf("%s you cannot vote",name);
    }
}
The above example was based on scanner class..lets do it with the help of buffered reader. 

Using import static keyword
Keywords used to import static members of a class to avoid the use of the class name again and again.

Syntax

import static <packagename>.<classname>.membername;
or
import static <packagename>.<classname>.*;

Example
import java.util.Scanner;
import static java.lang.System.*;
public class VoterTest
{
    public static void main(String args[])
    {
        Scanner s=new Scanner(in);
        out.print("Name : ");
        String name=s.next();
        out.print("Age : ");
        int age=s.nextInt();
       
        if(age>=18)
            out.printf("%s you can vote", name);
        else
            out.printf("%s you cannot vote",name);
    }
}

Using BufferedReader class
A class from java.io package to read data from anywhere.
When we press a key from keyboard (System.in), it provides stream of bits. This stream of bits get passed to another class called as InputStreamReader which converts the stream into readable character format.
These character get assembled into memory until we press the enter using another class called as BufferedReader. It provides readLine() method to read the data in the buffer.
            String readLine() throws IOException

import java.util.Scanner;
import static java.lang.System.*;
import java.io.*;
public class VoterTest1
{
    public static void main(String args[]) throws IOException
    {
        InputStreamReader isr=new InputStreamReader(System.in);
        BufferedReader br=new BufferedReader(isr);
       
        Scanner s=new Scanner(in);
        out.print("Name : ");
        String name=br.readLine();
        out.print("Age : ");
        int age=s.nextInt();
       
        if(age>=18)
            out.printf("%s you can vote", name);
        else
            out.printf("%s you cannot vote",name);
    }
}

So,this was like scanf and gets of C language, where we use scanner class as scanf() and buffered reader as gets().

In the next post we'll learn how to create our own static members and what are wrapper classes.


Thank you
Keep learning :)
keep coding :) 




CORE JAVA (ch-2 DATA TYPE/SETTING PATH)

Hey!guys,this is hitesh..and in the second chapter we'll discuss about data types in java and we'll also learn about path setting for java so that we can execute our programs.

Data Types in Java
1.     byte                1 byte
2.     short              2 byte
3.     int                   4 byte
4.     long                8 bytes
5.     float               4 bytes
6.     double           8 bytes
7.     boolean         undefined (Java Black Book – 2 bytes)
8.     char                2 bytes
Note: all are signed

Data inside the variables
1.     Literals
2.     Interactive Input
3.     Non-interactive input
4.     File Input
5.     Database input

Literals
The values that we use from our side for some assignment or expression are called as literals.
Example
int num=6;
double ar=3.14*num*num;

Literals can be of different types
1.     Integrals
2.     Floatings
3.     Characters
4.     Strings
5.     Booleans
Integrals
By default such numbers take size of int.
Use l or L with long as suffix
int num=6;
long num=6L;
Integral Literals can be of four types
1.     Decimal – 0 to 9, default
2.     Octal – 0 to 7, starts with 0
3.     Hexa – 0 to 9, A to F, Starts with 0x or 0X
4.     Binary – 0 and 1, starts with 0b or 0B
Example
//Sample.jar
class First
{
            public static void main(String args[])
            {
                        int x=6789; //decimal
                        int y=03456; //octal
                        int z=0X8D5; //hexa
                        int p=0b101011; //binary

                        System.out.println(x);
                        System.out.println(y);
                        System.out.println(z);
                        System.out.println(p);
                       
            }
}

Compile the program using JDK software with JAVAC compiler provided inside the BIN folder of the JDK


Syntax
JAVAC <programname>
Example
JAVAC Sample.java à First.class


Now run the class file
JAVA First

Note
If your BIN folder is not set in the PATH the JAVAC and JAVA will not work.
We need to set the PATH
PATH=C:\Program Files\Java\jdk1.8.0_05\bin

If you want to set the path for one time only use the following steps
My Computer à  Properties à Advance System Settings à Advanced à
Environmental Variables
à System Variables à Path à Edit…
Now paste the PATH after the semicolon


Note
We can also use underscore (_) as number separator
//Sample.java
class First
{
            public static void main(String args[])
            {
                        int x=12_67_899; //decimal
                        int y=07; //octal
                        int z=0X8D5; //hexa
                        int p=0b10_1011; //binary

                        System.out.println(x);
                        System.out.println(y);
                        System.out.println(z);
                        System.out.println(p);
                       
            }
}

Floating Literals

All numbers with decimal point are of double type by default. Use f or F with float.
double n=6.7;
float x=5.6; //error
float x=5.6f; //correct

Example
class Second
{
            public static void main(String... args)
            {
                        float x=5.6f;
                        System.out.println(x);
            }
}

Note:
A program name and class name can be same or different but if a class is public then both must be same.

Character Literals
Enclosed in single quotes and every character has corresponding ASCII value
char ch=’A’;
or
char ch=65;


String Literals
Enclosed in double quotes and managed by String class.
String name=”Rohit”;
Now we can use basic string methods on name.
Example
class Third
{
            public static void main(String args[])
            {
                        String name="Vikas Kumar Singh";
                        System.out.println("Name is : "+name);
                        System.out.println(name.toUpperCase());
                        System.out.println(name.toLowerCase());
                        System.out.println(name.length());
            }
}

Boolean Literals
Can have only two values
1.     true
2.     false
boolean married=true;

That's all about the data types in JAVA
In the next post we'll discuss about taking input from user with buffered reader,and scanner class with some more packages and we'll also learn about Classes and objects.


Thank You 
Keep learning :)
Keep Coding ;)