Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
9 views

Java File

Java interview question

Uploaded by

Sweet Cutee
Copyright
© Public Domain
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Java File

Java interview question

Uploaded by

Sweet Cutee
Copyright
© Public Domain
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

Q1 Write a program in java to perform addition/ substraction/

multiplication/ division of two integer number. The value and


operator must be passed as command Line argument.
import java.util.Scanner;

public class Arith {


public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter value for A : ");
int a = s.nextInt();
System.out.print("Enter value for B : ");
int b = s.nextInt();
System.out.print("Enter Operator (+,-,*,/) : ");
char op = s.next().charAt(0);

switch (op) {
case '+':
System.out.println("Result : " + (a + b));
break;
case '-':
System.out.println("Result : " + (a - b));
break;
case '*':
System.out.println("Result : " + (a * b));
break;
case '/':
System.out.println("Result : " + (a / b));
break;
default:
System.out.println("Enter correct operator!");
}
s.close();
}
}

Output:
Enter value for A : 15
Enter value for B : 30
Enter Operator (+,-,*,/) : *
Result : 450
Q2 Write a program in java to sort an integer array in ascending
order.
public class IntArraySort
{
public static void main(String[] args) {
int[] arr1 = {15,7,10,5,21,11};
int i, j, temp;

System.out.print("Original Array -\n{ ");


for(i = 0;i<arr1.length; i++){
System.out.print(arr1[i] + " ");
}
System.out.println("}");

for(j = 0; j < arr1.length; j++){


for(i = j+1; i < arr1.length; i++){

if(arr1[j] > arr1[i]){


temp = arr1[j];
arr1[j] = arr1[i];
arr1[i] = temp;
}
}
}

System.out.print("\nSorted Array -\n{ ");


for(i = 0;i<arr1.length; i++){
System.out.print(arr1[i] + " ");
}
System.out.print("}");
}
}

Output:
Original Array -
{ 15 7 10 5 21 11 }

Sorted Array -
{ 5 7 10 11 15 21 }
Q3 Write a program in java to calculate the total total salary of 5
Employees by using array of Objects.
import java.util.Scanner;

public class TotalEmpSal


{
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
Employee[] emps = new Employee[5];
for (int i = 0; i < 5; i++){
System.out.print("Enter salary of Employee " + (i + 1) + "
: ");
int salary = s.nextInt();
emps[i] = new Employee(i, salary);
}

int totalSalary = 0;
for (int i = 0; i < 5; i++){
totalSalary += emps[i].salary;
}
System.out.println("Total Salary of Employees : " +
totalSalary);
s.close();
}
}

class Employee{
public int id;
public int salary;

Employee (int id, int salary){


this.id = id;
this.salary = salary;
}
}

Output:
Enter salary of Employee 1 : 35000
Enter salary of Employee 2 : 12000
Enter salary of Employee 3 : 15000
Enter salary of Employee 4 : 45000
Enter salary of Employee 5 : 20000
Total Salary of Employees : 127000

Q4 Write a program in java to initialize the instance variable of


Parent class by using Child class constructor.
import java.util.Scanner;

public class ParentChild {


public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter name of child : ");
String child = s.nextLine();
System.out.print("Enter name of parent : ");
String parent = s.nextLine();

Child c1 = new Child(parent, child);


c1.display();
s.close();
}
}

class Parent {
public String parentName;
}

class Child extends Parent {


public String childName;

public Child(String pName, String cName) {


parentName = pName;
childName = cName;
}

public void display() {


System.out.println(childName + " is child of " +
parentName);
}
}
Output:
Enter name of child : Rajiv
Enter name of parent : Mahesh
Rajiv is child of Mahesh

Q5 Write a program in java to perform method overloading and method


overiding.
public class OverridingOverloading{
public static void main(String[] args) {
child c = new child();
c.display();
c.print(16);
c.print("Java!");
}
}

class parent{
void display(){
System.out.println("Parent display function.");
}
}

class child extends parent


{
@Override
void display(){
System.out.println("Child display function.");
}

void print(int num){


System.out.println("Print Number : " + num);
}

void print(String str){


System.out.println("Print String : " + str);
}
}

Output:
Child display function.
Print Number : 16
Print String : Java!

Q6 Write a program in java to demonstrate that String is an


