[go: up one dir, main page]

0% found this document useful (0 votes)
451 views59 pages

Java - A Complete Practical Solu - Swati Saxena

java basics

Uploaded by

pradeep
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
451 views59 pages

Java - A Complete Practical Solu - Swati Saxena

java basics

Uploaded by

pradeep
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 59

JAVA

A complete Practical Solution

By

Swati Saxena
FIRST EDITION 2018
Copyright © BPB Publications, INDIA
ISBN :978-93-88176-50-7

All Rights Reserved. No part of this publication can be stored in a retrieval


system or reproduced in any form or by any means without the prior written
permission of the publishers.

LIMITS OF LIABILITY AND DISCLAIMER OF WARRANTY


The Author and Publisher of this book have tried their best to ensure that the
programmes, procedures and functions described in the book are correct.
However, the author and the publishers make no warranty of any kind,
expressed or implied, with regard to these programmes or the documentation
contained in the book. The author and publisher shall not be liable in any event
of any damages, incidental or consequential, in connection with, or arising out
of the furnishing, performance or use of these programmes, procedures and
functions. Product name mentioned are used for identification purposes only
and may be trademarks of their respective companies.

All trademarks referred to in the book are acknowledged as properties of their


respective owners.

Distributors:
BPB PUBLICATIONS

20, Ansari Road, Darya Ganj

New Delhi-110002

Ph: 23254990/23254991

DECCAN AGENCIES

4-3-329, Bank Street,


Hyderabad-500195

Ph: 24756967/24756400

BPB BOOK CENTRE

376 Old Lajpat Rai Market,

Delhi-110006

Ph: 23861747

MICRO MEDIA

Shop No. 5, Mahendra Chambers,

150 DN Rd. Next to Capital Cinema,

V.T. (C.S.T.) Station,

MUMBAI-400 001

Ph: 22078296/22078297
 
 
 
 
Published by Manish Jain for BPB Publications, 20, Ansari Road, Darya Ganj,
New Delhi-110002 and Printed by Repro India Pvt Ltd, Mumbai
Preface

This book helps you to understand each and every topic of java
practically.
It will help you in developing software and websites because one
should have sound practical knowledge.
It covers all the topics which are important from the point of view
of the interview, certification and examinations and no topic is left
untouched.
This is a complete practical book.
This book has been written after a long experience .
Despite the fact that ample care has been taken, the possibility of
minor inaccuracies cannot be ruled out.
So, if any, your suggestions are highly solicited.
Lastly, Thanks to all thestudents who believe in me.
 
Swati Saxena
Acknowledgement

I am thankful of the BPB publication who inspire me and asked me to


work on this book “Java-A complete Practical Solution”.
I thank Prof. S.C. Saxena, Ex-Principal, Maharishi Arvind Institute
of Technology, Jaipur, who inspire me time to time. I thank Mr.
Naveen Saxena for his constant support during the preparation of
this book.I am thankful of Prof. Nidhi Saxena, Ex-Assistant
professor PESIT University, Banglore for her guidance and support.
Lastly, I thank the management, editorial and production staff of
BPB publication, New Delhi for bringing out this book in record time.
Table of Contents

History in Brief
Magic Code : Bytecode
Operators in java
Java Comment
Java Control Statement
Iteration / Looping
Array
Object and classes
Constructor
Static
“This”Keyword
Final Keyword
Java Regular Expressions (RegeX)
String
Instanceof
Inner Class
Inheritance
Super
Overriding
Abstraction
Abstract Class
Interface
Exception
The try-with- resource statement
Package
Collection and Generics
Applet
Life Cycle of Java Applet
AWT package
Adapter Class
Multhreading
Networking
File Handling ( IO package)
Serialization
Java Advance
Swing
JApplet
JDBC
Servlet
JSP
Extra Efforts
RMI , Border in Swing Component , LookAndFeel etc
Some Interview Question based on practical and Theory
HISTORY IN BRIEF:

Java is a general purpose, class based, object oriented, platform


