Saturday 31 January 2015

How To Read Current Time In JAVA

In this program we will learn how to show current time or system time in java


import java.util.*;

public class GetSystemDateAndTime
{
   public static void main(String args[])
   {
      int day, month, year;
      int second, minute, hour;
      GregorianCalendar date = new GregorianCalendar();
      day = date.get(Calendar.DAY_OF_MONTH);
      month = date.get(Calendar.MONTH);
      year = date.get(Calendar.YEAR);
      second = date.get(Calendar.SECOND);
      minute = date.get(Calendar.MINUTE);
      hour = date.get(Calendar.HOUR);
      System.out.println("Current date and time is  "+day+"/"+(month+1)+"/"+year+"::"+hour+" : "+minute+" : "+second);
   }
}



Now you will get current time of your system and you can customize it as your need.




How to Print Double Quotes in JAVA


how to print double quotes in java

public class Display {
public static void main(String[] args) {
       String str="GANGA:"+"\"RIVER\"";
       System.out.print(str);

   }
}


Output:

GANGA:"RIVER"

Thursday 29 January 2015

Nested Class In Java

Nested Class In Java 

In java we can define a class within other class, such class called nested class

class Outer{
    ...
    class Nested {
        ...
    }
}
 
Nested classes are two types:
1. static nested classes  .
2. Non-static nested classes( inner classes).



Static Class In Java

Static Class In Java

Static classes do not need the reference of the outer class. They act like an outer class within themselves. Normal non-static nested classes, on the other hand, need reference of the outer class.  In other words, static classes are independent of the outer class, while other inner classes are dependent on the outer class.

static nested class cannot access non-static (instance) data member or method.
It can access static data members of outer class including private.

 Example 1:

public class OuterClass {
 static int i=10;
static class InnerStatic{
  void print(){
  System.out.println("i="+i);
  }
}
public static void main(String[] args) {

OuterClass.InnerStatic obj=new OuterClass.InnerStatic();
obj.print();
}
}
Output:
I=10
Ex2:
public class OuterClass {
 static private int i=10;
static class InnerStatic{
  void print(){
  System.out.println("i="+i);
  }
}
public static void main(String[] args) {

OuterClass.InnerStatic obj=new OuterClass.InnerStatic();
obj.print();
}
}

Output:
i=10

Example 2:

package typeofclass;

public class OuterClass {
 int i=10;
static class InnerStatic{
  void print(){
  System.out.println("i="+i);
  }
}
public static void main(String[] args) {

OuterClass.InnerStatic obj=new OuterClass.InnerStatic();
obj.print();
}
}

Output:
Cannot make a static reference to the non-static field i

Example 3:

package typeofclass;

public class OuterClass {
     static int data=10;
     //int mark=10
static void display(){
System.out.println("data="+data);
//System.out.println("mark="+mark); error here
}

void show(){
System.out.println("In Show Method");
}

static class InnerStatic{
  void print(){
 display();
 //show(); Cannot make a static-
 //reference to the non-static method show() from the type OuterClass
  }
}
public static void main(String[] args) {

OuterClass.InnerStatic obj=new OuterClass.InnerStatic();
obj.print();
}
}

Output:
data=10


Tuesday 27 January 2015

How to get input from user in java

We are using Scanner class to get input from user.Scanner class is present in java.util package so we import this package in our program. We first create an object of Scanner class and then we use the methods of Scanner class. Consider the statement
Scanner sc = new Scanner(System.in); 
1) nextLine to input a string
2) nextInt to input an integer
3) nextFloat to input a float

package basic;

import java.util.Scanner;

public class GetInputFromUser {

public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter string");
String s1=sc.nextLine();
System.out.println("Enter number");
int i=sc.nextInt();
System.out.println("Enter double number");
double d=sc.nextDouble();
                System.out.println("s1="+s1)
System.out.println("i="+i);
System.out.println("d="+i);
;

}

}


//Output:

