Sunday, 22 May 2022

How to write a program to print month of the year in Java

Write a program to print month of the year in Java.

import java.util.*;
import java.time.*;
import java.time.temporal.TemporalAdjusters;

/**
 *
 * finding current month using Calendar class and LocalDate
 */
public class CurrentMonthInJava{

    public static void main(String[] args) {
                
        String[] month = {"January", "February", "March", "April", "May", "June", "July", "August","September", "October", "November", "December" };
 

            Calendar c=Calendar.getInstance();
            
            System.out.println(c);
            int mon=c.get(Calendar.MONTH)+1;            
            System.out.println("The current month of year is "+month[mon-1]);
            System.out.println("The previous month of year is "+month[mon-2]);
            System.out.println("The next month of year is "+month[mon]);
            
            
             // month,year
    LocalDate today = LocalDate.now();
    LocalDate currentDate = LocalDate.parse(""+today);
 
            // Get day from date
        int day = currentDate.getDayOfMonth();
            // method 1: Get month from date using currentDate
        Month m = currentDate.getMonth();
            // method 2: Get month from date using today
        Month m1=today.getMonth();
            // Get year from date
        int year = currentDate.getYear();
 
        // Print the day, month, and year
        System.out.println("Current Day: " + day);
        System.out.println("Current Month: " + m);
        System.out.println("Current Year: " + year);
        System.out.println(m1);
            
    // Printing remaining number of months
    
     
     System.out.println("Today is: "+today);
     LocalDate lastDayOfYear = today.with(TemporalAdjusters.lastDayOfYear());
     Period period = today.until(lastDayOfYear);    
     System.out.println("Months remaining in the year: "+period.getMonths());    
     
   
     
    }
    
}

Output:

java.util.GregorianCalendar[time=1653191579706,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Calcutta",offset=19800000,dstSavings=0,useDaylight=false,transitions=7,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2022,MONTH=4,WEEK_OF_YEAR=22,WEEK_OF_MONTH=4,DAY_OF_MONTH=22,DAY_OF_YEAR=142,DAY_OF_WEEK=1,DAY_OF_WEEK_IN_MONTH=4,AM_PM=0,HOUR=9,HOUR_OF_DAY=9,MINUTE=22,SECOND=59,MILLISECOND=706,ZONE_OFFSET=19800000,DST_OFFSET=0]
The current month of year is May
The previous month of year is April
The next month of year is June
Current Day: 22
Current Month: MAY
Current Year: 2022
MAY
Today is: 2022-05-22
Months remaining in the year: 7

 


Sunday, 20 March 2022

How to read json file in python without pandas?

How to read json file in python?

There are several ways are there to read data from json file. JSON which stands for javascript object notation is one of the commonly used file in application development because of its advantages. Python has so many libraries to read data from files. Here we see  python program to read data from json without using pandas.

 

 

import json
try:
    with open("emp.json",'r') as jsonfile:
        reader=json.load(jsonfile)
        for i in reader.items():
            print(i)
        jsonfile.close()
except FileNotFoundError:
    print("no file exist")



read data from json


Wednesday, 29 December 2021

How to check email already exist in database in java

One of the most important thing in applications is to check email id exist or not.
Email verification existence plays a major role while the application is running.
There are so many places are there where we need to check email id is there or not.
For example during forget password recovery we first check whether email id exist or not.Here is the java program to check email id already exist in database or not.


import java.sql.*;
class EmailExistenceCheck {
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        String email=sc.next();
        EmailExistenceCheck.emailValidate(email);
    
    }


    public static void emailValidate(String email){
        boolean status=false;  
        try{  
            Class.forName("oracle.jdbc.driver.OracleDriver");  
            Connection con= DriverManager.getConnection  

                                                       ("jdbc:oracle:thin:@localhost:1521:xe","system","system");  
            PreparedStatement pstmt=con.prepareStatement(  
            "select * from login where email=?");  
            pstmt.setString(1,email);       
            ResultSet rs=pstmt.executeQuery();  
            status=rs.next();  
             if(status){  
                    System.out.println("email id already exist");
                }  
            else{
                     System.out.println("email id does not exist");
                }  
    }catch(Exception e){System.out.println(e);}  
}  

}