independent, portable, architecturally neutral, multithreaded,
dynamic, distributed, portable, and robust interpreted programming
language.
Java was originally designed for interactive television, but it was
too advanced technology for the digital cable television industry at
the time.
Java was started as a green project by James Gosling , Patrick
Naughton, Chris Warth, Mike Sheridan, and Ed Frank at Sun
Microsystem in June 1991.
Team members of green project starts this project to develop a
language for digital devices such as set-top boxes, televisions, and
so on. But, it was suited for internet programming.
Firstly it was called as GreenTalk . language was initially called
oak but was renamed as Java in 1995. It made the promise of Write
Once, Run Anywhere, with free runtimes on popular platforms.
It was fairly secure and its security was configurable, allowing for
network and file access to be limited.
KeyPoints

: Java is an island of Indonesia where the first coffee was produced


(called java coffee).
• Java is just a name not an acronym.
• It was developed by James Gosling and team at Sun
Microsystems (which is now a subsidiary of Oracle Corporation)
and released in 1995.
• 1st version was JDK 1.0.
Versions of Java:
• JDK 1.0 (Januar1996)
•   JDK 1.1 (February 19, 1997)
•   J2SE 1.2 (December 8, 1998)
• J2SE 1.3 (May 8, 2000)
• J2SE 1.4 (February 6, 2002)
• J2SE 5.0 (September 30, 2004)
• Java SE 6 (December 11, 2006)
• Java SE 7 (July 28, 2011)
• Java SE 8 (March 18, 2014)
• Java SE 9 (September 21, 2017)
• Java SE 10 (March 20, 2018)
MAGIC CODE : BYTECODE:

Java Byte Code is the language to which Java source is compiled and
the Java Virtual Machine understands. Unlike compiled languages that
have to be specifically compiled for each different type of computers, a
Java program only needs to be converted to byte code once, after
which it can run on any platform for which a Java Virtual Machine
exists.
Bytecode is a set of instruction designed to be executed by the java
run time system, which is called JVM.
JVM is an interpreter of bytecode.
Features of Java:
✓ Simple
✓ Secure
✓ Platform Independent
✓ Object Oriented
✓ Robust
✓ Portable
✓ Dynamic
✓ Multithreaded
✓ Compiled and interpreted
both ✓ Supports networking

✓ High Performance
✓ Distributed
✓ Architecture Neutral

Requirement for Java Example


For executing any java program, you need to,
o install the JDK if you don’t have installed it, o set path of the
download the JDK and install it. jdk/bin directory.
o create the Java program.
o compile and run the Java program
For basic, looping, conditional question, and example please
refer : “C Programming and Coding, Question Bank with
Solution by swati saxena (BpB)”
1. Write a simple java program to print a message?
class First

{
public static void main(String [] arg)
{
System.out.println(“Welcome to Swati Computers”);
}
}
Save it as : First.java
Compile: C:\>javac First.java (it will create a First.class file that
contains bytecode)
Run: c:\> java First
Keywords in java:
Data Types in Java:
Data types represent the different values to be stored in the variable. In
java, there are two types of data types:
o Primitive data types
o Non-primitive data types
Datatype
 
1. Primitive
  A) Boolean
boolean
  B) Numeric
Character
char
Integeral
Integer
byte
short
int
long
Floating point
float
double
2. Non primitive
A) String
B) Array
C) etc.
Types of Variable:
There are three types of variables in Java:
o local variable
o instance variable
o static variable
2. Write a Java program to interchange values of two variable
without using any third variable?
class Swap

{
public static void main(String [] arg)
{
int a=2,b=3;
a=a+b;
b=a-b;
a=a-b;
System.out.println(“A=”+a+”\nb=”+b);
}
}
3. Write a Java program to check whether main() function can
overload or not?
class Overload

{
public static void main(Integer [] aq)
{
System.out.println(“hi”);
}
public static void main(String [] ar)
{
System.out.println(“Hello”);
}
}
4. Write a program to input length and breadth of rectangle and
calculate the area ( Input through command line argument)?
class Rect_area

{
public static void main(String [] aa)
{
int length= Integer.parseInt(aa[0]);

int breath= Integer.parseInt(aa[1]);

int area=length*breath;
System.out.println(“the output is “+area);
}
}

