0% found this document useful (0 votes)
6 views17 pages

Java Programming Basics and Examples

The document contains Java code examples covering various programming concepts such as GUI creation, exception handling, inheritance, polymorphism, and data structures like ArrayList and HashMap. It includes examples of user input handling, event-driven programming, and file operations. The code demonstrates the use of classes, interfaces, and abstract classes in Java.

Uploaded by

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

Java Programming Basics and Examples

The document contains Java code examples covering various programming concepts such as GUI creation, exception handling, inheritance, polymorphism, and data structures like ArrayList and HashMap. It includes examples of user input handling, event-driven programming, and file operations. The code demonstrates the use of classes, interfaces, and abstract classes in Java.

Uploaded by

shakeela Naveed
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

//print square root

package jaava;
import [Link].*;
public class JAAVA{
public static void main(String[] args)
{
String s = [Link]("Enter Number: ");
int number = [Link](s);
int square = number * number;
[Link]("Number: " + number + "\nSquare: "+ square);
[Link](null,"Number: "+number+"\nSquare: " +
square);
}
}

// java class

package jaava;
import [Link].*;
class Display
{
public Display() {
[Link](null, "Hello, world!");
}
}
public class JAAVA{
public static void main(String[] args)
{
[Link]("hello"+"\t"+"world");
new Display();
}
}

//Wrapper class
package firstprogram;
import [Link].*;
public class FirstProgram{
public static void main(String[] args)
{
Integer num = new Integer(4);
int pnum = [Link]();
[Link](null, pnum);
}
}
//Lecture 3
package firstprogram;
import [Link].*;
public class FirstProgram{
public static void main(String[] args)
{
int num = 12;
String n = [Link](num);
[Link](null, num);
}
}
//Lecture 4: class with sette getter
package firstprogram;
import [Link].*;
class Student{
int rollno;
String name;
void setR()
{
rollno = 100;
}
void setN()
{
name = "shakila";
}
void getR()
{
[Link]("Roll no: " + rollno);
}
void getN()
{
[Link]("Name : " + name);
}
}
public class FirstProgram{
public static void main(String[] args)
{
Student s = new Student();
[Link]();
[Link]();
[Link]();
[Link]();
}
}

// commant to run this


cd C:\Users\[Link]\Desktop\FirstProgram
javac -d bin src\firstprogram\[Link]
java -cp bin [Link]

// Inheritence lecture 5
package firstprogram;
import [Link].*;
class Student{
int rollno;
String name;
Student()
{
rollno = 0;
name = "";
}
void setS()
{
name = "shakila";
rollno = 100;
}
void getS()
{
[Link]("Roll no: " + rollno);
[Link]("Name : " + name);
}
}
class Department extends Student
{
int deptId;
String debtName;
Department()
{
deptId = 0;
debtName = "";
}
void setD()
{
deptId = 1455;
debtName = "Computer Science";
}
void getD()
{
[Link]("Debt ID : " + deptId);
[Link]("Dept Name : " + debtName);
}
}
public class FirstProgram{
public static void main(String[] args)
{
Department D = new Department();
[Link]();
[Link]();
[Link]();
[Link]();
}
}

// polimorphism in java

package firstprogram;
import [Link].*;
class Student{
int rollno;
String name;
Student()
{
rollno = 0;
name = "";
}
void set()
{
name = "shakila";
rollno = 100;
}
void get()
{
[Link]("Roll no: " + rollno);
[Link]("Name : " + name);
}
}
class Department extends Student
{
int deptId;
String debtName;
Department()
{
deptId = 0;
debtName = "";
}
@Override
void set()
{
[Link]();
deptId = 1455;
debtName = "Computer Science";
}
@Override
void get()
{
[Link]();
[Link]("Debt ID : " + deptId);
[Link]("Dept Name : " + debtName);
}
}
public class FirstProgram{
public static void main(String[] args)
{
Student s = new Department(); // object ka reference parent class ka aure
creation child class li
[Link]();
[Link]();
}
}