How to check email already exist in database in java using servlet.


Thursday, 17 June 2021

How can I get data from database table into combo box in Java

How can I get data in a combo box from a database in Java | Load data from database to Combo box in Java:

In this we will see how to load data from database table into combo box component of swings in java.  

 package demo;
 

import java.awt.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
import java.util.Vector;
import javax.swing.*;
public class RuntimeComboBoxDemo {
 
   
   public static void main(String[] args) {

      
       try{  


            Class.forName("oracle.jdbc.driver.OracleDriver");  
            Connection con=DriverManager.getConnection(  
                            "jdbc:oracle:thin:@localhost:1521:xe","system","system");  
            System.out.println("Connected to database...");
            Statement pstmt=con.createStatement();
            ResultSet rs=pstmt.executeQuery("select distinct ename from emp"); 
       
               JFrame f=new JFrame();
               Vector<String> v=new Vector<String>();
               while(rs.next()){
                  v.add(rs.getString(1));
               }
              JComboBox jcb = new JComboBox(v);
              f.setLayout(new FlowLayout());
              f.add(jcb);
              f.setSize(300, 250);
              f.setLocationRelativeTo(null);
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              f.setVisible(true);
              }
    catch(Exception e){
        System.out.println(e);
    }
   }
    
}

 

 


Wednesday, 12 May 2021

What is the difference between Combo box and radio button

Difference between Combo box and radio button in java:


  • Combo box is editable. 
    Radio button is non editable.
  • Combo box take less space on screen if multiple values are there.
    Radio button take more space on screen if multiple values are there.
  • Combo box allows us to select from list.
    Radio button allows us to select from group.
  • JComboBox jcbox = new JComboBox();    
    JRadioButton option1 = new JRadioButton("");
  • For Combo box import package is, import javax.swing.JComboBox;
    For radio button import package is, import javax.swing.JRadioButton;



Sunday, 9 May 2021

Combo box in java

What is Combo box in java:

One of the Swing component is JComboxBox which has a drop-down list of choices for user that lets him to selects one of the item from the list.

It allows user to select an item from the list.The combo box can be read only or it can be editable.

The read only combo box is the one from where user can select only one value from the list  (whether the desired value is not there or not).

The editable combo box is the one from where user can select only one value from the list if the desired value is not there then he can enter his own value.

For Combo box import package is, import javax.swing.JComboBox;


Wednesday, 7 April 2021

The python program to read string and print longest word

Write a program in python to read string and print longest word and its position:

word=input('enter a value')
words=word.split()
print(words)
length=len(words)
maximum=0
pos=0
for i in range(length):
    l=len(words[i])
    if l>maximum:
        maximum=l
        pos=i   
print('longest word is',words[pos])
print('Number of characters in longest word  is',maximum)
print('Position on longest word is ',pos+1)
    


Thursday, 28 January 2021

Python program for Peterson number

Python program for Peterson number:

 

import math
num=int(input("Enter a number"))
m=num
sum=0
while num>0:

    rem=num%10
    fact=math.factorial(rem)
    sum=sum+fact
    num=num//10
if sum==m:
    print('Number is Peterson number')
else:
    print('Number is not a Peterson number')

 

Output 1: 

 

Peterson Number

Output :2


 


Sunday, 13 December 2020

Coding standards in Java

 Coding standards in Java :

Java programming language has defined some coding standards for class, variables, methods, interface which has to be followed.

Standards for methods in java:

  • In java programming language coding standards for method is usually name of method  should either be verb or noun combination and it has to start with lower letter.
  • If method name has multiple word than every first character of inner word must start with uppercase.


    Ex: print(), println(), sleep(), setAttribute(), getAttribute().

Standards for Variables in java:

  • The variable names in java programming language usually should be noun and start with lowercase letter.
  • If variable name has multiple word than every first character of inner word must start with uppercase.


    Ex: name, age, email, mobileNumber, studentId.