5. Write a program to input total money and check how many of two
thousand, five hundred, hundred, fifty, twenty, ten, five rupee note
we need?
import java.util.*;

class notes

{
public static void main(String [] ar)
{
int thousand_2,hundred_5,hundred_1,fifty,ten,five,note;

Scanner sc=new Scanner(System.in);


System. out.println(“Enter Rupees”);

note=sc.nextInt();
thousand_2=note/2000;
note=note%2000;
hundred_5=note/500;
note=note%500;
hundred_1=note/100;
note=note% 100;
fifty=note/50;
note=note%50;
ten=note/10;
note%=10;
five=note/5;
note=note%5;
System.out.println(“We need \n2000rs note:”+thousand_2+”\
n500rs note:”+hundred_5+”\n100rs note:”+hundred_1+”\n50rs
note:”+fifty+”\n10rs note:”+ten+”\n5 rs note:”+five+”\nextra:”+note);}
}

6. Write a program to calculate the simple interest (input through


command-line)?
class SI

{
public static void main(String [] aa)
{
int principal= Integer.parseInt(aa[0]);

int time= Integer.parseInt(aa[1]);

double rate=Double.parseDouble(aa[2]);

double si=(principal*time*rate)/100;
System.out.println(“the SI is “+si);
}
}

7. Write a program to input the name and age of a person and print
(input through Scanner class)?

import java.util.*;

class inp
{
public static void main(String [] ar)
{
Scanner sc; //reference variable

sc=new Scanner(System.in);//object

String name;
String lname;

int age,i,count=0;
System.out.println(“enter ur name”);

name=sc.next();
System.out.println(“enter last name”);

lname=sc.next();
System. out.println(“enter age”);
age=sc.nextInt();
System. out.println(“Age:”+age);
System. out.println(“Hello “+name);

int len=name.length()+lname.length();

System. out.println(len);
}
}

8. Write a program to input name and course of student and assign it


in other class with object and function? (use two classes)
//import java.util.*;

class Stu

{
String n,cou;

java.util.Scanner sc;
public void read()
{
sc=new java.util.Scanner(System.in);
System.out.println(“Enter name and course”);
n=sc.next();
cou=sc.next();
}
public void inp(String n,String course)
{
this.n=n;
cou=course;
}
public String name()
{
return n;
}
public void disp()
{
System.out.println(“Hello “+n+” u r doing “+cou);

}
}
class Stu_demo

{
public static void main(String [] sd)
{
Stu p=new Stu();
//p.read();
p.inp( "swati" , "java" ); p.disp();
System.out.println(“bye “+p.name());
}
}

9. Write a program to input number using buffered reader?


import java.io.*;
class Inp

{
public static void main(String [] arg) //throws IOException

{
int n;
try{
BufferedReader br=new BufferedReader(new

InputStreamReader(System.in));
System.out.println(“enter a no”);

n=Integer.parseInt(br.readLine());
System.out.println(“u input :”+n);
}
catch(IOException e)
{
System.out.println(“err”);
}
System.out.println(“byeee.”);
}
}
10. Write a program to input name and print length of name?
import java.util.*;

class inp

{
public static void main(String [] ar)
{
Scanner sc; //reference variable

sc=new Scanner(System.in);//object

String name;
String lname;
System.out.println(“enter ur name”);

name=sc.next();
System.out.println(“enter last name”);

lname=sc.next();
System. out.println(“Hello “+name);

int len=name.length()+lname.length();

System.out.println(len);
}
}

11. Write a program to input three numbers and print their addition
(using command line)?
class Nums
{
public static void main(String [] aa)
{
int sum=0;
int a= Integer.parseInt(aa[0]);

int b= Integer.parseInt(aa[1]);

int c= Integer.parseInt(aa[2]);

sum=a+b+c;
System.out.println(“the output is “+sum);
}
}
OPERATORS IN JAVA:

1. Arithmetic Operators: +, -, *, /, %
2. Unary Operators: ++, --
3. Assignment Operators : =
4. Relational Operators: <, >, <=, >=
5. Comparision operator: ==
6. Logical Operators : &&, ||, !
7. Ternary Operators : (condition )? True statement : false
statement
8. Bitwise Operators : &, |, ^
9. Shift Operators: << , >>, >>>
10. Compound asssignment: +=, - =, *=, /=, %=

