0% found this document useful (0 votes)
189 views19 pages

Java Programming: Data Types & Concepts

This document contains examples of various Java programming concepts including data types, string manipulation, inheritance, polymorphism, exception handling, interfaces, packages, and multithreading. It demonstrates how to declare and initialize variables of different data types, convert strings to characters, reverse strings, implement single, multilevel, hierarchical and multiple inheritance, method overloading and overriding for polymorphism, handle exceptions like arithmetic and file not found, use interfaces, define packages to organize code, and create multiple threads to run tasks concurrently.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
189 views19 pages

Java Programming: Data Types & Concepts

This document contains examples of various Java programming concepts including data types, string manipulation, inheritance, polymorphism, exception handling, interfaces, packages, and multithreading. It demonstrates how to declare and initialize variables of different data types, convert strings to characters, reverse strings, implement single, multilevel, hierarchical and multiple inheritance, method overloading and overriding for polymorphism, handle exceptions like arithmetic and file not found, use interfaces, define packages to organize code, and create multiple threads to run tasks concurrently.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

1.

Various Data Types

import [Link].*;
import [Link].*;
import [Link].*;

class DataTypes{
public static void main(String args[]){
byte byteVar = 5;
short shortVar = 20;
int intVar = 30;
long longVar = 60;
float floatVar = 20;
double doubleVar = 20.123;
boolean booleanVar = true;
char charVar ='W';

[Link]("Value Of byte Variable is " + byteVar);


[Link]("Value Of short Variable is " + shortVar);
[Link]("Value Of int Variable is " + intVar);
[Link]("Value Of long Variable is " + longVar);
[Link]("Value Of float Variable is " + floatVar);
[Link]("Value Of double Variable is " + doubleVar);
[Link]("Value Of boolean Variable is " + booleanVar);
[Link]("Value Of char Variable is " + charVar);
}
}

Output:

Value Of byte Variable is 5


Value Of short Variable is 20
Value Of int Variable is 30
Value Of long Variable is 60
Value Of float Variable is 20.0
Value Of double Variable is 20.123
Value Of boolean Variable is true
Value Of char Variable is W

2. Manipulating String

(i) Converting String to Char

import [Link].*;
import [Link].*;
import [Link].*;

class StringToCharDemo
{
public static void main(String args[])
{
// Using charAt() method
String str = "Hello";
for(int i=0; i<[Link]();i++){
char ch = [Link](i);
[Link]("Character at "+i+" Position: "+ch);
}
}
}

Output:
Character at 0 Position: H
Character at 1 Position: e
Character at 2 Position: l
Character at 3 Position: l
Character at 4 Position: o

(ii) Reversing String:

import [Link].*;
import [Link].*;
import [Link].*;

public class Example


{
public void reverseWordInMyString(String str)
{
/* The split() method of String class splits
* a string in several strings based on the
* delimiter passed as an argument to it
*/
String[] words = [Link](" ");
String reversedString = "";
for (int i = 0; i < [Link]; i++)
{
String word = words[i];
String reverseWord = "";
for (int j = [Link]()-1; j >= 0; j--)
{
/* The charAt() function returns the character
* at the given position in a string
*/
reverseWord = reverseWord + [Link](j);
}
reversedString = reversedString + reverseWord + " ";
}
[Link](str);
[Link](reversedString);
}
public static void main(String[] args)
{
Example obj = new Example();
[Link]("Welcome to BeginnersBook");
[Link]("This is an easy Java Program");
}
}
Output:
Welcome to BeginnersBook
emocleW ot kooBsrennigeB
This is an easy Java Program
sihT si na ysae avaJ margorP

3. Various forms of inheritance

(i) Java program to illustrate the concept of single inheritance


import [Link].*;
import [Link].*;
import [Link].*;

class one
{
public void print_geek()
{
[Link]("Geeks");
}
}

class two extends one


{
public void print_for()
{
[Link]("for");
}
}
// Driver class
public class Main
{
public static void main(String[] args)
{
two g = new two();
g.print_geek();
g.print_for();
g.print_geek();
}
}

Output:
Geeks
for
Geeks

(ii) Java program to illustrate the concept of Multilevel inheritance


import [Link].*;
import [Link].*;
import [Link].*;

class one
{
public void print_geek()
{
[Link]("Geeks");
}
}

class two extends one


{
public void print_for()
{
[Link]("for");
}
}

class three extends two


{
public void print_geek()
{
[Link]("Geeks");
}
}

// Drived class
public class Main
{
public static void main(String[] args)
{
three g = new three();
g.print_geek();
g.print_for();
g.print_geek();
}
}

