0% found this document useful (0 votes)
95 views54 pages

Java Assignment

1. The document contains 15 questions about Java programming concepts like encapsulation, data types, methods, classes, inheritance, polymorphism and abstraction. 2. Code snippets are provided as examples to demonstrate how to implement each concept in Java with sample inputs and outputs. 3. The concepts covered include encapsulation, data types, methods to find prime numbers, Armstrong numbers, sorting arrays, finding min/max numbers, string manipulation, wrapper classes and more.

Uploaded by

Geny Many
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
95 views54 pages

Java Assignment

1. The document contains 15 questions about Java programming concepts like encapsulation, data types, methods, classes, inheritance, polymorphism and abstraction. 2. Code snippets are provided as examples to demonstrate how to implement each concept in Java with sample inputs and outputs. 3. The concepts covered include encapsulation, data types, methods to find prime numbers, Armstrong numbers, sorting arrays, finding min/max numbers, string manipulation, wrapper classes and more.

Uploaded by

Geny Many
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 54

JAVA Assignment

Q.1 Write a program that implements the concept of


Encapsulation.

CODE –
class Sub {
void sum() {
int a, b, c;
a = 10;
b = 20;
c = a + b;
System.out.println("\n*** Concept of Encapsulation ***\n");
System.out.println("a = " + a + ", b = " + b);
System.out.println("Sum of a and b : " + c);
}
}
public class Assignment1 {
public static void main(String[] args) {
Sub object = new Sub();
object.sum();
}
}

OUTPUT -
JAVA Assignment

Q.2 Write a program that use Boolean data type and print the
Prime number series up to 50.

CODE -
public class Assignment2 {
public static void main(String[] args) {
boolean b = true;
System.out.println("*** Prime Number series upto 50 ***\n");
System.out.println("Prime numbers - ");
for(int i =1; i<=50;i++)
{
b = true;
for(int j =2;j<=i/2;j++){
if(i%j==0)
{
b = false;
}
}
if(b)
System.out.print( i + " ,");
}
}
}
OUTPUT -
JAVA Assignment

Q.3 Write a program to check the given number is Armstrong


number or not.

CODE –

import java.util.Scanner;
import java.lang.Math;
public class Assignment3 {
static boolean isArmstrong(int n) {
int temp, digits = 0, last = 0, sum = 0;
temp = n;
while (temp > 0) {
temp = temp / 10;
digits++;
}
temp = n;
while (temp > 0) {
last = temp % 10;
sum += (Math.pow(last, digits));
temp = temp / 10;
}
if (n == sum)
return true;
else
return false;
}
public static void main(String args[]) {
int num;
Scanner sc = new Scanner(System.in);
JAVA Assignment

System.out.println("*** Check given number is Armstrong or not ***\n");


System.out.print("Enter the number: ");

num = sc.nextInt();
if (isArmstrong(num)) {
System.out.print("Armstrong number");
} else {
System.out.print("Not Armstrong number");
}
sc.close();
}
}

OUTPUT –
JAVA Assignment

Q.4 Write a program to sort the elements of One-Dimensional


Array in ascending order.