11. Write a program to implement unary operator?


class UnaryExample{
public static void main(String args[])
{
int x=10;
System.out.println(x++);//10 (11)
System.out.println(++x);//12
System.out.println(x--);//12 (11)
System.out.println(--x);//10
}
}

12. Write a program to fin d minimum out of two numbers using


ternary operator?
class OperatorExample

{
public static void main(String args[])
{
int a=2;

int b=5;
int min=(a<b)?a:b;

System.out.println(min);
}
}
JAVA COMMENT:

Comments are non executable code. They can be used to provide


information or explanation about the variable, method, class, or
any statement.
Types of Java Comments:
There are 3 types of comments in Java:
Single Line Comment: //
Multi Line Comment: /*-------*/
Documentation Comment: /**------*/
  Control statement

1. If- else

Syntax:
if (expression1)
{
    // codes
}
else if(expression2)
{
// codes
}
else if (expression3)
{
    // codes
}
.
.
else
{
    // codes
}

2. Switch case
Syntax:
switch (variable/expression)

{
case value1:
// statements break;
case value2:
// statements
break;
.. .. ...
.. .. ...
default:
// statements
}
13. Write a Java program to check whether two String variable are equal
or not?
{ class String_Demo
public static void main(String []

ar) {
String a,b=”hi”;

a=ar[0];
System.out.println(“address of a:”+a.hashCode());
System.out.println(“address of b:”+b.hashCode());
 
if(a==b)
System.out.println(“equal”);
else
System.out.println(“not equal”);
if(a.equals(b))
System.out.println(“equal”);
else
System.out.println(“not equal”);
String c=new String(“sub”);
String s=new String(b);
System.out.println(“address of c:”+c.hashCode());
System.out.println(“address of s:”+s.hashCode());
if(a==c)
System.out.println(“equal”);
else
System.out.println(“not equal”);

if(a.equals(c))
System. out.println(“equal”);

else
System. out.println(“not equal”);
}
}
14. Write a program to fin d out maximum out of three?
public class JavaExample

{
public static void main(String[] args)
{
int num1 = 10, num2 = 20, num3 = 7;
if( num1 >= num2 && num1 >= num3)

System.out.println(num1+” is the largest Number”);


else if (num2 >= num1 && num2 >= num3)

System.out.println(num2+” is the largest Number”);


else
System.out.println(num3+” is the largest Number”);
}
}

15. Write a Java program to display calculated result of numbers


based on the operator entered?

import java.util.Scanner;
 
class Calculator

{
public static void main (String[] args) {
 
char operator;
Double number1,nymber2,result;
 
Scanner scanner = new Scanner(System.in);

System.out.print(“Enter operator (either +, -, * or /): “);


operator = scanner.next().charAt(0);
System.out.print(“Enter number1 and number2 respectively: “);

number1 = scanner.nextDouble();

number2 = scanner.nextDouble();
 
switch (operator) {

case ‘+’:
   result = number1 + number2;
System.out.print(number1 + “+” + number2 + “ = “ + result);
   break;
case ‘-’:
   result = number1 - number2;
   System.out.print(number1 + “-” + number2 + “ = “ + result);
   break;
 
case ‘*’:
   result = number1 * number2;
   System.out.print(number1 + “*” + number2 + “ = “ + result);
   break;
 
case '/':
   result = number1 / number2;
   System.out.print(number1 + “/” + number2 + “ = “ + result);
   break;
 
default:
   System.out.println(“Invalid operator!”);
   break;
}
}
 }
16. Write a program to check whether a given year is leap year or not?

import java.util.Scanner;

class Calculator
{
public static void main(String[] args)
 {
int chk_year;
Scanner scanner = new Scanner(System.in);
System.out.println(“Enter year”);
Chk_year=scanner.nextInt();
 
if ((chk_year % 400) == 0)
System.out.println(“ year”+ chk_year+” is leap year”);

else if ((chk_year % 100) == 0)


System.out.println(chk_year + “ is a not leap year.\n”);

else if ((chk_year % 4) == 0)

System.out.println(chk_year +” is a leap year.”);

else
System.out.println(chk_year + “ is not a leap year”);
}
}