// Using ArrayList

package firstprogram;
import [Link].*;
import [Link].*;
class Student{
int id;
String name;
Student(int i, String n )
{
id = i;
name = n;
}
void print()
{
[Link](id + " " + name);
}
}
public class FirstProgram{
public static void main(String[] args)
{
ArrayList al = new ArrayList();
Student s1 = new Student(12, "shakila");
Student s2 = new Student(13, "shagufta");
[Link](s1);
[Link](s2);
[Link]([Link]());
[Link]([Link]());
Student s = (Student)[Link](0);
[Link]();
s = (Student)[Link](1);
[Link]();

[Link](0); //s1 removed


[Link](s2); //s2 removed
[Link]([Link]());
[Link]([Link]());
[Link]();
}
}

// Using HashMap

package firstprogram;
import [Link].*;
import [Link].*;
class Student{
int id;
String name;
Student(int i, String n )
{
id = i;
name = n;
}
void print()
{
[Link](id + " " + name);
}
}
public class FirstProgram{
public static void main(String[] args)
{
HashMap h = new HashMap();
Student s1 = new Student(03234633, "asma\n");
Student s2 = new Student(98765, "Shakeela");
[Link]("One",s1);
[Link]("Two",s2);
[Link]([Link]());
[Link]([Link]());
Student s = (Student)[Link]("Two");
[Link]();
s = (Student)[Link]("One");
[Link]();
[Link]("One");
}
}

// Unchecked Exception

package firstprogram;
public class FirstProgram{
public static void main(String[] args)
{
//Unchecked Exception
try{
int a = 10;
int b = 0;
int div = a/b;
[Link](div);
}
catch(Exception e)
{
[Link]("Error: " + e);
}
}
}

//checked Exception
package firstprogram;
import [Link].*;
public class FirstProgram{
public static void main(String[] args)
{
//checked Exception
try{
FileReader fr = new FileReader("[Link]");
BufferedReader br = new BufferedReader(fr);
String line = [Link]();
[Link]("Line: " + line);
}
catch(IOException e)
{
[Link]("Error: " + e);
}
}
}

// Two or more Catch blocks


package firstprogram;
import [Link].*;
public class FirstProgram
{
public static void main(String[] args)
{
try{
FileReader fr = new FileReader("[Link]");
BufferedReader br = new BufferedReader(fr);
String line = [Link]();
[Link]("Line: " + line);
int i = [Link](line);
}
catch(NumberFormatException ne)
{
[Link]("Error: " + ne);
}
catch(FileNotFoundException fe)
{
[Link]("Error: " + fe);
}
catch(IOException e)
{
[Link]("Error: " + e);
}
finally{
[Link]("Always run");
}
}
}

//Print Stack track


// Two or more Catch blocks
package firstprogram;
import [Link].*;
public class FirstProgram
{
public static void main(String[] args)
{
try{
FileReader fr = new FileReader("[Link]");
BufferedReader br = new BufferedReader(fr);
String line = [Link]();
[Link]("Line: " + line);
int i = [Link](line);
}
catch(IOException e)
{
[Link]();
}
finally{
[Link]("Always run");
}
}
}

//Reading from File


package firstprogram;
import [Link].*;
public class FirstProgram
{
public static void main(String[] args)
{
FileReader fr = null;
BufferedReader br = null;
try{
fr = new FileReader("[Link]");
br = new BufferedReader(fr);
String line = [Link]();
while(line!=null)
{
[Link](line);
line = [Link]();
}
[Link]();
[Link]();
}
catch(IOException e)
{
[Link]();
}
}
}

//Writing to File
package firstprogram;
import [Link].*;
public class FirstProgram
{
public static void main(String[] args)
{
FileWriter fw = null;
PrintWriter pw = null;

try{
fw = new FileWriter("[Link]");
pw = new PrintWriter(fw);
String s1 = "Shakila";
String s2 = "Naveed";
[Link](s1);
[Link](s2);
[Link]();
[Link]();
[Link]("Record Saved");
}
catch(IOException e)
{
[Link]();
}
}
}