Enter string
i love my india
Enter number
123
Enter double number
233.22

s1=i love my india
i=123
d=123




ER Diagram Symbols and Meaning

  1. An entity–relationship model (ER model) is a data model for describing the data or information aspects of a business domain or its process requirements, in an abstract way that lends itself to ultimately being implemented in a database such as a relational database. The main components of ER models are entities (things) and the relationships that can exist among them.








ENTITIES

Entities are objects or concepts that represent important data. They are typically nouns, e.g. customersupervisorlocation, or promotion.
                   
  • Strong entities exist independently from other entity types. They always possess one or more attributes that uniquely distinguish each occurrence of the entity.


  • Weak entities depend on some other entity type. They don't possess unique attributes (also known as a primary key) and have no meaning in the diagram without depending on another entity. This other entity is known as the owner.

  • Associative entities , the entity describes a connection between two entities with an otherwise many-to-many relationship, for example, a student can registers in many course and a course can have many student.





RELATIONSHIPS

  • Relationships are meaningful associations between or among entities. They are usually verbs, e.g. assignassociate, or track. A relationship provides useful information that could not be discerned with just the entity types.
  • Weak relationships, or identifying relationships, are connections that exist between a weak entity type and its owner.


ATTRIBUTES

  • An Attribute describes a property or characterstic of an entity. For example, Name, Age, Address etc can be attributes of a Student. An attribute is represented using eclipse.





Key Attribute

Key attribute represents the main characterstic of an Entity. It is used to represent Primary key. Ellipse with underlying lines represent Key Attribute




Composite Attribute

An attribute can also have their own attributes. These attributes are known as Composite attribute.



 Relationship:

A Relationship describes relations between entities. Relationship is represented using diamonds.




There are three types of relationship that exist between Entities.
  • Binary Relationship
  • Recursive Relationship
  • Ternary Relationship 

Binary Relationship

Binary Relationship means relation between two Entities. This is further divided into three types.
  1. One to One : This type of relationship is rarely seen in real world.

  2. one-to-one example

    The above example describes that one student can enroll only for one course and a course will also have only one Student. This is not what you will usually see in relationship.

  1. One to Many : It reflects business rule that one entity is associated with many number of same entity. For example, Student enrolls for only one Course but a Course can have many Students.

  2. one-to-many example

    The arrows in the diagram describes that one student can enroll for only one course
    .
  3. Many to Many :

  4. many-to-many example

    The above diagram represents that many students can enroll for more than one courses.

Recursive Relationship

When an Entity is related with itself it is known as Recursive Relationship.

recursive relationship example

Ternary Relationship

Relationship of degree three is called Ternary relationship.


Monday 26 January 2015

Data Structure And Algorithm In Java

data structure and algorithm in java

Array Tutorial In java

Array Problems In java

Linked list Tutorial In Java.

Linked list Problems In Java

Stack and Queue Tutorial

Stack and Queue Problems In Java

Sorting Algorithms.

Searching Algorithms.

Tree Tutorial In Java

Tree problems In Java

Graph Tutorial In java

Graph problems In java




Sunday 25 January 2015

Default constructor of super class always call in java

Default constructor of super call always call.

         
India.java

package inherintance;

public class India {
    static int _i=0;
    static int _j=0;
    India(int i){
    _j++;
    System.out.println("India parameter constructor call="+_j);
    }
    public India() {
          // TODO Auto-generated constructor stub
    _i++;
    System.out.println("India default constructor call="+_i);
     }
    
}

Dehradun.java

package inherintance;

public class Dehradun extends India {
     Dehradun(){
         
     }

Dehradun (int i){
     System.out.println("Dehradun parameter constructor calli="+i);
}   
     public static void main(String[] args) {
          Dehradun obj=new Dehradun(4);
        System.out.println("I value="+_i);

           System.out.println("==============");

           Dehradun obj1=new Dehradun();
             System.out.println("I value="+_i);
         
     }
    
}

Output:

India default constructor call=1
Dehradun parameter constructor call i=4
I value=1
==========
India default constructor call=2
Dehradun defalt constructor call
I value=2

  

Saturday 24 January 2015

Swap two number using bit operator

Swap two number using bitwise operator.

We use  ^ (XOR) operator for this.

public class SwapNumberUsingBitOperator {

public static void main(String[] args) {
int i=9;
int j=4;
System.out.println("Before swap i="+i+"j="+j);
i=i^j;
j=i^j;
i=i^j;
System.out.println("After Swap i="+i+"j="+j);
}

}

Check a string value is Integer or not in java


Check a given string value is Integer or not in java


private boolean isInteger(String str){

for (int i = 0; i < str.length(); i++) {
if (str.charAt(i)-'0'<0||str.charAt(i)-'0'>9) {
return false;
}
}
return true;
}



 Related Posts:


Check a string value is Integer or not in java. (Solution).

Check ia string is hexadecimal number or not (Solution).

Generate Combination in java (Solution).

Generate permutation of string(Solution).

Reverse string in java (Solution).

Find duplicate characters with occurrences in a string(Solution).

Permutation of a number(Soluion).

Split the String in java(Solution).

Convert string into number in java(Solution).

Swap two strings without using any variable(Solution).

Get a number from a string in java(Solution).

Add Two Big Number In Java(Solution).

Expand String(Solution).

Reverse String (Solution).

 

 

Check ia string is hexadecimal number or not


Check if a String is Hexadecimal number or not in java


  public boolean isHexNumber(String){
       boolean flag;
       try {
           int t = Integer.parseInt(value, 16);
            flag = true;
       } catch (NumberFormatException e) {
            flag = false;
       }
       return flag;
}
   



 Related Posts:


Check a string value is Integer or not in java. (Solution).

Check ia string is hexadecimal number or not (Solution).

Generate Combination in java (Solution).

Generate permutation of string(Solution).

Reverse string in java (Solution).

Find duplicate characters with occurrences in a string(Solution).

Permutation of a number(Soluion).

Split the String in java(Solution).

Convert string into number in java(Solution).

Swap two strings without using any variable(Solution).

Get a number from a string in java(Solution).

Add Two Big Number In Java(Solution).

Expand String(Solution).

Reverse String (Solution).

Friday 23 January 2015

Read File And Count Occurrence Of Word In Java

Read a file and count the occurrence of word in java

import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.TreeMap;
import java.util.StringTokenizer;

public class fileRead {

    public static void main(String [] args){

        try{
           
            String textFile ="D:\\workspace\\datastructure\\src\\javaprogram\\test.txt";
            BufferedReader input = new BufferedReader(new FileReader(textFile));
           
            //Creating the Map to store the words and their occurrences
            TreeMap<String, Integer> frequencyMap = new TreeMap<String, Integer>();
            String currentLine = null;
           
            //Reading line by line from the text file
            while((currentLine = input.readLine()) != null){
               
                //Parsing the words from each line
                StringTokenizer parser = new StringTokenizer(currentLine, " \t\n\r\f.,;:!?'\"");
                while(parser.hasMoreTokens()){
                    String currentWord = parser.nextToken();
                   
                    Integer frequency = frequencyMap.get(currentWord);
                    if(frequency == null){
                        frequency = 0;                       
                    }
                    //Putting each word and its occurrence into Map
                    frequencyMap.put(currentWord, frequency + 1);
                }
               
            }
           
            //Displaying the Result
            System.out.println(frequencyMap);
                  
        }catch(IOException ie){
            ie.printStackTrace();
            System.err.println("Your entered path is wrong");
        }       
       
    }
   
}

Wednesday 21 January 2015

Tic Tac Toe game



Tic Tac Toe Game In Java


Tic Tac Toe game program in java

TicTacToe.java