Output:
Geeks
for
Geeks
(iii) Java program to illustrate the concept of Hierarchical inheritance
import [Link].*;
import [Link].*;
import [Link].*;

class one
{
public void print_geek()
{
[Link]("Geeks");
}
}

class two extends one


{
public void print_for()
{
[Link]("for");
}
}

class three extends one


{
/*............*/
}

// Drived class
public class Main
{
public static void main(String[] args)
{
three g = new three();
g.print_geek();
two t = new two();
t.print_for();
g.print_geek();
}
}

Output:

Geeks
for
Geeks

(iv) Java program to illustrate the concept of Multiple inheritance


import [Link].*;
import [Link].*;
import [Link].*;
interface one
{
public void print_geek();
}

interface two
{
public void print_for();
}

interface three extends one,two


{
public void print_geek();
}
class child implements three
{
@Override
public void print_geek() {
[Link]("Geeks");
}

public void print_for()


{
[Link]("for");
}
}

// Drived class
public class Main
{
public static void main(String[] args)
{
child c = new child();
c.print_geek();
c.print_for();
c.print_geek();
}
}

Output:
Geeks
for
Geeks
4 (i) Polymorphism : Method overloading

import [Link].*;
import [Link].*;
import [Link].*;

class Rectangle{

public static void printArea(int x,int y){


[Link](x*y);
}
public static void printArea(int x){
[Link](x*x);
}
public static void printArea(int x,double y){
[Link](x*y);
}
public static void printArea(double x){
[Link](x*x);
}

public static void main(String[] args){


printArea(2,4);
printArea(2,5.1);
printArea(10);
printArea(2.3);
}
}

Output:
8
10.2
100
5.289999999999999

4 (i) Polymorphism : Method overriding


import [Link].*;
import [Link].*;
import [Link].*;

class Animals{
public void sound(){
[Link]("This is parent class.");
}
}
class Dogs extends Animals{
public void sound(){
[Link]("Dogs bark");
}
}
class Cats extends Animals{
public void sound(){
[Link]("Cats meow");
}
}
class Monkeys extends Animals{
public void sound(){
[Link]("Monkeys whoop.");
}
}
class m{
public static void main(String[] args){
Animals d = new Dogs();
Animals c = new Cats();
Animals m = new Monkeys();
[Link]();
[Link]();
[Link]();
}
}

Output:
Dogs bark
Cats meow
Monkeys whoop.

5. Exception Handling

(i) Java program to demonstrate Arithmetic Exception

import [Link].*;
import [Link].*;
import [Link].*;

class ArithmeticException_Demo
{
public static void main(String args[])
{
try {
int a = 30, b = 0;
int c = a/b; // cannot divide by zero
[Link] ("Result = " + c);
}
catch(ArithmeticException e) {
[Link] ("Can't divide a number by 0");
}
}
}
Output:
Can't divide a number by 0

(ii)Java program to demonstrate FileNotFoundException


import [Link];
import [Link];
import [Link];
class File_notFound_Demo {

public static void main(String args[]) {


try {

// Following file does not exist


File file = new File("E://[Link]");

FileReader fr = new FileReader(file);


} catch (FileNotFoundException e) {
[Link]("File does not exist");
}
}
}

Output:

File does not exist

6. Interfaces
import [Link].*;
import [Link].*;
import [Link].*;

interface Bank{
float rateOfInterest();
}
class SBI implements Bank{
public float rateOfInterest(){return 9.15f;}
}
class PNB implements Bank{
public float rateOfInterest(){return 9.7f;}
}
class TestInterface2{
public static void main(String[] args){
Bank b=new SBI();
[Link]("ROI: "+[Link]());
}}

Output:

ROI: 9.15
7. Packages