17. Write a program to check whether a given number is positive /


negative or zero?

class Ladder

{
public static void main(String[] args)
{
 
int number = 0;
if (number > 0)
{
System.out.println(“Number is positive.”);
}
else if (number < 0)
{
System.out.println(“Number is negative.”);
}
else
{
System.out.println(“Number is 0.”);
}
}
}

18. Write a program to calculate the amount payable after deducting


the discount on the purchase amount.

Discounts are as follows:

Purchase amount >=8,000Discount=10% on the purchase amount

Purchase amount >=5,000Discount =8% on the purchase amount

Purchase amount >=1,000Discount =4% on the purchase amount

Otherwise          Discount = Rs. 100


import java.util.Scanner;

class Rates
{
public static void main(String[] args)
{
double PR,dis, amount;
Scanner scanner = new Scanner(System.in);

System.out.println(“Enter purchase rate”);

PR=scanner.nextDouble();
 
If(PR>=8000)
dis=PR* .10;
else if(PR>=5000)
dis=PR*.08;
else if(PR>=1000)
dis=PR*.04;
else
dis=100;
 
amount=PR-dis;
System.out.println(“Amount payable after “+ dis+” discount
is “+amount);
}
}
ITERATION/ LOOPING:

A loop statement allows us to execute a statement or group of


statements multiple times.
Java supports 3 type of loops and also enhanced for loop.
1. for loop
Java for loop provides the user to write the whole condition, i.e.
initialization, condition, and increment/decrement in one line.
For(initialization; condition; increment/decrement){}
2. Enhanced for loop
This version was introduced in Java 5, this feature allows you to iterate
with elements of arrays. This feature should only be used when the
index is unknown.
for (T element:Collection obj/array)
{
statement(s)
}
3. While loop
In Java while loop, a loop is continuously executed if the Boolean
condition comes true, it can be considered as a repeating if statement.
While(condition){}
4. Do-while loop
A do while statement is an exit controlled loop, i.e. it checks the
condition after the execution of the loop
do
{statements;}
while(condition);
19. Write a program to count vowels in given name?
import java.util.*;
class Vowels

{
public static void main(String [] ar)
{
Scanner sc; //reference variable

sc=new Scanner(System.in);// object

String name;
Int i,count=0;
 
System.out.println(“enter ur name”);

name=sc.next();
System.out.println(“Hello “+name);
for(i=0;i<name.length();i++)
{
char c=name.charAt(i);
if(c== 'a' | |c== 'e' | |c== 'i' | |c== 'o' | |c== 'u' )
{
count++;
}
System. out.print(c+”:”);
}
System.out.println(“no. of vowels in “+name+” is “+count);
}
}

20. Write a program to validate an email id: it should contain one @


and at least one “.” ?
import java.util.*;
class Scan

{
public static void main(String [] aa)
{
Scanner as= new Scanner(System.in);
String email;
int i,count=0,count1=0;
System.out.println(“ enter the email “);

email= as.next();

int c=email.length();

for(i=0;i<email.length();i++)
{ char k=email.charAt(i);
if(k==’@’)
{
count++;
}
if(k==’.’)
{
count1++;
}
}
if(count==1 &&count1 >0)

{
System.out.println(“valid id”);
}

else
{
System.out.println(“valid id ni h “);
}
}
}

21. Write a program to reverse a given number?


import java.util.Scanner;

class ReverseNumberWhile
{
public static void main(String args[])
{
int num=0;
int reversenum =0;
System.out.println(“Input your number and press enter: “);

Scanner in = new Scanner(System.in);

num = in.nextInt();
//While Loop: Logic to find out the reverse number

while( num != 0 )
{
reversenum = reversenum * 10;

reversenum = reversenum + num%10;

num = num/10;
}
System.out.println(“Reverse of input number is: “+reversenum);
}
}

22. Write a program to calculate factorial of given number?