public class TicTacTOe {
  int _row=3;
char _board[][]=new char[_row][_row];
public void makeBoard(){
for (int i = 0; i <_row; i++) {
for (int j = 0; j < _row; j++) {
_board[i][j]='o';
}

}
}
boolean isValid(int r,int c){
return((r>=0&&r<_row)&&(c>=0&&c<_row));
}
boolean isFill(int r,int c){
return(_board[r][c]!='o');
}
public boolean gamePlay(int r ,int c,int playerNo){
if (!(isValid(r,c))) {
System.out.println("Enter Correct index");
return true ;
}
if (isFill(r,c)) {
System.out.println("This index already fill");
return true;
}
if (playerNo==1) {
_board[r][c]='*';
} else {
        _board[r][c]='+';
}
return false;
}

boolean horizontalAndVerticalMatch(char ch,int n){
// for row and col math
    boolean flag=true;
for (int i = 0; i < _row; i++) {
   flag=true;
  for (int j = 0; j < _row; j++) {
  System.out.println("i="+i+"j="+j);
  char ch1=(n==1)?_board[i][j]:_board[j][i];
         if (ch1!=ch) {
         System.out.println("y");
flag=false;
break;
}
 }
  if (flag) {
  return flag;
}
}
return flag;
}
boolean majorDiagonal(char ch){
return((_board[0][0]==ch)&&(_board[1][1]==ch)&&(_board[2][2]==ch));
}
boolean minorDiagonal(char ch){
return((_board[2][0]==ch)&&(_board[1][1]==ch)&&(_board[0][2]==ch));
}
public boolean isGameOver(int PlayerNo){
char ch;
if (PlayerNo==1) {
ch='*';
} else {
ch='+';
}
return(horizontalAndVerticalMatch(ch,1)||horizontalAndVerticalMatch(ch,2)||majorDiagonal(ch)||minorDiagonal(ch));
}
public void display(){
for (int i = 0; i <_row; i++) {
for (int j = 0; j < _row; j++) {
System.out.print("     "+_board[i][j]);
}
System.out.println("");
}
}

}

MainTicTacToe.java

import java.util.Scanner;

public class MainTicTacToe extends TicTacTOe {
 public static void main(String[] args) {
TicTacTOe obj=new TicTacTOe();
obj.makeBoard();
obj.display();
int r,c;
Scanner input=new Scanner(System.in);
while(true){
boolean flag=true;
while(flag){
System.out.println("Player 1");
System.out.println("enter row");
r=input.nextInt();
System.out.println("enter col");
c=input.nextInt();
flag=obj.gamePlay(r,c,1);
}
if (obj.isGameOver(1)) {
obj.display();
System.out.println("Player 1 Win Game");
break;
}
System.out.println("============");
obj.display();
flag=true;
while(flag){
System.out.println("Player 2");
System.out.println("enter row");
r=input.nextInt();
System.out.println("enter col");
c=input.nextInt();
flag=obj.gamePlay(r,c,2);
}
if (obj.isGameOver(2)) {
obj.display();
System.out.println("Player 2 Win Game");
break;
}
System.out.println("============");
obj.display();
}
}
}






Minesweeper game in java


minesweeper Program in java

Minesweeper.java