CODE -
public class Assignment4 {
public static void main(String[] args) {
int arr[] = { 7, 8, 3, 1, 2 };
System.out.println("Before the sorting : ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println("\nAfter sorting :");
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
JAVA Assignment

OUTPUT –
JAVA Assignment

Q.5 Write a Java method to find the smallest number among three
numbers.

CODE –

public class Assignment5 {


public static void main(String[] args) {
int x = 110, y = 70, z = 169;
System.out.println("*** find the greatest number betweenn three numbers ***\
n");
System.out.println("x = " + x + ", y = " + y + ", z = " + z);
if (x <= y) {
if (x <= z)
System.out.println("The smallest number is: " + x);
else
System.out.println("The smallest number is: " + z);
} else {
if (y <= z)
System.out.println("The smallest number is: " + y);
else
System.out.println("The smallest number is: " + z);
}
}
}
OUTPUT –
JAVA Assignment

Q.6 Write a Java method to count all words in a string.

CODE –
import java.util.Scanner;
public class Assignment6 {
static int wordcount(String string) {
int count = 0;
char ch[] = new char[string.length()];
for (int i = 0; i < string.length(); i++) {
ch[i] = string.charAt(i);
if (((i > 0) && (ch[i] != ' ') && (ch[i - 1] == ' ')) || ((ch[0] != ' ') && (i == 0)))
count++;
}
return count;
}
public static void main(String[] args) {
System.out.println("*** count all words in a string ***\n");
System.out.println("Ente few words : -");
Scanner sc = new Scanner(System.in);
String string = sc.nextLine();
System.out.println(wordcount(string) + " words.");
sc.close();
}
}
OUTPUT –
JAVA Assignment

Q.7 Write a Java method to count all vowels in a string.

CODE –

public class Assignment7 {


public static void main(String[] args) {
int vCount = 0;
String str = "This is my area.";
str = str.toLowerCase();
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i' || str.charAt(i) ==
'o'
|| str.charAt(i) == 'u') {
vCount++;
}
}
System.out.println("*** Write a Java method to count all vowels in a string ***\
n");
System.out.println("sentence: " + str);
System.out.println("Number of vowels: " + vCount);
}
}
OUTPUT -
JAVA Assignment

Q.8 Write a Java method to compute the sum of the digits in an


integer.

CODE -
import java.util.Scanner;

public class Assignment8 {


public static void main(String[] args) {
int number,digit,sum=0;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number : ");
number = sc.nextInt();
while(number>0){
digit = number %10;
sum = sum+digit;
number = number/10;
}
System.out.println("sum of digit : "+sum);
sc.close();
}
}
OUTPUT -
JAVA Assignment

Q.9 Write a Java method to check whether an year entered by the


user is a leap year or not.

CODE -

import java.util.Scanner;

public class Assignment9 {


public static void main(String[] args) {
int year;
System.out.println("*** Entered year is a leap year or not ***\n");
System.out.print("Enter an Year :: ");
Scanner sc = new Scanner(System.in);
year = sc.nextInt();
if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0))
System.out.println("Specified year is a leap year");
else
System.out.println("Specified year is not a leap year");
sc.close();
}
}

OUTPUT -
JAVA Assignment

Q.10 Write a Java method to check numbers is palindrome


number or not.

CODE -

public class Assignment10 {


public static void main(String args[]) {
int r, sum = 0, temp;
int n = 454;
System.out.println("*** check numbers is palindrome number or not ***\n");
System.out.println("Number :: " + n);
temp = n;
while (n > 0) {
r = n % 10;
sum = (sum * 10) + r;
n = n / 10;
}
if (temp == sum)
System.out.println("palindrome number ");
else
System.out.println("not palindrome");
}
}
OUTPUT –
JAVA Assignment

Q.11 Write a Java method to displays prime numbers between 1 to


20.

CODE -

public class Assignment11 {


public static void main(String[] args) {
int num = 20, count;
System.out.println("*** prime numbers between 1 to 20 ***\n");
System.out.println("Prime numbers are : -");
for (int i = 1; i <= num; i++) {
count = 0;
for (int j = 2; j <= i / 2; j++) {
if (i % j == 0) {
count++;
break;
}
}
if (count == 0)
System.out.print(i + " , ");
}
}
}
OUTPUT -
JAVA Assignment

Q.12 Write a program to calculate simple interest using the


Wrapper class.

CODE –

import java.util.Scanner;
public class Assignment12 {
public static void main(String args[]) {
float principalAmount, rate, time, simpleIntrest;
Float p, r, t, SI;
Scanner sc = new Scanner(System.in);
System.out.println("*** Simple Intrest using Wrapper class ***\n");
System.out.print("Enter the principal Amount : - ");
principalAmount = sc.nextFloat();
System.out.print("Enter the Rate : - ");
rate = sc.nextFloat();
System.out.print("Enter the Time (in years) : - ");
time = sc.nextFloat();
p = principalAmount;
r = rate;
t = time;
simpleIntrest = (p * r * t) / 100;
SI = simpleIntrest;
System.out.println("Simple Interest is: " + SI);
sc.close();
}
}
JAVA Assignment