class FactorialDemo
{
public static void main(String args[])
{
int factorial = fact(4);
System.out.println(“Factorial of 4 is: “+factorial);
}
static int fact(int n)
{
int output;

if(n==1){

return 1;
}
//Recursion: Function calling itself!!

output = fact(n-1)* n;

return output;
}
}

23. Write a program to generate random numbers between 0 to 200?


import java.util.*;
class GenerateRandomNumber
{
public static void main(String[] args)
{
int counter;
Random rnum = new Random();
/* Below code would generate 5 random numbers

* between 0 and 200.


*/
for (counter = 1; counter <= 5; counter++)
{
System.out.println(rnum.nextInt(200));
}
}
}

24. Write a program to print fibonacci series 0,1,1,2,3....N ?


import java.util.Scanner;

class ReverseNumberWhile

{
public static void main(String args[])
{
int num=0;

int i=0,j=1;
System.out.println(“Input your number and press enter: “);

Scanner in = new Scanner(System.in);

num = in.nextInt();

while(i<=num)
{
System.out.println(i);
j=i+j;
i=J-i;
}
}
}

25. Write a program to find first N prime numbers?


import java.util.Scanner;
 
class PrimeNumberDemo

{
public static void main(String args[])
{
int n;
int status = 1;

int num = 3;
//For capturing the value of n
Scanner scanner = new Scanner(System.in);
System.out.println(“Enter the value of n:”);
//The entered value is stored in the var n

n = scanner.nextInt();

if(n >= 1)
{
System.out.println(“First “+n+” prime numbers are:”);
//2 is a known prime number
System.out.println(2);
}
 
for ( int i = 2 ; i <=n ; )
{
for ( int j = 2 ; j <= Math.sqrt(num) ; j++ )
{
if ( num%j == 0 )
{
status = 0;
break;
}
}
if ( status != 0 )
{
System.out.println(num);
i++;
}
status = 1;
num++;
}
}
}

26. Write a program to input Login details:user name and password,


password should not be visible at runtime?

import java.util.*;

import java.io.*;

class Login

{
public static void main(String [] args)
{
String uname,pwd;

char [] p=new char[10];


Scanner sc=new Scanner(System.in);
Console con=System.console();
System.out.println(“Enter user name”);

uname=sc.next();
//uname=con.readLine();
System.out.println(“Enter user password”);
//pwd=sc.next();
p=con.readPassword();
System.out.println(“Hello user :”+uname);

//System.out.println(“U entered Password :”+pwd);


}
}
For pattern and loops example please refer “C programming
and coding question bank with solution”.
ARRAY:

Array is an object that contain elements of the similar data type. We can
store only fixed set of elements in a Java array.
Once defined, the size of an array is fixed and cannot increase to
accommodate more elements.The first element of an array starts with
index zero.
Syntax:
Datatype[] arrname;
arrname=new datatype[size of array];
datatype [][] arrname=new datatype[rows][cols];
Advantages of array:
o Code Optimization: It makes the code optimized, we can retrieve or
sort the data easily.
o Random access: We can get any data located at any index position.

27. Write a program to input five numbers in an array and calculate their
sum and find maximum?
import java.util.*;

class arry1

{
public static void main(String []at)
{
Scanner sc=new Scanner(System.in);

int []a=new int[5];

int i,s=0,max=0;

for(i=0;i<5;i++)
{
System. out.println(“Enter no. ”);
a[i]=sc.nextInt();
s=s+a[i];
if(a[i]>max)

max=a[i];
}
for(i=0;i<5;i++)
{
System.out.println(“a[“ + i + “]=” + a[i]);
}
System.out.println(“Sum =”+s);
System. out.println(“Max=”+max);
}
}

28. Write a program to print different number of columns in a 2-D array?


import java.util.*;

class Arry3

{
public static void main(String []at)
{
Scanner sc=new Scanner(System.in);

int a[][]=new int[][] {


{1,2} ,
{2,3,4} ,
{5,6,9} ,
{8}
};
int i,j;
 
for(i=0;i<a.length;i++)
{
for(j=0;j<a[i].length;j++)
{
//System.out.print(“a[“ + i + “][“+j+”]=” + a[i][j]);
System.out.print(a[i][j]+”\t”);
}
System.out.println();
}
}
}