Immuteable object.
public class ImmutableString
{
public static void main(String[] args) {
String s1 = "ok"; //s1 refers to "ok"
String s2 = "ok"; //s2 also refers to "ok"
String s3 = s1; //s3 also refers to "ok"

System.out.println("Before modification -");


System.out.println("s1 and s2 refers to same reference : " +
(s1 == s2));
System.out.println("s1 and s3 refers to same reference : " +
(s1 == s3));
System.out.println("s3 and s2 refers to same reference : " +
(s3 == s2));

s1 = s1.concat(" ready"); // s1 refers to new concatenated


string "ok ready"
s2.concat(" cancel"); // results in new string "ok cancel" but
not referred by any object

System.out.println("After modification -");


System.out.println("s1 and s2 refers to same reference : " +
(s1 == s2));
System.out.println("s1 and s3 refers to same reference : " +
(s1 == s3));
System.out.println("s3 and s2 refers to same reference : " +
(s3 == s2));
}
}

Output:
Before modification -
s1 and s2 refers to same reference : true
s1 and s3 refers to same reference : true
s3 and s2 refers to same reference : true
After modification -
s1 and s2 refers to same reference : false
s1 and s3 refers to same reference : false
s3 and s2 refers to same reference : true

Q7 Write a program in java to implement multiple inheritance using


interface.
public class MultipleInheritance{
public static void main(String[] args){
Rectangle r = new Rectangle(12.5f,4.4f);
r.show();
System.out.println("Area of Rectangle : " + r.compute());
System.out.println();
Circle c = new Circle(3.5f);
c.show();
System.out.println("Area of Circle : " + c.compute());
}
}

interface Area{
public static float PI = 3.142857f;
float compute();
}

class Rectangle implements Area{


float w = 0;
float l = 0;
Rectangle(float width, float length){
w = width;
l = length;
}
void show(){
System.out.println("Width and length of Rectangle : " + w +
", " + l);
}
public float compute(){
return w*l;
}
}

class Circle implements Area{


float r = 0;
Circle(float radius){
r = radius;
}
void show(){
System.out.println("Radius of Circle : " + r);
}
public float compute(){
return PI * (r * r);
}
}

Output:
Width and length of Rectangle : 12.5, 4.4
Area of Rectangle : 55.0

Radius of Circle : 3.5


Area of Circle : 38.5

Q8 Write a program in java to create a package that validates


usernae and password.
File – validation/Validators.java
package validation;