//Abstract classes (Khiyali plao)


// abstract class always parent class
package firstprogram;
abstract class Person {
abstract void takeInput();
abstract void displayOutput();
}

class Student extends Person {


int id;
String name;

@Override
public void takeInput() {
id = 100;
name = "Shakila";
}

@Override
public void displayOutput() {
[Link]("ID: " + id);
[Link]("Name: " + name);
}
}
public class FirstProgram
{
public static void main(String[] args)
{
Person p = new Student();
[Link]();
[Link]();
}
}

//Lecture 18

package javadifficult;
import [Link].*;
import [Link].*;
class myPanel extends JPanel
{
@Override
public void paintComponent(Graphics g)
{
[Link](g);
Graphics2D g2 = (Graphics2D) g;
[Link](20, 20, 20, 20);
[Link]([Link]);
[Link](50, 50, 20, 20);
[Link]("Hello world", 120, 50);
}
}
public class JavaDifficult {
public static void main(String[] args)
{
JFrame F = new JFrame();
myPanel P = new myPanel();
[Link]("MyPainting");
[Link](100, 100, 300, 300);
[Link]().setLayout(new BorderLayout());
[Link]().add(P);
[Link](true);
[Link](JFrame.EXIT_ON_CLOSE);
}
}

//Interface classes (Khiyali plao)


package firstprogram;
interface Person {
void takeInput();
void displayOutput();
}
class Student implements Person
{
int id;
String name;

@Override
public void takeInput() {
id = 100;
name = "Shakila";
}

@Override
public void displayOutput() {
[Link]("ID: " + id);
[Link]("Name: " + name);
}
}

public class FirstProgram


{
public static void main(String[] args)
{
Person p = new Student();
[Link]();
[Link]();
}
}

// GUI
package firstprogram;
import [Link].*;
import [Link].*;
public class FirstProgram{
public static void main(String[] args)
{
JFrame myFrame = new JFrame();
[Link](JFrame.EXIT_ON_CLOSE);
[Link]("My First GUI Project");
[Link](250, 250);
[Link](100, 200);
Container C = [Link]();
[Link](new FlowLayout());
JTextField TF = new JTextField("Enter Your Name: ");
JButton B = new JButton("Click here");
[Link](100,20);
[Link](75, 30);
[Link](TF);
[Link](B);
[Link](true);
}
}

// Event handling : ActionEvent


package firstprogram;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
public class FirstProgram implements ActionListener
{
void init()
{
JFrame myFrame = new JFrame();
[Link](JFrame.EXIT_ON_CLOSE);
[Link]("My GUI Application");
[Link](500, 300);
[Link](100, 100);
Container C = [Link]();
[Link](new FlowLayout());
JButton B = new JButton("Click here");
[Link](200, 50);
[Link](150, 150);
[Link](this);
[Link](B);
[Link](true);
}
@Override
public void actionPerformed(ActionEvent e)
{
[Link](null, "Button Clicked");
}
public static void main(String[] args)
{
FirstProgram Test = new FirstProgram();
[Link]();
}
}

// Event handling : MouseMotionEvent


package firstprogram;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
public class FirstProgram implements MouseMotionListener
{
JFrame myFrame;
JLabel L;
void init()
{
myFrame = new JFrame();
[Link](JFrame.EXIT_ON_CLOSE);
[Link]("My Title my marzi");
[Link](true);
[Link](100, 100);
[Link](500, 400);
Container C = [Link]();
[Link](new BorderLayout());
[Link](this);
L = new JLabel("Virtual University");
[Link](L, BorderLayout.PAGE_START);
}
@Override
public void mouseDragged(MouseEvent me)
{
int x = [Link]();
int y = [Link]();
[Link]("Mouse X-axis: " + x + "Mouse Y-axis: " + y);
}
@Override
public void mouseMoved(MouseEvent me)
{
int x = [Link]();
int y = [Link]();
[Link]("Mouse X-axis: " + x + "Mouse Y-axis: " + y);
}
public static void main(String[] args)
{
FirstProgram Test = new FirstProgram();
[Link]();
}
}