29. Write a program to initialize String array and print it?


import java.util.*;

class arry4

{
public static void main(String []at)
{
Scanner sc=new Scanner(System.in);
String [] col=new String[]{“red”,”green”,”blue”};

int i;
for(i=0;i<col.length;i++)
{
System.out.println(col[i]+” : “+col[i].length());
}
}
}

30. Write a program to print random captcha?


import java.util.*;

class sgn

{
public static void main(String [] aa)
{
Random r= new Random();
 
char [] q1=new char[] {'a','b','c','d','e','i' ,'g','h','i','j','k','l','m','n','o','
P' , 'q' , 'r' , 's' , 't' , 'u ', 'v' , 'w' , 'x' , 'y' , 'z' };
char [] q2=new char[] {‘A’,’ B’,’C ’,'D', E’ ,’F ’ ,’G ’ ,’H ’, 'I’,’J', ’K’,’L’,’
M','N','O’,'P’,'Q',’R’,'S','T','T','v','U’,'v’,'W’,'X’,'Y’,'Z’};
int f=r. nextInt(20);
System.out.print(q2[f ]);

System.out.print(f+100*f+q1[f ]);
System.out.print(q1[f/2]);
}
}

31. Write a program to demonstrate three-dimensional array?


class ThreeD
{
public static void main(string [] arg)
{
int threed [ ] [ ] [ ]==new int [3][4][5];

int i,j,k;

for(i=0;i<3;i++)
for(j=0;j<4;j++)

for(k=0;k<5;k++)

threed[i][j][k]= i * j *k;
 
for(i=0;i<3;i++) {

for(j=0;j<4;j++) {

for(k=0;k<5;k++)
System.out.print(threeD[i][j][k] +” “);

System.out.println();
}
System.out.println();
}
}
}

32. Write a program to demonstrate labeled break?


class Break
{
public static void main(String [] arg)
{
boolean flag=true;
first:{
second:{
third:{
System.out.println(“Before break”);
If(flag) break second; //break out of second block

System.out.println(“this wont’ execute”);


}
System.out.println(“this wont’ execute”);
}
System.out.println(“this is after second block”);
}
}
}
33. Write a program to print triangular multiplication table for 0 to 9?
class Tables

{
public static void main(String [] arg)
{
outer: for(int i=0;i<10;i++){
for(int j=0;j<10;j++){
if(j>i){
System.out.println();
Continue outer;
}
System.out.println(“ “+( i * j));
}
}
System.out.println();
}
}
OBJECT AND CLASSES

Object is a real world entity which has some identity, state,


behaviour.
A class is a group of objects which have common properties. It is
a template or blueprint from which objects are created. It is a logical
entity. It can’t be physical.
A class can have the following:
o fields
o methods
o constructors
o blocks
o nested class and interface
A variable which is created inside the class but outside the
method, is known as instance variable.
Instance variable doesn’t get memory at compile time. It gets
memory at run time when object (instance) is created. That is why, it
is known as instance variable.
The new keyword is used to allocate memory at run time. All
objects get memory in Heap memory area.
First letter of class name in java should be capital ( it is a rule of
java) but if you write it in small there is no error.

34. Write a program to create different classes for student and


employee with methods and fill details?
import java.util.*;

class emp

{
String job;
Scanner sc;
public void inp()
{
sc=new Scanner(System.in);
System. out.println(“enter post”);

job=sc.next();
}
public void put()
{
System.out.println(“u r working as “+job);
}
}
class stu

{
String name;

int age;
Scanner sc;

public void get()


{
sc=new Scanner(System.in);

System.out.println(“Enter name and age”);

name=sc.next();

age=sc.nextInt();
}
public void put()
{
System.out.println(“hello “+name);

System.out.println(“u r “+age+”years old”);


}
}
class stu_demo

{
public static void main(String [] ar)
{
stu s=new stu();

emp e=new emp();


System.out.println(“Enter stu data”);

s.get();
System.out.println(“Enter employee record”);
e.inp();
System.out.println(“Data Input:”);
s.put();
e.put();
}
}

35. Write a program to demonstrate implicit and explicit conversion?


class Explicit
{
public static void main(String [] ar)
{
Object o,o1;
String s = new String(“Hello”);

o = new String(“Hello”);
String t;
t = (String) o;
o1=t;//implicit
}
}

36. Write a program to check whether a given string is palindrome


or not?
import java.util.*;

class count_word

{
public static void main(String [] as)
{
String n;
int i,wc=1,cc=0,space=0,j;

char c,c1;
Scanner sc=new Scanner(System.in);
System.out.println(“Enter a string”);
n=sc.nextLine();
for(i=0;i<n.length();i++)
{
c=n.charAt(i);
if(c==’ ‘)
{
space++;
wc++;
}
}
cc=n.length()-space;
System.out.println(“Total characters in name are” + cc + “\n

Total words are “ + wc);


 
//Palindrome string
 
space=0;
for(i=0,j=n.length()-1;i<n.length()/2;i++,j--)
{
c=n.charAt(i);
c1=n.charAt(j);
if(c!=c1)
{
space=1;
break;
}
}
if(space==0)
System.out.println(“Palindrome string”);

else
System. out.println(“Not”);
}
}

37. Write a program to call methods of a class using anonymous


object?
class Factorial
{
void fact(int n)
{
int fact=1;

for(int i=1;i<=n;i++)
{
fact=fact*i;
}
System.out.println(“factorial is “+fact);
}
public static void main(String args[]){
new Factorial().fact(5);//calling method with anonymous
object
}
}

38. Write a program to calculate the area of rectangle, create


method get() to input values and calculateArea() to calculate
area?
class Rectangle

{
int length;

int width;

void get(int l,int w)


{
length=l;
width=w;
}
void calculateArea()
{
System.out.println(length*width);}
}
class TestRectangle2 {
public static void main(String args[]){
Rectangle r1=new Rectangle(),r2=new Rectangle();//

creating two objects

r1.get(11,5);

r2.get(3,15);

r1.calculateArea();

r2.calculateArea();
}
}

39. Write a program to create a class Account with different


methods like deposit(), withdraw() and operate?
class Account

{
int acc_no;
String name;

float amount;
void open_account(int a,String n,float amt)
{
acc_no=a;
name=n;
amount=amt;
}
void deposit(float amt)
{
amount=amount+amt;
System.out.println(amt+” deposited”);
}
void withdraw(float amt)
{
if(amount<amt)
{
System.out.println(“Insufficient Balance”);
}
else{
amount=amount-amt;

System.out.println(amt+” withdrawn”);
}
}
void checkBalance()
{System.out.println(“Balance is: “+amount);}

void display()
{System.out.println(acc_no+” “+name+” “+amount);}
}
 
class TestAccount{
public static void main(String[] args){
Account a1=new Account();
a1. open_account (212345,”Shweta”,10000);
a1.display();
a1.checkBalance();
a1.deposit(40000);
a1.checkBalance();
a1.withdraw(15000);
a1.checkBalance();
}}
40. Write a program to create set() and get() methods to read/ write
values of student data?
class Student

{
int roll_no;
String course;

void set_roll(int r)
{
Roll_no=r;
}
int get_roll()
{
return (roll_no);
}
void set_course(String c)
{
course=c;
}
int get_course()
{
return(course);
}
public static void main(String [] arg)
{
Student s=new Student();
s.set_roll(101);
s.set_course(“java”);
System.out.println(“Roll no”+s.get_roll()+” doing
“+s.get_course);
}
}
CONSTRUCTOR:

Constructor is a member function of a class. It is called automatically


when an instance of an object is created and memory is allocated for
the object.
It is used to initialize an object.
Every class has at least one constructor called default
constructor.
Keypoints:
o Constructor name is same as class name. o It has no return
type.
o It is called automatically we need not to call explicitly.
o Its overloading is possible means a class can have any number
of constructor with different parameters.
o It can be of two type: default , parameterized

41. Write a program to demonstrate default, parameterized and


copy constructor?

End of this sample Kindle book.

Enjoyed the sample?


Buy Now

or     

See details for this book in the Kindle Store

You might also like