import java.util.Random;
public class Minesweeper {
  int _row=5,_col=5,_countGameOver=0;
  int [][] _board=new int[_row][_col];
  boolean [][] _flagMatrix=new boolean[_row][_col];
 public void plotBoard(){
 int noOfBomb=_col;
while(noOfBomb>0) {
 int i=getRandomNumber();
 int j=getRandomNumber();
 if (_board[i][j]!=-1) {
_board[i][j]=-1;
noOfBomb--;
  }
 }
  }
public int getRandomNumber(){
Random t = new Random();
// random integers in [0, 100]
int num;
{
num=t.nextInt(_col);
}while(num>_col);
return num;
    }
boolean isValid(int i,int j){
return((i>=0 && i<_row)&&(j>=0 && j<_col));
}
int getAdjBomb(int i,int j){
int num=0;
//System.out.println("i="+i+"j="+j);
for (int k = i-1; k <=(i+1); k++) {
for (int l= j-1; l<=(j+1); l++) {
    if (isValid(k,l)&&(_board[k][l]==-1)) {
num++;
   }
    }
}
return num;
}
public void calculateCounts(){
for (int i = 0; i <_row; i++) {
    for (int j = 0; j <_col; j++) {
    if(_board[i][j]!=-1)
       _board[i][j]=getAdjBomb(i,j);
    }
}
}
public void print(){
for (int i = 0; i <_row; i++) {
for (int j = 0; j <_col; j++) {
System.out.print(" "+_board[i][j]);
}
System.out.println("");
}
}
public void displayFlagMatrix(){
for (int i = 0; i <_row; i++) {
   for (int j = 0; j <_col; j++) {
    if (_flagMatrix[i][j]==true) {
    System.out.print(" "+"*");
}
    else{
    System.out.print(" "+"+");
    }
   }
System.out.println(" ");
}
}
public boolean play(int r,int c){
if (!(isValid(r,c))) {
System.out.println("Please Enter row and col in correct range");
return false;
}
if (_flagMatrix[r][c]==true) {
System.out.println("This is a open position please enter other col and row");
return false;
}
if (_board[r][c]==-1)
return true;
if (_board[r][c]!=0) {
_countGameOver++;
_flagMatrix[r][c]=true;
}
else{
_flagMatrix[r][c]=true;
_countGameOver++;
openSpace(r, c);
}
return false;
}
void openSpace(int r,int c){
for (int k = r-1; k <=(r+1); k++) {
   for (int l= c-1; l<=(c+1); l++) {
            if (isValid(k,l)&&(_board[k][l]!=-1)&&(_flagMatrix[k][l]==false)) {
             _flagMatrix[k][l]=true;
              _countGameOver++;
          if (_board[k][l]==0) {
             openSpace(k,l);
          }
         }  
    }
}
}
public boolean checkGameOver(){
return(_countGameOver==(_row*_row)-(_row));
}
}

++++++++++++++++++

MainMinessweeper.java


import java.util.Scanner;
import com.jan21.*;
public class MainMinesweeper extends Minesweeper {
public static void main(String[] args) {
MainMinesweeper obj=new MainMinesweeper();
    obj.plotBoard();
    obj.calculateCounts();
    System.out.println("afate count");
    obj.print();
    int r,c;
    System.out.println("+++++++++++++++");
    obj.displayFlagMatrix();
    while(true){
  System.out.println("===============");
    Scanner input=new Scanner(System.in);
    System.out.println("enter row");
    r=input.nextInt();
    System.out.println("enter col");
    c=input.nextInt();
    if (obj.play(r,c)) {
System.out.println("You Lose");
break;
  }
System.out.println("ok");
if (obj.checkGameOver()) {
obj.displayFlagMatrix();
System.out.println("You Win Game");
break;
}
obj.displayFlagMatrix();
System.out.println("+++++++++++");
obj.print();

  }
}

}



Top array Programs In Java

arrays program in java with solution

 expand a given array (Solution)

Java Tutorial

 

Java Tutorial


OOP Concept:




      Programs :



Java Collections Framework Tutorials For Beginners:





Data Structure in Java



Top String Programs In Java

Top String Program In Java


Check a string value is Integer or not in java. (Solution).

Check ia string is hexadecimal number or not (Solution).

Generate Combination in java (Solution).

Generate permutation of string(Solution).

Reverse string in java (Solution).

Find duplicate characters with occurrences in a string(Solution).

Permutation of a number(Soluion).

Split the String in java(Solution).

Convert string into number in java(Solution).

Swap two strings without using any variable(Solution).

Get a number from a string in java(Solution).

Add Two Big Number In Java(Solution).

Expand String(Solution).

Reverse String (Solution).



Other Useful Posts:


  Top 50 core java coding interview question and answer

  Guava Tutorial