OUTPUT -
JAVA Assignment

Q.13 Write a program to calculate area of various geometrical


figures using Abstract class.

CODE –

abstract class cir {


static final float pi = 3.14f;
abstract float area(float x);
}
class circle extends cir {
public float area(float x) {
System.out.println("x - "+x);
System.out.println("pi - "+pi);
float A = pi * x * x;
return A;
}
}
class Assignment13 {
public static void main(String[] args) {
circle obj = new circle();
float z = obj.area(5f);
System.out.println("Area of circle = " + z);
}
}
OUTPUT -
JAVA Assignment

Q.14 Write a program where single class implements more than


one Interfaces and with help of Interface reference variable user
call the method.

CODE –

interface Area{
final static float pi = 3.14f;
float compute(float x , float y);
}
interface RectArea{
int calculate(int i,int w);
}
class Test implements Area, RectArea{
public float compute(float x , float y){
System.out.println("\npi = " +pi+" x = " +x+" y = " + y);
return(pi*x*y);
}
public int calculate(int l, int w){
System.out.println("\nlength = " +l+" width = " +w);
return(l*w);
}
}
public class Assignment14 {
public static void main(String[] args) {
Area A;
RectArea R;
Test T = new Test();
A = T;
JAVA Assignment

System.out.println("Area of circle : " + A.compute(10,20));


R = T;
System.out.println("Area of Rectangle is : " + R.calculate(5, 20));
}
}

OUTPUT –
JAVA Assignment

Q.15 Write a program to illustrate the use of Method Overloading .

CODE –

public class Assignment15 {


static int add(int a, int b) {
System.out.println("a = " + a + " b = " + b);
System.out.print("Addition : - ");
return a + b;
}
static int add(int a, int b, int c) {
System.out.println("\na = " + a + " b = " + b + " c = " + c);
System.out.print("Multiplication : - ");
return a * b * c;
}
public static void main(String[] args) {
System.out.println("*** Method Overloading ***\n");
System.out.println(add(11, 11));
System.out.println(add(11, 11, 11));
}
}

OUTPUT –
JAVA Assignment

Q.16 Write a program to illustrate the use of Method Overriding .

CODE –

class Vehicle {
void run() {
System.out.println("In childwood TMKOC was my fav TV serial. s");
}
}
class Bike extends Vehicle {
void run() {
System.out.println("Now OTT platform web series is my fav .");
}
public static void main(String args[]) {
System.out.println("*** Method Overriding Program ***\n");
Bike obj = new Bike();
obj.run();
}
}

CODE -
JAVA Assignment

Q.17 Write a program program to demonstrate the concept of


Constructor Overloading.

CODE –

public class Assignment17 {


int id;
String name;
int age;
Assignment17(int i,String n){
id = i;
name = n;
}
Assignment17(int i,String n , int a){
id = i;
name = n;
age = a;
}
void display(){
System.out.println("ID = " +id + "\tName = " + name + " Age = " + age);
}
public static void main(String[] args) {
System.out.println("*** Constructor Oveloading ***\n");
Assignment17 obj1 = new Assignment17(10, "ishwar");
Assignment17 obj2 = new Assignment17(20, "ishwarrr",9);
System.out.println("Before Constructor Oveloading");
obj1.display();
System.out.println("\nAfter Constructor Oveloading");
obj2.display();
JAVA Assignment

}
}

OUTPUT -
JAVA Assignment

Q.18 Write a program to illustrate Single Level Inheritance.

CODE -