// Event handling : Windaw Adapter plus closing window


package firstprogram;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
public class FirstProgram extends WindowAdapter
{
JFrame myFrame;
void init()
{
myFrame = new JFrame();
[Link]("My GUI Application");
[Link](100, 100);
[Link](500, 400);
[Link](true);
[Link](this);
}
@Override
public void windowClosing(WindowEvent e)
{
[Link](null, "Good bye");
[Link](0);
}
public static void main(String[] args)
{
FirstProgram Test = new FirstProgram();
[Link]();
}
}

// Handling window event with inner classes


package firstprogram;

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

public class FirstProgram extends WindowAdapter {

JFrame myFrame;
JLabel L;
myClass1 t1;
myClass2 t2;

void init() {
myFrame = new JFrame();
[Link]("My GUI Application");
[Link](100, 100);
[Link](500, 400);

t1 = new myClass1();
t2 = new myClass2();

[Link](t1);
[Link](t2); // Corrected

Container C = [Link]();
[Link](new BorderLayout());

L = new JLabel("Shakila Naveed");


[Link](100, 200);
[Link](L, BorderLayout.PAGE_START);

[Link](true);
}

private class myClass1 extends WindowAdapter {


@Override
public void windowClosing(WindowEvent w) {
[Link](null, "Good Bye");
[Link](0);
}
}

private class myClass2 extends MouseMotionAdapter {


@Override
public void mouseMoved(MouseEvent m) {
int x = [Link]();
int y = [Link]();
[Link]("X-axis: " + x + " Y-axis: " + y);
}
}

public static void main(String[] args) {


FirstProgram Test = new FirstProgram();
[Link]();
}
}

// Handling window event with inner classes using anonimous class


package firstprogram;

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

public class FirstProgram {


JFrame myFrame;
JLabel L;

void init() {
myFrame = new JFrame();
[Link]("My GUI Application");
[Link](100, 100);
[Link](500, 400);

Container C = [Link]();
[Link](new BorderLayout());

L = new JLabel("Shakila Naveed");


[Link](100, 200);
[Link](L, BorderLayout.PAGE_START);

// Add window listener using anonymous inner class


[Link](new WindowAdapter() {
@Override
public void windowClosing(WindowEvent w) {
[Link](null, "Good Bye");
[Link](0);
}
});

// Add mouse motion listener using anonymous inner class


[Link](new MouseMotionAdapter() {
@Override
public void mouseMoved(MouseEvent m) {
int x = [Link]();
int y = [Link]();
[Link]("X-axis: " + x + " Y-axis: " + y);
}
});

[Link](true);
}

public static void main(String[] args) {


FirstProgram Test = new FirstProgram();
[Link]();
}
}

package javadifficult;

import [Link].*;

public class JavaDifficult {


public static void main(String[] args) {
try {
// Use double backslashes in the path for Windows
String url = "jdbc:ucanaccess://D:\\ssc\\shakeela downloads\\MidTerm
Prepration\\[Link]";

Connection con = [Link](url);


Statement st = [Link]();
String qry = "SELECT * FROM Person";
ResultSet rs = [Link](qry);
while ([Link]()) {
int id = [Link]("ID");
String name = [Link]("name");
String address = [Link]("address");
String phone = [Link]("PhoneNum");

[Link]("ID: " + id + " Name: " + name + " Address: " +


address + " Phone: " + phone);
}

[Link]();
} catch (Exception e) {
[Link]();
}
}
}

//Executing SQL DML Statements