For Classes:

  • Coding standard of class in java programming language is name of class  should be noun and it has to star with uppercase letter.
  • If class name has multiple word than every word must start with uppercase.


    Ex: String, System, StringBuffer, StringBuilder, Thread

For Interface:

  • Unlike class interface in java language usually name of interface must be adjective and interface name must start with uppercase letter.
  • If interface name has multiple word than every first character of word must start with uppercase.


Eg:  Serializable, Runnable



Constants:

  • These names should be a noun and these should contain only uppercase.
  • If the name of constant consists of multiple word than thye should be separated with ( _ ) underscore.

    
    Ex: MAX_PRIORITY, MIN_PRIORITY.



Getter Methods:


  • Getter should be public method.
  • Method name should be prefixed with get.
  • Getter should not take any parameter.

   syntax:   getXXXX( )
    
    Ex.  getInt( ), getString( ), getDate( ).

Setter Methods:


  • Setter should be public method and return Type of setters should be void.
  • Method names of setters should be prefixed using set.
  • They take some argument.

    

    syntax:   setXXXX( )


    Ex.  setInt( ), setString( ), setAttribute( ).

This is a java program for getters and setters:

public class EmployeeBean{

    private int empId;
    private String name;

    public void setId(int id){
        this.empId=id;
    }

    public int getId(){
        return empId;
    }
    public void setName(String name){
        this.name=name;
    }

    public String getName(){
        return name;
    }

}

Friday, 4 December 2020

In C programming V is used for

In C programming V is used for:

 In C programming V is used for vertical tab. This is a program that demonstrate the use of  \V.

// this is a C program to demonstrate V in c language

 #include <stdio.h>

int main()
{
    printf("Hello \n ");  

    printf("This  \v is  \v a  \v c-language \v program \v to \v demonstrated \v V. ");

    return 0;
}

 OUTPUT:



 Here are few escape characters:

 \b which is used for Backspace in C programming language 

\e   we use this for escape character  in C.

\n 
 This is used for new line character.
 
 \t 
   This is used for Horizontal tab
\\ 
  We use this in c-language  to display the backslash character.

 

Tuesday, 1 December 2020

How to Beautify xml code

 Beautify XML code:

 Online XML Beautifier beautifies ugly XML code and makes it more readable.
 These Online XML Beautifiers gives the code proper indentation, spaces,newlines etc. so that
 it becomes well-formatted code which is easy understandable by user.

Some of them are Notepad3, Code Browser, Kate, Bluefish, Text Editor Pro, Notepad++, XML Notepad 2007, Atom.
 

Friday, 27 November 2020

How to check url is http or https in java

 This is a java program to check protocol is http or not.

URLProtocolDemo.java    

 
import java.net.*;    
public class URLProtocolDemo{    
public static void main(String[] args){  
//String url="https://www.w3schools.com/html/";  
try{    
    URL url=new URL(url);    
     String protocol=   url.getProtocol();
     System.out.println("Protocol of given url is : "+protocol);
     if(protocol.equalsIgnoreCase("https")); 

     System.out.println("Protocol is a https protocol");    
       }

    else{

           if(protocol.equalsIgnoreCase("http")){
                   System.out.println("Protocol is a http protocol");    
              }

          else{
                   System.out.println("Protocol is neither http nor https protocol ");    
               }    
   }

catch(Exception e)  {
    System.out.println(e);
  }  
 }
}



Thursday, 26 November 2020

Printing diagonal elements of a given matrix in C language

Printing diagonal elements of a given matrix in language: 

In this we are going to display left and right diagonal elements of a given matrix in language.