class Dad{
String rs = "5 lacks";
void superMethod(){
System.out.println(" (parent class) Dad's properties " + rs);}
}
class Me extends Dad{
String myRs = "2 lacks";
void childMethod(){
System.out.println("My properties " + myRs);
System.out.println("(child class) I can access my Dad's all properties.");}
}
class Assignment18{
public static void main(String args[]){
System.out.println("*** Single Inhertance Example ***\n");
Me obj=new Me();
obj.childMethod();
obj.superMethod();
}}
OUTPUT -
JAVA Assignment

Q.19 Write a program to illustrate Multi-Level Inheritance.

CODE –

class Vechicle {
void VechicleTypes() {
System.out.println("There are many types of Vechicle : - \n Cars , bikes , Scooty ,
Trucks , buses");
}
}
class Car extends Vechicle {
String price = "15 lacks to 40 lacks";
void CarsTypes() {
System.out.println("");
System.out.println(" There are many famous cars compaines : ");
System.out.println("Maruti , Tata , XUV , Range Rover , Invova , Toyota.");
}
}
class Invova extends Car {
String myPrice = "15 lacks to 25lacks";
void InvovaCars() {
System.out.println("");
System.out.println("My fav car is Invova and I can Buy it.");
System.out.println("Invova Cars price " + price);
System.out.println("My Bugut " + myPrice);
}
}

public class Assignment19 {


JAVA Assignment

public static void main(String args[]) {


System.out.println("Multilevel Inhertance Example - ");
Invova obj = new Invova();
obj.VechicleTypes();
obj.CarsTypes();
obj.InvovaCars();
}
}

OUTPUT –
JAVA Assignment

Q.20 Write a program to illustrate Hybrid Inheritance.

CODE -

class ParentA {
public void displayA() {
System.out.println("This is ParentA class");
}
}
class ParentB {
public void displayB() {
System.out.println("This is ParentB class");
}
}
class Child extends ParentA {
public void displayA() {
System.out.println("This is Child class A part");
}
}
class GrandChild extends Child {
ParentB b = new ParentB();
public void displayB() {
b.displayB();
System.out.println("This is GrandChild class B part");
}
}
public class Assignment20b {
public static void main(String[] args) {
System.out.println("\n *** Hybrid Inheritance *** \n");
JAVA Assignment

ParentA a = new ParentA();


a.displayA();
Child c = new Child();
c.displayA();
GrandChild gc = new GrandChild();
gc.displayA();
gc.displayB();
}
}

OUTPUT -
JAVA Assignment

Q.21 Write a program to illustrate Hierarchical Inheritance.

CODE –

class Base {
public void display() {
System.out.println("I am Parent class");
}
}
class Derived1 extends Base {
public void display2() {
System.out.println("This is Child1 class");
}
}
class Derived2 extends Base {
public void display3() {
System.out.println("This is Child2 class");
}
}
public class Assignment21 {
public static void main(String[] args) {
System.out.println("\n *** Hierarchical Inheritance *** \n");
Derived1 d1 = new Derived1();
d1.display();
d1.display2();
System.out.println("\n");
Derived2 d2 = new Derived2();
d2.display();
d2.display3();
JAVA Assignment

}
}

OUTPUT -
JAVA Assignment

Q.22 Write a program to implement Interface with suitable


example.

CODE –

interface Bank {
public void user();
public void password();
}
public class Assignment22 implements Bank {
public void user() {
System.out.println("your name - : ishwar nishad");
}
public void password() {
System.out.println("your password - : Ishu@123 ....");
}
public static void main(String[] args) {
System.out.println("\n*** Interface Program ***\n");
System.out.println("Show my Bank Details : - \n");
Assignment22 obj = new Assignment22();
obj.user();
obj.password();
}
}
JAVA Assignment

OUTPUT -
JAVA Assignment

Q.23 Write a program to implement Multiple Interface in a single


class.

CODE –

interface Printable {
void print();
}
interface Showable {
void Show();
}
public class Assignment23 implements Printable, Showable {
public void print() {
System.out.println("called Method of Interface 1");
}
public void Show() {
System.out.println("called Method of Interface 2");
}
public static void main(String[] args) {
Assignment23 obj = new Assignment23();
System.out.println("\n*** Multiple Interface Example ***\n");
// System.out.println("multiple interface example");
obj.print();
obj.Show();
System.out.println();
}
}
JAVA Assignment

OUTPUT –
JAVA Assignment

Q.24 Write a program to extend one Interface to another Interface.

CODE –

interface Shape {
double getArea();
}
interface Colorable extends Shape {
void fillColor();
}
class Square implements Colorable {
double side;
String color;
Square(double s, String c) {
side = s;
color = c;
}
public double getArea() {
return side * side;
}
public void fillColor() {
System.out.println("Filling color " + color + " in square");
}
}

public class Assignment24 {


public static void main(String[] args) {
System.out.println("\n *** Extend Interface to another Interface *** \n");
Square s = new Square(6, "Sky Blue");
JAVA Assignment

System.out.println("Area of Square: " + s.getArea());


s.fillColor();
}
}

OUTPUT -
JAVA Assignment

Q.25 Write a program to illustrate thread in java.

CODE –

class file3 extends Thread {


public void run() {
System.out.println("thread class function...");
System.out.println("thread name : "+Thread.currentThread().getName());
System.out.println("thread class name : "+Thread.currentThread().getClass());
}
}
public class Assignment25 {
public static void main(String[] args) throws InterruptedException {
System.out.println("\n **** Thread class Program ***");
file3 obj = new file3();
obj.start();
System.out.println("\nmain class function...\n");
}
}

OUTPUT -
JAVA Assignment

Q.26 Write a program to illustrate Multithreading.

CODE –

class MultiThread1 extends Thread {


public void run() {
System.out.println("Thread 1 class function is called");
for (int i = 0; i < 3; i++) {
System.out.println("thread 1 function : " + i);
}
}
}
class MultiThread2 extends Thread {
public void run() {
System.out.println("Thread 2 class function is called");
for (int i = 0; i < 3; i++) {
System.out.println("thread 2 function : " + i);
}
}
}
public class Assignment26 {
public static void main(String[] args) {
System.out.println("\n*** Multithreading program ***\n");
MultiThread1 obj = new MultiThread1();
obj.start();
MultiThread2 obj2 = new MultiThread2();
obj2.start();
System.out.println("main thread ");
for (int i = 0; i < 3; i++) {
JAVA Assignment

System.out.println(" main thread : "+i);


}
}
}

OUTPUT -
JAVA Assignment

Q.27 Write a program to suspend a thead for some specific time


duration.

CODE –

class MyThread extends Thread {


public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Thread: " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

public class Assignment27 {


public static void main(String[] args) {
System.out.println("\n *** Thread suspend program ***\n");
MyThread t = new MyThread();
t.start();
try {
Thread.sleep(5000);
t.suspend();
System.out.println("Thread suspended for 5 seconds");
JAVA Assignment

Thread.sleep(5000);
t.resume();
System.out.println("Thread resumed");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

OUTPUT –
JAVA Assignment

Q.28 Write a program and use the this and super keyword.

CODE –

class Parent {
int value;
Parent(int v) {
value = v;
}
}
class Child extends Parent {
int value;
Child(int v1, int v2) {
super(v1);
value = v2;
}
public void display() {
System.out.println(" Parent Age: " + super.value);
System.out.println("Child Age: " + this.value);
}
}
public class practical28 {
public static void main(String[] args) {
System.out.println("\n *** super and this keyword *** \n");
Child c = new Child(50, 30);
c.display();
}
}
JAVA Assignment

OUTPUT -
JAVA Assignment

Q.29 Write a program to create a packege and use it in your


program.

CODE :-

Creating Package
//Package Name
package practical29p;
public class Demo {
public void show() {
System.out.println("Hi Everyone");
}
public void view() {
System.out.println("Hello");
}
}
Import Package

import practical29p.Demo;
public class Practical29b {
public static void main(String arg[]) {
Demo d = new Demo();

d.show();
d.view();
}
}
JAVA Assignment

Output :-
JAVA Assignment

Q.30 Write a program to read data from using java i/o package
(using character class).

CODE –

import java.io.*;

public class ReadFile {


public static void main(String[] args) {
System.out.println("\n *** Read data using character class *** \n");
System.out.println("Data - :");
try{
FileReader obj = new FileReader("ishwar.txt");
try{
int i;
while( (i=obj.read())!=-1){
System.out.print((char)i);
}
}
finally{
obj.close();
}
}
catch(IOException e){
System.out.println("Exception handled");

}
JAVA Assignment

}
}

OUTPUT –
JAVA Assignment

Q.31 Write a program to write data into using java i/o


package(using character class).

CODE –

import java.io.FileWriter;
import java.io.IOException;

public class MyFile {


public static void main(String[] args) throws IOException {
System.out.println("\n *** Write data in file using character class *** \n");
FileWriter obj = new FileWriter("FirstFile.txt");

obj.write("Assignment no . 31");
obj.write(" by - ishwar nishad");
System.out.println("file created successfully ...");
obj.close();
}
}

OUTPUT -
JAVA Assignment

Q.32 Write a program to read data from using java i/o package
(using byte class).

CODE –

import java.io.FileInputStream;
public class Assignment32 {
public static void main(String args[]){
System.out.println("\n *** Read data using Byte Class *** \n");
System.out.println("data : - ");
try{
FileInputStream fin=new FileInputStream("ishwar.txt");
int i=0;
while((i=fin.read())!=-1){
System.out.print((char)i);
}
fin.close();
}catch(Exception e){System.out.println(e);}
}
}

OUTPUT –

Q.33 Write a program to write data into using java i/o


package(using byte class).
JAVA Assignment

CODE –

import java.io.*;

class Assignment33 {
public static void main(String[] args)
throws IOException
{
int i;
FileOutputStream obj = new FileOutputStream("ishwar2.txt",true);
String st = "Ishwar is writing in me";
char ch[] = st.toCharArray();
for (i = 0; i<st.length(); i++) {
obj.write(ch[i]);
}
System.out.println("\n *** Write in file using Byte class *** \n");
System.out.println("written successfully ...");
obj.close();
}
}
JAVA Assignment

OUTPUT –

Q.34 Write a program to read and write data in a single program


using java i/o package.
JAVA Assignment

CODE –

import java.io.*;
import java.util.*;

public class Assignment34 {


public static void main( String args[])
{
try {
BufferedReader obj = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter few lines : - ");
String str = obj.readLine();
FileWriter obj2=new FileWriter("ishwar3.txt");
obj2.write(str);
System.out.println("Writing successful");
obj2.close();
System.out.println();
File file = new File("ishwar3.txt");
Scanner scn = new Scanner(file);
while (scn.hasNextLine())
System.out.println(scn.nextLine());
System.out.println("Reading successful");

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

}
}
}

OUTPUT –

Q.35 Write a program to JDBC Connectivity.

CODE -
JAVA Assignment

import java.sql.*;
import java.util.*;

Assignment36{
public static void main(String a[])
{

String url = "jdbc:oracle:thin:@localhost:1521:xe";


String user = "system";
String pass = "2003";
Scanner obj = new Scanner(System.in);
System.out.println("enter first name");
String Firstname = obj.next();
System.out.println("enter last name");
String LastName = obj.next();

String sql = "insert into student1 values('" + FirstName + "'," +


LastName + "')";
Connection con = null;
try {
DriverManager.registerDriver(
new oracle.jdbc.OracleDriver());
con = DriverManager.getConnection(url, user,
pass);
Statement st2 = con.createStatement();
int obj2 = st2.executeUpdate(sql);
JAVA Assignment

if (obj2 == 1)
System.out.println("successfully inserted : " + sql);
else
System.out.println("insertion operation is failed");
con.close();
}
catch (Exception ex) {
System.err.println(ex);
}
}
}

OUTPUT –

You might also like