package javadifficult;
import [Link].*;
public class JavaDifficult {
public static void main(String[] args) {
try{
String url = "jdbc:ucanaccess://D:\\ssc\\shakeela downloads\\MidTerm
Prepration\\[Link]";
Connection con = [Link](url);
Statement st = [Link]();
String qry = "INSERT INTO Person (name, address, phoneNum)
VALUES('khizar shahal', 'pakistan', '877665454343')";
int num = [Link](qry);
[Link](num + "Rows Affected");
[Link]();
}
catch(Exception e)
{
[Link]();
}
}
}

//Updatable resultset(): Use of previous ( ), next( ) & various getters methods


package javadifficult;
import [Link].*;
public class JavaDifficult {
public static void main(String[] args) {
try{
String url = "jdbc:ucanaccess://D:\\ssc\\shakeela downloads\\MidTerm
Prepration\\[Link]";
Connection con = [Link](url);
String qry = "SELECT * FROM Person";
PreparedStatement ps = [Link](qry,
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = [Link]();
[Link]();
[Link]();
[Link]("Move Forward");
String name = [Link]("name");
[Link]("Name: " + name);
[Link]();
name = [Link]("name");
[Link]("Name: " + name);
[Link]();
}
catch(Exception e)
{
[Link]();
}
}
}

//Lecture 16: Update methos


package javadifficult;
import [Link].*;
public class JavaDifficult {
public static void main(String[] args) {
try{
String url = "jdbc:ucanaccess://D:\\ssc\\shakeela downloads\\MidTerm
Prepration\\[Link]";
Connection con = [Link](url);
String qry = "SELECT * FROM Person";
PreparedStatement ps = [Link](qry,
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = [Link]();
[Link]();
String name = [Link]("name");
[Link]("Name: " + name);

}
catch(Exception e)
{
[Link]();
}
}
}

//Lecture 16: Absolute method


package javadifficult;
import [Link].*;
public class JavaDifficult {
public static void main(String[] args) {
try{
String url = "jdbc:ucanaccess://D:\\ssc\\shakeela downloads\\MidTerm
Prepration\\[Link]";
Connection con = [Link](url);
String qry = "SELECT * FROM Person";
PreparedStatement ps = [Link](qry,
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = [Link]();
[Link](3);
String name = [Link]("name");
[Link]("Name: " + name);

}
catch(Exception e)
{
[Link]();
}
}
}

//Lecture 16: Absolute method


package javadifficult;
import [Link].*;
public class JavaDifficult {
public static void main(String[] args) {
try{
String url = "jdbc:ucanaccess://D:\\ssc\\shakeela downloads\\MidTerm
Prepration\\[Link]";
Connection con = [Link](url);
String qry = "SELECT * FROM Person";
PreparedStatement ps = [Link](qry,
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = [Link]()
;
[Link](); // lASTS
[Link]("name", "Arooj Fatime");
[Link]("address", "mngalsingspace");
[Link]("phoneNum", "66545457");
[Link]();
[Link]("Row inserted");
[Link]();
}
catch(Exception e)
{
[Link]();
}
}
}

Common questions

Powered by AI

Encapsulation in Java is achieved by restricting direct access to some of an object's components and creating a controlled interface for others, typically using private fields and public getter/setter methods. This practice enhances data hiding and integrity by preventing indirect interactions that could corrupt the internal state. The document demonstrates encapsulation through a `Student` class with private fields `rollno` and `name`, coupled with setter methods `setR` and `setN`, and getter methods `getR` and `getN` to access these fields . This encapsulation approach ensures the internal state of the object is modified safely and predictably, promoting code reliability and modularity.

Polymorphism in Java allows objects to be treated as instances of their parent class, providing a unified interface to different types. This means a single function can operate on objects of different classes. This facilitates code reusability and flexibility in software design. In the document, polymorphism is demonstrated with an instance of a `Department` class being referenced using a `Student` class reference. This allows for overriding methods in `Department` to alter or extend the behavior of those methods from `Student` using the same reference . This design strategy reduces code redundancy and supports dynamic method invocation.

Collections like ArrayLists and HashMaps in Java offer flexible and efficient storage and management of groups of objects. ArrayLists provide dynamic arrays that can grow and shrink as needed, which is less memory-intensive than traditional arrays. HashMaps allow key-value pair storage, enabling fast retrieval of data based on keys. The document illustrates the use of an ArrayList to store and manage `Student` objects dynamically, allowing operations like addition, removal, and checking the list's emptiness or size . Similarly, a HashMap example demonstrates storing `Student` objects with string keys, simplifying the retrieval and management of entries . These collections are vital for organizing complex data structures efficiently.

Inner classes in Java GUIs, particularly anonymous inner classes, facilitate concise event handling by allowing the rapid implementation of listener interfaces within GUI code. Inner classes provide encapsulation and can simplify otherwise complex event listeners. The document describes using anonymous inner classes to add event listeners directly to GUI components like buttons and window adapters. This approach encapsulates the event handling logic with the components they relate to, enhancing code manageability. An example in the document illustrates these listening mechanisms for tracking mouse movements and handling window close events . This structure promotes cleaner and more modular code organization.

Java Database Connectivity (JDBC) involves creating a connection to a database using connection URLs and executing SQL queries to retrieve or modify data. In the document, `DriverManager.getConnection` is used to connect to a Microsoft Access database, exemplifying how to execute a SQL query to select all rows from a "Person" table using `Statement.executeQuery`, and further navigate the `ResultSet` with methods like `next()` and `getString()` . JDBC allows dynamic interaction with database systems, providing a platform-independent interface to various databases and supporting operations such as data retrieval, updates, and transaction management.

A GUI application in Java is constructed using components from `javax.swing` and `java.awt` libraries. The `JFrame` class provides the window on which to build the application. Within it, various components like `JButton`, `JLabel`, and `JTextField` can be added, managed with layout managers like `FlowLayout` or `BorderLayout`. The document showcases constructing a simple GUI with a `JFrame` titled "My First GUI Project", containing a text field and button integrated into a flow layout . Event listeners such as `ActionListener` can be attached to the components for interactivity, responding to user actions like button clicks.

Abstract classes in Java provide a way to define methods that can be shared by all classes inheriting from them, while also allowing for method modification or specific implementations in these subclasses. They serve as a blueprint for creating concrete classes, ensuring that derived classes implement these methods. This structure supports design patterns such as Template Method, where an abstract class defines the skeleton of an algorithm using abstract methods, allowing subclasses to fill in the details. In the document, an abstract class "Person" is used to enforce structure on the "Student" class .

Exception handling in Java is crucial for managing runtime errors, allowing the program to continue execution instead of crashing. It involves using `try`, `catch`, `finally`, and `throw` constructs to handle errors gracefully. The document discusses multiple examples, such as handling unchecked exceptions like division by zero and checked exceptions like file reading errors. For instance, while dividing a `10` by `0`, a generic exception is caught to print an error message . This method helps ensure that programs can handle exceptions, provide user-friendly feedback, and maintain system stability.

In Java, inheritance is implemented using the `extends` keyword that allows one class to inherit fields and methods from another. This promotes code reusability by allowing common functionality in a base class to be shared with subclasses. In the provided sources, the `Department` class extends the `Student` class to inherit properties like name and roll number and adds department-specific properties . However, inheritance can introduce issues such as tight coupling between classes, making code maintenance challenging, and potential hierarchy complexity if not properly managed, which can lead to the fragile base class problem where changes in the base class affect derived classes unexpectedly.

Interfaces in Java provide a mechanism to achieve abstraction and multiple inheritance. They declare methods that a class must implement, promoting a separation of definition from implementation. In an interface, methods are abstract by default, without any implementation. In the document, the "Person" interface requires implementing classes, like "Student," to define methods `takeInput` and `displayOutput` . Unlike abstract classes, interfaces cannot hold method implementations (before Java 8) and do not maintain any state (fields with values). Additionally, interfaces enable a class to implement multiple interfaces, allowing flexible design and promoting interfaces over inheritance where feasible.

You might also like