[Link]
package p1;
public class Student
{
int regno;
String name;
public void getdata(int r,String s)
{
regno=r;
name=s;
}
public void putdata()
{
[Link]("regno = " +regno);
[Link]("name = " + name);
}

[Link]

import p1.*;
class StudentTest
{
public static void main(String arg[])
{
student s=new student();
[Link](123,"xyz");
[Link]();
}
}

Output:
regno = 123
name = xyz

8. Multithreading

import [Link];
class A extends Thread
{
public void run()
{
[Link]("thread A is sterted:");
for(int i=1;i<=5;i++)
{
[Link]("\t from thread A:i="+i);
}
[Link]("exit from thread A:");
}
}
class B extends Thread
{
public void run()
{
[Link]("thread B is sterted:");
for(int j=1;j<=5;j++)
{
[Link]("\t from thread B:j="+j);
}
[Link]("exit from thread B:");
}
}
class C extends Thread
{
public void run()
{
[Link]("thread C is sterted:");
for(int k=1;k<=5;k++)
{
[Link]("\t from thread C:k="+k);
}
[Link]("exit from thread C:");
}
}
class Threadtest
{
public static void main(String arg[])
{
new A().start();
new B().start();
new C().start();
}
}

Output:

thread A is sterted:
thread B is sterted:
thread C is sterted:
from thread A:i=1
from thread B:j=1
from thread C:k=1
from thread A:i=2
from thread B:j=2
from thread C:k=2
from thread A:i=3
from thread B:j=3
from thread C:k=3
from thread A:i=4
from thread B:j=4
from thread C:k=4
from thread A:i=5
from thread B:j=5
from thread C:k=5
exit from thread A:
exit from thread B:
exit from thread C:

9 (i) java program to draw a ellipse using java applets

import [Link].*;
import [Link].*;

public class ellipse extends JApplet {

public void init()


{
// set size
setSize(400, 400);

repaint();
}

// paint the applet


public void paint(Graphics g)
{
// set Color for rectangle
[Link]([Link]);

// draw a ellipse
[Link](100, 100, 150, 100);
}
}

Output:
9(ii) Java Program to Draw a rectangle

import [Link].*;
import [Link].*;

public class rectangle extends JApplet {

public void init()


{
// set size
setSize(400, 400);

repaint();
}

// paint the applet


public void paint(Graphics g)
{
// set Color for rectangle
[Link]([Link]);

// draw a rectangle
[Link](100, 100, 200, 200);
}
}

Output:
9(iii) Java program to Draw a Smiley using Java Applet
import [Link].*;
import [Link].*;

public class Smiley extends Applet {


public void paint(Graphics g)
{

// Oval for face outline


[Link](80, 70, 150, 150);

// Ovals for eyes


// with black color filled
[Link]([Link]);
[Link](120, 120, 15, 15);
[Link](170, 120, 15, 15);

// Arc for the smile


[Link](130, 180, 50, 20, 180, 180);
}
}
Output:
9(iv) Handling Mouse Events Using java applet

import [Link].*;
import [Link].*;
import [Link].*;
public class MouseApplet extends Applet implements MouseListener
{
String msg="Initial Message";
public void init()
{
addMouseListener(this);
}
public void mouseClicked(MouseEvent me)
{
msg = "Mouse Clicked";
repaint();
}
public void mousePressed(MouseEvent me)
{
msg = "Mouse Pressed";
repaint();
}
public void mouseReleased(MouseEvent me)
{
msg = "Mouse Released";
repaint();
}
public void mouseEntered(MouseEvent me)
{
msg = "Mouse Entered";
repaint();
}
public void mouseExited(MouseEvent me)
{
msg = "Mouse Exited";
repaint();
}
public void paint(Graphics g)
{
[Link](msg,20,20);
}
}
/*
<applet code="MouseApplet" height="300" width="500">
</applet>
*/

Output:

10. (i) Window Based application using Java Swing

import [Link].*;
public class HelloWorldSwing {
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Make sure we have nice window decorations.
[Link](true);

//Create and set up the window.


JFrame frame = new JFrame("HelloWorldSwing");
[Link](JFrame.EXIT_ON_CLOSE);

//Add the ubiquitous "Hello World" label.


JLabel label = new JLabel("Hello World");
[Link]().add(label);

//Display the window.


[Link]();
[Link](true);
}

public static void main(String[] args) {


//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
[Link](new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}

Output:

10 (ii) Java program to create a frame using Swings in main().

import [Link].*;
public class Swing_example
{
public static void main(String[] args)
{
// creates instance of JFrame
JFrame frame1 = new JFrame();

// creates instance of JButton


JButton button1 = new JButton("click");
JButton button2 = new JButton("again click");

// x axis, y axis, width, height


[Link](160, 150 ,80, 80);
[Link](190, 190, 100, 200);

// adds button1 in Frame1


[Link](button1);

// adds button2 in Frame1


[Link](button2);

// 400 width and 500 height of frame1


[Link](400, 500) ;

// uses no layout managers


[Link](null);

// makes the frame visible


[Link](true);
}
}

Output:

Common questions

Powered by AI

Java supports single inheritance, which means that a class can inherit from only one other class. For example, class 'two' extends class 'one', allowing access to its methods, as seen in the output 'Geeks for Geeks' from invoking 'print_geek()' and 'print_for()' . Multilevel inheritance involves a class extending a class that is already derived from another class, like class 'three' extending 'two', which itself extends 'one'. The output 'Geeks for Geeks for Geeks' reflects the multilevel inheritance as 'three' inherits methods from both 'two' and 'one' .

In Java, data types such as 'int', 'float', 'double', etc., represent how data is stored and manipulated. For example, an 'int' data type is used to store integer values, which are whole numbers without a decimal. A 'float' can hold decimal numbers but with a precision that may lead to rounding errors, as seen in the example where 'floatVar' prints 20.0 . A 'double' has a double precision that allows it to store larger floating-point numbers with greater accuracy, leading to the output of 20.123 for 'doubleVar' . The variability in precision when using 'float' versus 'double' is crucial for calculations requiring high accuracy.

Method overloading and overriding are both manifestations of polymorphism in Java but differ fundamentally in their application type and scope. Overloading occurs at compile-time, allowing multiple methods with the same name but different parameters. It showcases Java's ability to process inputs differently based on signatures, such as the various 'printArea' methods . In contrast, method overriding is a runtime process where a subclass provides a specific implementation of a method declared in its superclass, such as different animal sounds like 'Dogs bark', encapsulating behavioral polymorphism for dynamic method execution .

Multithreading in Java facilitates concurrent execution of parts of a program to optimize CPU use and improve performance, especially for operations that can run independently. One such implementation involves extending the 'Thread' class and overriding the 'run' method, as seen with classes 'A', 'B', and 'C', each executing independently in parallel. This concurrent execution results in impressive time efficiency but introduces complexities like thread synchronization and potential race conditions. Example program outputs like 'thread A is started', 'thread B is started', demonstrate this concurrency . Interleaving outputs underscore the need for careful thread management to prevent data inconsistency.

Polymorphism in Java allows objects to be treated as instances of their parent class, enabling method behavior to be determined at runtime. Method overloading is a compile-time polymorphism example where the same method name has different parameters, such as different 'printArea' methods calculating and printing areas based on parameter types: int, double, etc. . Method overriding, a feature of runtime polymorphism, allows subclass methods to provide specific implementations of methods already defined in its superclass. This is seen in 'Dogs', 'Cats', and 'Monkeys' classes that override the 'sound()' method in 'Animals', each providing unique outputs like 'Dogs bark' .

Interfaces in Java are central for achieving multiple inheritance, where a class can implement more than one interface. Java avoids multiple inheritance of classes to prevent complexity but allows multiple interface inheritance. Interfaces define methods that a class must implement, allowing for shared characteristics across unrelated class hierarchies. For example, the 'child' class implements both interface 'one' and 'two' via 'three', demonstrating multiple inheritance with 'print_geek()' and 'print_for()' methods being used to output 'Geeks for Geeks' .

Java Swing provides a set of lightweight components for building window-based applications. A GUI application typically begins with creating a 'JFrame' instance, which serves as the main window. Within this frame, components like 'JButton' can be added for interaction. For example, a program can create a frame using 'JFrame frame1 = new JFrame();', then add buttons like 'JButton button1 = new JButton("click");' to the frame at specified coordinates using 'setBounds'. This creates an interactive interface with components arranged according to specified layout constraints, achieved without using layout managers for explicit positioning . These components are commonly packed into the frame using 'frame.setVisible(true)' to render them on screen.

Java applets are capable of creating interactive graphics directly within a browser or an applet viewer. Simple graphics like ellipses, rectangles, and smileys can be drawn using the 'Graphics' class methods within the applet's 'paint' method. For instance, an ellipse can be drawn using 'g.drawOval(100, 100, 150, 100)', resulting in an ellipse output . A smiley can be created using 'drawOval' for the face, 'fillOval' for the eyes, and 'drawArc' for the mouth, illustrating graphical capability with output that matches human expressions .

Java packages group related classes and interfaces to prevent naming conflicts, promote modularity, and enhance code reusability. They act as namespaces, allowing the organization of classes in a concise way. For example, a package 'p1' contains a class 'Student', which can be accessed in other classes via 'import p1.*'. This is evident as 'StudentTest' utilizes 'Student' class methods to neatly handle student data within its namespace . By using packages, developers mitigate risks of class name collisions and improve structured code development.

Exception handling in Java uses try-catch blocks to manage runtime errors and maintain program flow. For example, an 'ArithmeticException' occurs during arithmetic operations like division by zero. By placing the code within a try-block and catching the exception, as seen with 'int c = a/b;', the program can gracefully handle the error with output 'Can't divide a number by 0' . Similarly, a 'FileNotFoundException' happens when attempting to read non-existent files. The try-catch mechanism captures this with the output 'File does not exist', ensuring the program doesn’t crash .

You might also like