public class Validators {


public static boolean validateUsername(String username) {
if (username == "") {
System.out.println("Error : Username cannot be
blank.");
return false;
} else if (username.length() < 4 || username.length() >
20) {
System.out.println("Error : Username needs to be
between 4 and 20 characters.");
return false;
}
return true;
}

public static boolean validatePassword(String password) {


if (password == "") {
System.out.println("Error : Password cannot be
blank.");
return false;
} else {
if (!password.matches("(?=.*\\d)(?=.*[a-z])(?=.*[A-
Z])(?=.*[^\\w\\s]).{8,}")) {
System.out.println("Error : Password needs,");
System.out.println("* at least one digit,
uppercase and lowercase.");
System.out.println("* at least one symbol (!,
@, #, $, %, ^, &, *).");
return false;
}
if (password.indexOf(" ") != -1) {
System.out.println("Error : Password cannot
contain space");
return false;
}
}
return true;
}
}

File – ValidateUserPass.java
import java.util.Scanner;
import validation.Validators;

public class ValidateUserPass


{
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter Username : ");
String username = s.nextLine();
System.out.print("Enter Password : ");
String password = s.nextLine();

if(!Validators.validateUsername(username)){
System.out.println("\nUsername incorrect!");
}
else if(!Validators.validatePassword(password)){
System.out.println("\nPassword incorrect!");
}
else {
System.out.println("\nCredentials are correct.");
}
s.close();
}
}

Output:
Enter Username : Kailash sharma
Enter Password : admin@11
Error : Password needs,
* at least one digit, uppercase and lowercase.
* at least one symbol (!, @, #, $, %, ^, &, *).

Password incorrect!

Q9 Design a database in Oracle


Structure of database
FieldName s
empId
empName
empDepartment
empSalary

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class JdbcCreate {


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");

Statement stmt = con.createStatement();


stmt.executeUpdate("CREATE TABLE emp (empId number
NOT NULL, empName varchar2(15), empDepartment varchar2(15),
empSalary number, PRIMARY KEY(empId))");

System.out.println("Table created successfully.");


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

Output:
Table created successfully.

Q10 Write a program in java to insert atleast 5 employees details.


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class JdbcInsert {


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");

Statement stmt = con.createStatement();


int count = stmt.executeUpdate("INSERT INTO emp
VALUES(1, 'Raj', 'Sales', 34000)");
count += stmt.executeUpdate("INSERT INTO emp
VALUES(2, 'Rahul', 'CS', 7500)");
count += stmt.executeUpdate("INSERT INTO emp
VALUES(3, 'Vikas', 'Sales', 13000)");
count += stmt.executeUpdate("INSERT INTO emp
VALUES(4, 'Mahinder', 'Sales', 25000)");
count += stmt.executeUpdate("INSERT INTO emp
VALUES(5, 'Atul', 'CS', 30000)");
count += stmt.executeUpdate("INSERT INTO emp
VALUES(6, 'Kailash', 'Sales', 9600)");
count += stmt.executeUpdate("INSERT INTO emp
VALUES(7, 'Vijay', 'Management', 55000)");
System.out.println(count + " rows inserted.");
} catch (Exception e) {
System.out.println(e);
}
}
}

Output:
7 rows inserted.

Q11 Write a program in java to update empSalary by 10% who are in


"CS" Department
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class JdbcUpdate {


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");

Statement stmt = con.createStatement();


int count = stmt.executeUpdate("UPDATE emp SET
empsalary = ((empsalary / 100 * 10) + empsalary) WHERE empdepartment
= 'CS'");

System.out.println(count + " rows updated.");


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

Output:
2 rows updated.
Q12 Write a program in java to delete all the records whose salary
is in between 5000 and 10000.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class JdbcDelete {


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");

Statement stmt = con.createStatement();


int count = stmt.executeUpdate("DELETE FROM emp
WHERE empsalary BETWEEN 5000 AND 10000");

System.out.println(count + " rows deleted.");


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

Output:
2 rows deleted.

Q13 Write a program in java to display all the records whose salary
is greater than 50000 and but not in department "CS".
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class JdbcDisplay {


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");

Statement stmt = con.createStatement();


ResultSet resultSet = stmt.executeQuery("SELECT *
FROM emp WHERE empsalary > 50000 AND empdepartment <> 'CS'");

System.out.println("EMPID\tEMPNAME \
tEMPDEPARTMENT \tEMPSALARY");

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

while (resultSet.next()) {
System.out.printf("%1$s\t%2$-15s\t%3$-15s\t
%4$s\n",
resultSet.getString(1),resultSet.getString(2),resultSet.getString(3)
,resultSet.getString(4));
}
} catch (Exception e) {
System.out.println(e);
}
}
}

Output:
EMPID EMPNAME EMPDEPARTMENT EMPSALARY
-------------------------------------------------
7 Vijay Management 55000

Q14 Create servlet to design Registration Form.

package com.registration;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/register")
public class RegistrationForm extends HttpServlet {

protected void doGet(HttpServletRequest req,


HttpServletResponse res) throws ServletException, IOException {
// TODO Auto-generated method stub

res.setContentType("text/html");

PrintWriter out = res.getWriter();

out.println("<style>.inputfield{width:300px;
display:flex; justify-content:space-between;}</style>");
out.println("<center><form>");
out.println("<div class='inputfield'>First name <input
type='text' name='fname'></div>");
out.println("<div class='inputfield'>Last name <input
type='text' name='lname'></div>");
out.println("<div class='inputfield'>Email <input
type='email' name='email'></div>");
out.println("<div class='inputfield'>Address <input
type='text' name='address'></div>");
out.println("<div class='inputfield'>Password <input
type='password' name='password'></div>");
out.println("<div class='inputfield'>Confirm Password
<input type='password'></div>");
out.println("<div class='inputfield'><input type='submit'
value='submit'></div>");
out.println("</form></center>");

out.close();
}
}

Output:
Q15. Create a Servlet that validates username and password.

package com.validation;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/validate")
public class UserPassValid extends HttpServlet {

protected void doGet(HttpServletRequest req,


HttpServletResponse res) throws ServletException, IOException {
// TODO Auto-generated method stub

res.setContentType("text/html");

PrintWriter out = res.getWriter();


out.println("<style>.inputfield{width:300px;
display:flex; justify-content:space-between;}");
out.println(".btn{width:300px; text-align:right; padding-
top:10px}</style>");
out.println("<center><form action='./validate'
method='post'>");
out.println("<div class='inputfield'>Username <input
type='text' name='username'></div>");
out.println("<div class='inputfield'>Password <input
type='password' name='password'></div>");
out.println("<div class='btn'><input type='submit'
value='submit'></div>");
out.println("</form></center>");

out.close();
}

protected void doPost(HttpServletRequest request,


HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter out = response.getWriter();

String user = request.getParameter("username");


String pass = request.getParameter("password");

if(user.equals("admin") && pass.equals("admin@123"))


{
out.print("<h1>Welcome " + user + " !<h1>");
}else {
out.println("Wrong username or password.");
}
out.close();
}
}

Output:

You might also like