#include <stdio.h>
void main(){
int matrix1[3][3],i, j;

 // reading the elements of first matrix
    printf(" enter elements of first matrix ");
    for( i=0; i<3 ;i++){
        for(j=0;j<3;j++){
            scanf( "%d", &matrix1[i][j]);
        }
    }

    // printing the resultant matrix  
    printf(" the matrix is  \n");
    for (i=0; i<3; i++){
        for( j=0; j<3; j++){
            printf(" %d ", matrix1[i][j]);
        }
        printf(" \n ");
    }
printf(" the left diagonal elements of this matrix are \n");

printf( "%d,   %d,   %d ",  matrix1[0][0],matrix1[1][1],matrix1[2][2]);

printf(" the right diagonal elements of this matrix are \n");

printf(" %d,   %d,   %d ",  matrix1[0][2],matrix1[1][1],matrix1[2][0]);
}

Sunday, 22 November 2020

What's the difference between comment line and code line?

What's the difference between comment line and code line?

  • Comment line:  

    Comment line is a that describes something about the code. But these lines wont get executed.
  •  Code line: 

    Code line  is a line that has the logic or our program. This line will get executed. Compiler will compile this line and output will be generated.
The similarity between comment line and code line is both will be there in the same file.But when we run code line will get executed and comment line wont get executed.

Tuesday, 17 November 2020

Elements features of Basic and C programming

Elements features of Basic and C programming:

BASIC Language Features:

BASIC a programming language which is abbreviated as Beginners All Purpose Symbolic Instruction Code,  is the Simplest and high level programming language.


 The language used in BASIC is very simple English, which can be easily programmed by anyone.
 
 BASIC a programming language designed in 1964, by John G. Kemeny and Thomas E. Kurtz  at Dartmouth College in the U.S. state of New Hampshire.
 This programming language is widely used because it is easy to learn  and it supported by most  operating systems.


 
It was the principal programming language during the 1970s taught to students,

As it is simple, BASIC language is used for a wide variety of business applications.
There is an ANSI standard for the BASIC programming language.

It allow multi features which are described below.
   

  1.     It is a general-purpose programming languages  
  2.     It is a high-level programming languages
  3.     It allow input from the keyboard.
  4.     It access Menu driven Application.
  5.     It is structured programming language.
  6.     BASIC programming language has Built in Functions.
  7.     BASIC allow User defined functions.
  8.     Subroutine features are available  BASIC language.
  9.     It allows us to  create Loops.
  10.     It contains several System commands.

 

Monday, 21 September 2020

How to get cdata value from xml in java

How to get cdata value from xml in java  | How to read cdata in xml using java


In this article, we are going to discuss XML CDATA which stands for Character Data. which is defined as blocks of text that will not be parsed by the xml parser.

 syntax of cdata in xml:


    <![CDATA[
        characters with markup
        ]]>


Java provides some of the options to parse XML documents. Some of the commonly used  XML parsers for java programming language are as follows:

  1.     DOM Parser  (Document Object Model)
  2.     SAX Parser
  3.     StAX Parser  (Streaming API for XML)
  4.     JAXB

    
let us consider the following xml file cdata.xml

cdata.xml


<?xml version="1.0" encoding="UTF-8"?>
<employee>
  <emp_info id="1">
    <emp_name>
      <first_name>abc</first_name>
      <last_name>xyz</last_name>
    </emp_name>
    <emp_contact_info>
      <address><![CDATA[
        This is the CDATA area.
        You can store special character that are recognize. Ex. '  " & / - < >
        you can specify company address also
        ]]>
      </address>
    </emp_contact_info>
  </emp_info>
</employee>

This is the java program.

XmlCData.java

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

class XmlCData{
    public static String getCharacterDataFromElement(Element e) {
        NodeList list = e.getChildNodes();
        String data;

        for(int index = 0; index < list.getLength(); index++){
            if(list.item(index) instanceof CharacterData){
                CharacterData child = (CharacterData) list.item(index);
                data = child.getData();

            if(data != null && data.trim().length() > 0)
                return child.getData();
        }
    }
    return "";
  }
}


JavaXmlCdata .java


public class JavaXmlCdata {    
    public static void main(String[] args) throws Exception{
        File file = new File("D:\\cdata.xml");
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = builder.parse(file);
        
        NodeList nodes = doc.getElementsByTagName("emp_contact_info");
        
        for (int i = 0; i < nodes.getLength(); i++) {
      
            Element element = (Element) nodes.item(i);
            NodeList title = element.getElementsByTagName("address");
            Element line = (Element) title.item(0);
            System.out.println("Cdata is  " + XmlCData.getCharacterDataFromElement(line));
    }
  }
}


Monday, 7 September 2020

Write a note on compiling and executing a Java program

 Write a note on compiling and executing a Java program


First, we have to open a text file using notepad or any text editor and then write the java program and then save this java program by any name with extention java example <anyname.java>.
Now compile the java program and then run the java program.

Compilation process of java using command prompt:

  •    open command prompt
  •    goto the place where java program is saved.
  •    now type below command

                d:\> javac   <filename>.java


If no compilation errors are there then we get .class file which consists of bytecode.
Once after sucess compilation we have to run the java program

Process of running the java program using command prompt:

  •      d:\> java <file name>

    
     name of the file which consists of main method and main method should be public static void main(String args[]).
 This bytecode gets interpreted on different machines.

Java virtual machine (JVM) is responsible for allocating memory space.

Friday, 4 September 2020

The add values of matrix horizontally with another vertically

 Java program which will add the values of 2d matrix horizontally with another 2d matrix vertically

import java.util.*;
class MatrixAddition{
    public static void main(String args[]){
    int matrix1[][]=new int[2][2];
    int matrix2[][]=new int[2][2];
    int res_matrix[][]=new int[2][2];
    int i, j;
   Scanner sc=new Scanner(System.in);

    // reading the elements of first matrix
    System.out.println(" enter elements of first matrix ");
    for( i=0; i<2 ;i++){
        for(j=0;j<2;j++){
            matrix1[i][j]=sc.nextInt();
        }
    }

    // reading the elements of second matrix
    System.out.println(" enter the elements of second matrix ");
    for( i=0; i<2; i++){
        for(j=0; j<2; j++){
            matrix2[i][j]=sc.nextInt();
        }
    }

    // adding two  matrices`
    for( i=0; i<2; i++){
        for (j=0; j<2; j++){
            res_matrix[i][j]= matrix1[i][j] + matrix2[j][i];
        }
    }

    // printing the resultant matrix  
    System.out.println(" the resultant matrix is  \n");
    for (i=0; i<2; i++){
        for( j=0; j<2; j++){
            System.out.print(res_matrix[i][j]+" ");
        }
        System.out.println("");
    }
  }
}

Wednesday, 2 September 2020

Java program for finding double letter sequence word in Java

 

 

 

 

Java program for finding double letter sequence word in Java

Double-letter words:

   These are the words which contain atleast one set of characters used twice consecutively.

 For example:
    add,all, bee, boo, ebb, ell, egg, fee, goo, tee, too,  see.


import java.util.*;
class DoubleSequenceWord{
    public static void main(String args[]){
    Scanner sc=new Scanner(System.in);
    System.out.println("enter a word to check whether it is double sequence or not");
    String str=sc.nextLine();
    int count=0;
        for(int i=0;i<str.length()-1;i++){
            if(str.charAt(i)==str.charAt(i+1)){
                count++;
                break;
            }
        }
        if(count>0)
            System.out.println("It is a double sequence word");
        else
            System.out.println("It is a not a double sequence word");

   }

}
       

Saturday, 29 August 2020

Java program to find heat capacity

 Java program to find heat capacity


import java.util.*;
class HeatCapacity{
    public static void main(String args[]){
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter amount of heat transferred (in joules)");
        float heat=sc.nextFloat();
        System.out.println("Enter rise (difference) in temperature");
        float temperature=sc.nextFloat();
    
        System.out.println("Amount of heat supplied "+heat);
        System.out.println("Rise in temperature "+temperature);
         float heatCapacity;
         heatCapacity = heat/temperature;


        System.out.println("Heat Capacity = "+heatCapacity+"j/c");
    
    
        }
}